<?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 Robert Felkins on Medium]]></title>
        <description><![CDATA[Stories by Robert Felkins on Medium]]></description>
        <link>https://medium.com/@robert_84835?source=rss-1a5e3f553f20------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MQp0fKF84gSSobhURxd6ow.png</url>
            <title>Stories by Robert Felkins on Medium</title>
            <link>https://medium.com/@robert_84835?source=rss-1a5e3f553f20------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 17:12:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@robert_84835/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[Architecture-Powered Claude Engineering: The Judgment Under the Toolkit]]></title>
            <link>https://medium.com/@robert_84835/architecture-powered-claude-engineering-the-judgment-under-the-toolkit-3f5b9456a7fc?source=rss-1a5e3f553f20------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f5b9456a7fc</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Robert Felkins]]></dc:creator>
            <pubDate>Sun, 19 Jul 2026 11:14:28 GMT</pubDate>
            <atom:updated>2026-07-19T11:14:28.230Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*imIODWGqzGlQ1OzDtsd5ZA.png" /></figure><p><em>Everyone’s racing to write a </em><em>CLAUDE.md and a folder of skills. But those files are containers — what goes in them is architectural judgment, and if the judgment is wrong, you&#39;ve just automated a mistake five times faster. I built a five-service event-driven job board with Claude Code, and the </em><em>.claude/ toolkit isn&#39;t the achievement. The architecture that authored it is. Hand the same tools to someone without that experience, and you get a plausible alpha. With it, you get something you&#39;d actually push.</em></p><p>There’s a lot of excitement right now about moving AI discipline into the repository — CLAUDE.md files, rules, skills, subagents, hooks. I&#39;m all for it; I do it, and I&#39;ll show you exactly how below. But there&#39;s a quiet assumption beneath the excitement that&#39;s worth bringing to light: <strong>that the toolkit is the hard part.</strong> It isn&#39;t. Writing a rule that says &quot;no shared database&quot; takes thirty seconds. <em>Knowing</em> that rule is load-bearing — knowing the eleven other boundaries that matter, in what order to prove them, and what breaks in production if you get one wrong — is the work of years. The file is easy. The judgment inside it is not.</p><p>That’s the whole thesis of this post, and the reason I frame what I do as <strong>Architecture-Powered Claude Engineering</strong> rather than just Claude engineering. The public proof is at <a href="https://github.com/architect4hire/jobboard">github.com/architect4hire/jobboard</a>: a genuinely functional job board built as five bounded .NET services behind one gateway, an Angular front end, an event bus, all orchestrated locally by Aspire, driven agentically with Claude Code. The .claude/ toolkit that drives it is real, and it&#39;s good. But it&#39;s <em>downstream</em>. It&#39;s architectural experience compiled into a form an agent can execute — and it&#39;s only as good as the architecture it encodes.</p><h3>The tool is neutral. The judgment is not.</h3><p>Here’s the uncomfortable part for anyone selling “just add a CLAUDE.md and go.”</p><p>Claude Code will happily encode a <em>bad</em> architecture as faithfully as a good one. Ask it to build a job board with no guardrails, and it produces plausible code — code that compiles, demos, and looks right in the diff. Plausible is not correct. In a distributed system, plausible-but-wrong is where the money leaks out: the agent helpfully opens a second database connection to grab data it needs, and now two services share a table, and you have a distributed monolith wearing a microservices costume. It passes review if the reviewer doesn’t know what they’re looking at. I call this the Plausibility Trap, and no amount of tooling closes it — because the tool has no opinion about whether your boundaries are right. It just executes.</p><p>So the interesting question was never <em>whether</em> Claude Code could build a microservice system. It’s: <strong>can it build one that behaves correctly when things go wrong, without the architecture drifting</strong> — and the answer to that lives entirely in the judgment you feed it. That’s the experience I’m actually selling. Not “I know how to write a rules file.” Anyone can. I know <em>which</em> rules are worth writing, because I’ve watched the alternatives fail in production. As my application-development service puts it: I don’t just draw the architecture — I build in it, so the design and the code never drift apart. This is how I build the toolkit now. The architecture is why the toolkit is right.</p><h3>Trace one decision, and you’ll see where the value is</h3><p>Take the single most important rule in the whole repo: <strong>no shared database, ever. A service reads and writes only its own database.</strong> Watch where that rule actually comes from, because the origin is the point.</p><p>It does not start in the .claude/ folder. It starts as a <em>decision</em>, reasoned out in the High-Level Design and recorded in an Architecture Decision Record — ADR-0001, database-per-service — with its context, its consequences, and the alternatives I rejected and why. That ADR exists because I&#39;ve lived the failure it prevents: two services quietly coupled through a shared table, evolving independently right up until the day one migration takes them both down. The judgment is: <em>pay the cost of duplicating a little reference data now, or pay for a rewrite later.</em> That&#39;s not a preference. It&#39;s a scar.</p><p><em>Only then</em> does it become tooling. The decision becomes a rule that the agent loads when it touches a service. It turns into a subagent that reviews for the violation. It turns into a compiler-enforced reference graph — the project references are one-way and acyclic, Contracts ← Shared ← Service.Core ← Service host ← AppHost, so a service reaching sideways into another is a <em>build error</em>, not a code-review conversation. I checked the repo: no service&#39;s .Core references another&#39;s. Not because everyone remembered to be careful — because the architecture made carelessness impossible.</p><p>That’s the chain that matters: <strong>experience → decision → record → guardrail → enforcement.</strong> The .claude/ folder is the last two links. The first three are the architect. Remove the architect and the chain still runs — it just encodes whatever plausible thing the agent invented, and enforces <em>that</em> with the same mechanical rigor. You&#39;d get a beautifully automated, ruthlessly consistent mistake.</p><h3>The toolkit is architecture, encoded four ways</h3><p>With that framing, here’s what’s in the .claude/ folder — and notice that every layer is a <em>decision an experienced architect made</em>, not a clever use of a feature.</p><p><strong>Rules</strong> are the conventions the agent should <em>know</em>, and they’re path-scoped so they load exactly when relevant — five of them (aspire.md, backend.md, frontend.md, gateway.md, messaging.md). Touch a service, the layered-architecture rules load; touch the bus, the outbox-and-idempotency rules load. But the layered architecture those rules describe — thin host plus a .Core library, facade → business → data → repository, ViewModel in and ServiceModel out — is ADR-0005&#39;s judgment. The rule is just its enforcement. A different architect&#39;s rules file would describe a different architecture, and the agent would obey it just as well. The rule is only as good as the layering it encodes.</p><p><strong>Skills</strong> are procedures the agent should <em>follow</em> when a task matches — and the crown jewel, add-endpoint, encodes the single most error-prone operation in this architecture. Adding a REST endpoint here is a lot of correct steps in a specific order: pick the owning service, build the full controller → facade → business → data → repository slice, enqueue the integration event on the outbox <em>atomically in the same transaction as the write</em>, add the gateway route, wire the DI, write the tests. That ordering is architectural knowledge. The skill fires and the agent does it right every time — but only because someone who knew the right way wrote the skill. Hand the same skill mechanism to someone who thinks a fat controller is fine, and it&#39;ll reproduce a fat controller with perfect consistency.</p><p><strong>Subagents</strong> are work to <em>delegate</em>, and I keep all three strictly read-only on purpose — code-reviewer, test-gap-analyzer, api-contract-checker. They report; they never touch code. And what they hunt for is not generic — it&#39;s the specific mistakes <em>this</em> architecture is prone to. The test-gap analyzer flags a consumer with no idempotency test, because at-least-once delivery means that callback <em>will</em> fire twice and a handler that isn&#39;t safe to run twice is a latent double-effect bug. Knowing that&#39;s the test that matters is the judgment. The subagent is just where I parked it.</p><p><strong>Hooks</strong> are the non-negotiables — the things that happen whether the agent decides to or not — and there are two. secret-guard.sh runs <em>before</em> every edit and physically blocks anything credential-shaped from being written, no matter how I prompt or how tired I am. format.sh formats every touched file after the fact. Rules ask. Hooks enforce. Deciding <em>which</em> invariants deserve a hook instead of a rule — which things must be true versus merely encouraged — is, again, an architectural call.</p><p>Rules teach, skills guide, subagents check, hooks enforce. Four ways to encode a decision. But the encoding is the easy 20%. The decisions are the 80% you’re hiring an architect for.</p><h3>SCRUB: how I serialize judgment into something an agent can run</h3><p>The connective tissue is a discipline I’ve used for months: <strong>SCRUB</strong> — Scope, Constraints, Restrictions, Usage, Behavior. It started as a way to write a good prompt. What it really is, I’ve come to understand, is a <em>format for transferring architectural judgment into an executable form</em>. Scope names what’s in and out of bounds. Constraints pin the stack and conventions. Restrictions are the hard <em>do-NOTs</em>. Usage points at the right tool. Behavior demands a plan before any change.</p><p>The JobBoard’s CLAUDE.md — the constitution loaded every session — is itself written as a SCRUB prompt, because the constitution <em>is</em> architecture. Its Scope declares that adding a service is an architectural decision, not a feature: &quot;propose it, don&#39;t scaffold it.&quot; Its Restrictions are the load-bearing rulings — no shared database, the gateway is the only public door, publish through the outbox in the same transaction, consumers are idempotent. Every one of those is a decision with an ADR behind it. SCRUB is just the grammar that lets me hand those decisions to an agent without losing their meaning, and diagnose exactly which one failed when something goes wrong.</p><h3>Alpha versus polished — which is the whole pitch</h3><p>Here’s the contrast I most want a client to hold onto, because it’s the value stated plainly.</p><p>Give Claude Code to a competent developer with no distributed-systems architecture background, and you’ll get an <strong>alpha</strong>: a working, demoable job board that looks finished. Post a job, apply, watch a status change — it all works on the happy path. And it’s quietly wrong at every seam. A declined payment leaves stock reserved because there’s no compensation path. A redelivered message is double-processed because the consumer isn’t idempotent. Two services share a table because that was the plausible way to get the data. The design and the code drift apart the day after the build ships, because nothing was recording <em>why</em> anything was done. It’ll get to about ninety percent and stall there forever, because the last ten percent is all the correctness-under-failure work that doesn’t show up in a demo.</p><p>Give an architect the <strong>same tools</strong>, and the guardrails carry the experience the developer didn’t have. The outbox and idempotent inbox make it correct under partial failure — no lost events, no double effects — by design, not by luck. The acyclic references keep the boundaries safe, enforced by the compiler. The ADRs and developer docs keep the design and the code locked together so nothing drifts. That’s the difference between an alpha and something you’d push: not the toolkit, which is identical in both cases, but the judgment the toolkit is carrying. <strong>The architecture is what turns “it runs” into “it’s ready.”</strong></p><p>And there’s a document ecosystem that keeps it that way, each link feeding the next: the design (the high level design and its C4 diagrams) reasons out the decisions; the decisions become the .claude/ guardrails; the guardrails drive Claude Code to produce the src/; the output is recorded in twelve ADRs; and the ADRs are explained to the next human in developer docs — an add-an-endpoint-by-hand walkthrough, a seed-data guide, an ongoing architecture review with a ranked risk table. Design → guardrails → code → record → explanation, kept deliberately in sync, because a design that&#39;s drifted from its code is worse than no design at all. That closed loop is the deliverable. The job board is just the proof it works.</p><h3>The contrarian bit: I barely write prompts anymore</h3><p>Here’s what surprises people. Once the architecture is encoded, I mostly stop writing prompts. The rules auto-load, the skills carry the procedures, the subagents catch the drift, the hooks enforce the invariants — so day-to-day work needs nothing more than “add a withdraw-application endpoint,” because the repository already knows what “endpoint” means here and which service owns applications.</p><p>But read that carefully, because the reason I <em>can</em> stop prompting is not that the tooling is clever. It’s that <strong>the architecture is doing the constraining.</strong> The leverage was never the automation. It was the judgment the automation carries.</p><p>Prompt engineering optimizes the prompt; architecture-powered Claude engineering makes the prompt unnecessary — by building years of hard-won structural decisions into the repo once, so they’re paid forward on every task without me re-typing a single one.</p><h3>What the architecture experience buys a business</h3><p>I work with two kinds of decision-makers, often in the same room. So, plainly:</p><ul><li><strong>Polished, not alpha.</strong> You get the ninety-to-a-hundred percent that the correctness-under-failure work represents — the part a toolkit alone never reaches.</li><li><strong>Correct when it counts.</strong> Compensation on every failure path, idempotent consumers, safe boundaries — stated as outcomes: partial-order incidents at zero, double-effects at zero, oversells at zero.</li><li><strong>No drift.</strong> The design, the code, and the reasoning stay locked together, enforced by the compiler and the hooks, so the system six months out still matches the diagram.</li><li><strong>Cheap onboarding.</strong> A new engineer reads the ADRs and developer docs and is productive in an afternoon, not a month.</li><li><strong>You own all of it.</strong> SCRUB is a discipline, not a dependency. No proprietary framework to keep paying for. Clone it, run it, keep it.</li></ul><h3>The honest part</h3><p>Let me label the scaffold as a scaffold, because I always do. JobBoard is a reference build — a spike. It runs entirely on local Aspire-orchestrated containers at zero cloud spend, talking to the real Azure Service Bus SDK through an emulator; going live is a configuration and DevOps change, not a rewrite, but it <em>is</em> a change I haven’t made here. Two of the twelve ADRs are still marked <em>Proposed</em>, not Accepted — the cross-service read-model strategy is named as a pending decision, not pre-built, because pretending to have solved it would be a dishonest move.</p><p>And the standing advice in the toolkit is <em>verify before trusting</em>: Aspire, the Service Bus emulator, YARP, and Claude Code all ship fast, so confirm the exact API names against the live docs before you lean on them. That caveat is in the repository, in writing, because a scaffold that lies about its completeness is worse than useless.</p><h3>Where this starts</h3><p>If your team has adopted an AI coding assistant and it keeps producing plausible-but-wrong output — code that demos and then drifts, an architecture that erodes a little with every generated file, a build that’s perpetually ninety percent — the missing piece isn’t a better tool. You already have the tool. The missing piece is the architectural judgment that tells the tool what “right” is, and encodes it so it holds.</p><p>That’s the work I do: <a href="https://www.architect4hire.com/services/application-development">architect4hire.com/services/application-development</a>. Read the repo first — <a href="https://github.com/architect4hire/jobboard">github.com/architect4hire/jobboard</a> — and the SCRUB framework in full at <a href="https://www.architect4hire.com/scrub">architect4hire.com/scrub</a>. Then, if it’s the shape of what your team needs, reach out at <a href="/service/mailto:robert@architect4hire.com">robert@architect4hire.com</a>. Fractional or contract, the first conversation is the same: what you’re trying to build, and whether I’m the right person to help you build it. If I’m not, I’ll tell you.</p><p><em>Robert Felkins is the principal architect at Architect4Hire — Chicago-based fractional and contract architecture for small and mid-sized teams. I design right-sized .NET and Azure systems, modernize the ones you already have, and bring AI-assisted development into teams in a way that survives contact with production: senior judgment without the full-time price tag. Reach me at </em><a href="/service/mailto:robert@architect4hire.com"><em>robert@architect4hire.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f5b9456a7fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Prompt Engineering to Claude Engineering: How SCRUB Moved Out of the Chat Window and Into the…]]></title>
            <link>https://medium.com/@robert_84835/from-prompt-engineering-to-claude-engineering-how-scrub-moved-out-of-the-chat-window-and-into-the-4baaab34af98?source=rss-1a5e3f553f20------2</link>
            <guid isPermaLink="false">https://medium.com/p/4baaab34af98</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[ai-assisted-coding]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[claude-code]]></category>
            <dc:creator><![CDATA[Robert Felkins]]></dc:creator>
            <pubDate>Fri, 17 Jul 2026 13:12:11 GMT</pubDate>
            <atom:updated>2026-07-17T13:12:11.192Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nrCBzaU-GtBbOYrOwHSFLg.png" /></figure><h3>From Prompt Engineering to Claude Engineering: How SCRUB Moved Out of the Chat Window and Into the Repo</h3><p><em>I used to write the whole SCRUB discipline into every prompt, every time. Then I built a repo where the discipline lives in the codebase instead — a </em><em>CLAUDE.md constitution, path-scoped rules, on-demand skills, read-only subagents, and hooks that fire no matter what the agent decides. It&#39;s public. You can clone it and read every piece.</em></p><p>There’s a repo on my GitHub called <a href="https://github.com/architect4hire/claudebox">ClaudeBox</a>, and its tagline is the most honest thing on the whole account: “a sandbox where Claude Code does the heavy lifting and I take the credit.” Inside it is RecipeBox — a full-stack recipe app built with Aspire, ASP.NET Core, and Angular, orchestrated entirely on your laptop with no cloud spend. Boot it with aspire run and the dashboard comes up with logs, traces, and health for every resource.</p><p>But the app isn’t the point. Or rather — it’s exactly half the point. The other half is the .claude/ folder sitting next to it, because that folder is the record of a shift I&#39;ve been making in how I work: I stopped writing prompts and started engineering Claude.</p><p>Let me explain what that sentence actually means, because it’s not a cute reframe. It’s a different job.</p><h3>First, the honest part</h3><p>RecipeBox is a scaffold. It’s a genuinely good app — layered, tested, properly wired — but it’s built to be cloned and continued, with deliberate seams where the exercises begin. The README says, in as many words, to verify the exact Aspire commands and API names against the docs, because Aspire ships fast and some surface changes occur between versions. I’d rather label a real 90% honestly than sell you a polished 100% that doesn’t survive git clone.</p><p>I build these on purpose. “I do disciplined AI-assisted development” is a claim, and claims are free. A repo you can clone, read, and run is a different kind of evidence — it shows the process, the guardrails, the trade-offs, and the seams. If you’re evaluating whether I actually know how to drive an agent through a real .NET stack, that folder will tell you more in ten minutes than this entire post will. Go read it. Then come back, and I’ll tell you what it’s doing.</p><h3>The old way: SCRUB as a tax you pay every prompt</h3><p>If you’ve read anything else I’ve written, you know <a href="https://www.architect4hire.com/scrub">SCRUB</a>. It’s my five-part discipline for AI-assisted coding — <strong>S</strong>cope, <strong>C</strong>onstraints, <strong>R</strong>estrictions, <strong>U</strong>sage, <strong>B</strong>ehavior — and the idea is to apply all five to every prompt, every time. Each element names exactly which class of bug you invite when you skip it. Skip Scope, and the AI builds the wrong thing. Skip Constraints, and it builds the right thing in the wrong patterns. Skip Restrictions — the star of the framework — and you get the Plausibility Trap: code that compiles, looks idiomatic, passes its tests, and is quietly wrong in a way only domain knowledge catches.</p><p>SCRUB works. I’ll defend it on,” “thin controllers, DTOs at the boundary,restating your entire architecture from memory into a chat box a whiteboard all day. But here’s the thing nobody puts on the slide: writing all five elements into every prompt is a <em>tax</em>. By the twentieth prompt of a build, you are typing “Do NOT hardcode connection strings” and “thin controllers, DTOs at the boundary” and “plan before you touch more than one file” for the twentieth time. You are re-stating your entire architecture, from memory, into a chat box, at the exact moment your attention should be on the actual problem.</p><p>And the tax has a nasty failure mode. The one time you’re tired, or in a hurry, or halfway through a debugging spiral at 6 pm, you skip the Restrictions block “just this once” — and that’s the prompt that commits a secret or oversells the last unit or defaults the tip to 20%. The discipline is only as good as your worst moment of remembering to apply it.</p><p>So I asked the obvious question. If SCRUB is five elements I apply every single time — what if they didn’t have to live in the prompt at all?</p><h3>The shift: every SCRUB element has a home in the repo</h3><p>Here’s the move, and it’s the whole post in one table. Each of the five SCRUB elements has a natural home somewhere in a Claude Code project — a place where it can live <em>once</em>, load itself when relevant, and stop being something I retype:</p><p>SCRUB element Where it lives now What it becomes <strong>Scope</strong> a <strong>skill</strong> in .claude/skills/ a procedure the agent follows when a task matches <strong>Constraints</strong> a <strong>rule</strong> in .claude/rules/ + CLAUDE.md conventions that auto-load by file path <strong>Restrictions</strong> a <strong>hook</strong> in .claude/hooks/ a guardrail that fires no matter what the agent decides <strong>Usage</strong> CLAUDE.md (the constitution) the operating context, read every session <strong>Behavior</strong> CLAUDE.md + <strong>subagents</strong> how work proceeds; what gets delegated read-only</p><p>The .claude/README.md in the repo states the same idea as a rule of thumb, and it&#39;s worth memorizing: a <strong>rule</strong> (or CLAUDE.md) is something Claude should <em>know</em>; a <strong>skill</strong> is a procedure Claude should <em>follow</em> when a task matches; a <strong>subagent</strong> is work Claude should <em>delegate</em> to keep the main context clean; and a <strong>hook</strong> is something that must happen <em>no matter what Claude decides</em>.</p><p>Read that last one twice. “No matter what Claude decides.” That is a Restriction that has stopped being a polite request in a prompt and become a physical property of the repository. That’s the difference between asking and enforcing — and it’s the whole reason this shift is worth making.</p><p>Let me walk each home with the actual artifacts.</p><h3>CLAUDE.md is a SCRUB prompt wearing a suit</h3><p>Open the CLAUDE.md at the root of RecipeBox, and here is its opening line, verbatim: <em>project memory, written as a SCRUB prompt — Scope, Constraints, Restrictions, Usage, Behavior. Loaded every session.</em></p><p>The file has those exact five headers. The constitution of the entire project <em>is</em> a SCRUB prompt — one I wrote once, that Claude Code auto-discovers by walking up from the working directory, and that survives a /compact. The Scope section says what&#39;s in bounds and, more importantly, what&#39;s out of bounds (don&#39;t build i18n unprompted). The Constraints section pins the stack — Aspire 13 on .NET 10, ASP.NET Core, EF Core on Npgsql, Angular standalone components — and the canonical commands to use verbatim. The Restrictions section says don&#39;t hardcode connection strings, don&#39;t put business logic in the AppHost, don&#39;t run ng serve by hand. Usage describes the world (everything&#39;s local, services find each other through discovery). Behavior sets the working rhythm: plan before touching more than one file, wait for approval, use the matching skill instead of freelancing.</p><p>The payoff is a line I’m quietly proud of: because every rule has one obvious home under one of five headers, <em>every misstep is diagnosable by section</em>. When the agent does something wrong, I don’t wonder what went wrong in the ether — I ask which SCRUB element failed, and the fix goes back into that section. The prompt framework became the debugging framework. That’s not a coincidence I planned; it’s what happens when your discipline has structure.</p><h3>Constraints that load themselves: rules</h3><p>Typing your architecture conventions into every prompt is the single most repetitive part of the old tax. So they moved into .claude/rules/, and the trick is that rules are <strong>path-scoped</strong>. backend.md carries a little header declaring it applies to src/RecipeBox.ApiService/**. It loads into context <em>only</em> when Claude touches the API — thin controllers, DTOs at the boundary, DbContext via the Aspire integration, async all the way down, validate at the edge. frontend.md loads only for the Angular app. aspire.md loads only for the AppHost.</p><p>This is the Constraints element of SCRUB, except it now costs me zero keystrokes and — better — it can’t bleed. The backend conventions don’t clutter the context when Claude is writing an Angular component. The right rules show up for the right files, automatically, and the prompt that used to carry three paragraphs of “here’s how my codebase works” carries none.</p><h3>Scope frozen into a procedure: skills</h3><p>The add-endpoint skill is my favorite artifact in the repo because it&#39;s a whole SCRUB prompt frozen solid into a reusable procedure. RecipeBox has nine skills in .claude/skills/ (three I authored — add-endpoint, new-component, add-aspire-resource — plus six vendored Aspire and Playwright ones kept as-shipped so they can be re-vendored). But add-endpoint is the one that fully illustrates the idea.</p><p>It encodes the entire layered architecture of the API as a step-by-step playbook: controller → facade → business → data layer → repository, each with strict, non-negotiable responsibilities. The controller does HTTP only. The facade owns validation and caching. The business layer translates ViewModel to domain, applies domain rules, and maps domain back to a ServiceModel. The data layer composes repository calls into whole operations and owns the transaction boundary. The repository does EF queries and nothing else. There’s a checklist at the bottom — sixteen boxes — that the agent ticks before it calls the work done.</p><p>That skill is Scope, Constraints, Restrictions, and Behavior all at once, written once, that I never type again. When I say “add an endpoint to list recipes by category,” the skill loads on its own and the agent builds it <em>my</em> way, down to which layer is allowed to touch the DbContext. The scrub-prompts doc in the repo says it best: when you reuse a prompt two or three times, promote it to a skill so you stop needing the prompt at all. That&#39;s the asymptote this whole approach bends toward — <strong>the best SCRUB prompt is the one you never have to write, because its scope already lives in a skill.</strong></p><h3>Restrictions that can’t be forgotten: hooks</h3><p>This is where the shift stops being a convenience and starts being a genuinely different guarantee.</p><p>In the old model, “Do NOT commit secrets” is a line in a Restrictions block — a request the agent honors if you remembered to write it and it remembered to obey. In RecipeBox, that Restriction is a file: .claude/hooks/secret-guard.sh, wired as a PreToolUse hook. Before any edit or write lands, the hook scans the payload for anything credential-shaped — an API key pattern, an AWS access-key ID, a PEM private-key header, a password literal, a Postgres or Redis URL with inline credentials — and if it matches, it exits with code 2. Exit 2 means deny. The edit does not happen. The message it prints back is a small act of teaching: use Aspire-injected config, not literals.</p><p>Read what that changes. The secret guard doesn’t ask Claude to be careful. It doesn’t depend on my worst-moment discipline or the agent’s mood. It fires <em>no matter what the agent decides</em>, on every single edit, deterministically, forever. It is the Restrictions element of SCRUB — the star of the framework — turned from a sentence into a law of physics for this repo. The tired-developer-at-6 pm failure mode I described earlier? The one prompt where you skip the guardrail “just this once”? It can’t happen here because the guardrail isn’t in the prompt anymore.</p><p>There’s a second hook, format.sh, wired as PostToolUse: after every edit, it formats the file — dotnet format for C#, the Angular app&#39;s own pinned Prettier for the frontend — and it&#39;s written carefully to never block an edit even if the formatter is missing. That&#39;s the Behavior element made automatic. Consistency stops being something I nag about in review and becomes something that already happened before I looked.</p><h3>Behavior you delegate: subagents</h3><p>The last home is for the work you want done <em>without</em> polluting your main context. RecipeBox has four read-only subagents in .claude/agents/: a code-reviewer that checks a diff against the repo&#39;s conventions and reports blockers, suggestions, and nits; a test-gap-analyzer; an api-contract-checker that hunts for drift between the API&#39;s boundary types and the Angular models that mirror them; and a skills-evals agent that audits whether generated code actually followed the skills.</p><p>The critical design choice: they are all <strong>read-only</strong>. Their frontmatter grants Read, Grep, Glob, and Bash — and Bash only for read-only inspection like git diff. They report; they never edit. That&#39;s a Behavior restriction from CLAUDE.md (&quot;subagents stay read-only; make edits in the main session so I can approve them&quot;) enforced structurally rather than hoped for. I get a senior second set of eyes on demand, running in its own context window, handing me findings without ever touching the code or crowding the session where the real work happens.</p><h3>What the prompt looks like now</h3><p>So after all of that — the constitution, the rules, the skills, the hooks, the subagents — what do I actually type?</p><p>Almost nothing. Once the app is scaffolded, most day-to-day work needs no bespoke prompt at all, because the rules, skills, subagents, and hooks carry the structure. Short instructions inherit the whole discipline. “Add a delete-recipe endpoint” now pulls in the backend rules automatically, follows the add-endpoint skill&#39;s layered playbook, gets its transaction boundary right because the skill insists on it, can&#39;t commit a secret because the hook won&#39;t let it, comes out formatted, and can be handed to @code-reviewer for a read-only pass — and I typed six words.</p><p>That’s the shift, stated plainly. <strong>Prompt engineering is writing the discipline out, in full, every time. Claude engineering is building the discipline into the repository so a short prompt inherits it.</strong> SCRUB didn’t go away — it went <em>structural</em>. The five elements didn’t disappear from my work; they moved out of the chat window and into the codebase, where they load themselves, enforce themselves, and survive my worst moment of remembering.</p><h3>Why a business should care, not just an engineer</h3><p>I work with two kinds of decision-makers, often in the same room, so here’s the version for the one who signs the checks.</p><p><strong>Onboarding gets cheap.</strong> A new developer — or a new AI agent session — reads CLAUDE.md and the rules and understands how the system is built in an afternoon, not a month. The conventions are written down in one diagnosable place, not in a senior engineer&#39;s head as folklore.</p><p><strong>The discipline stops depending on heroics.</strong> The secret-guard hook doesn’t get tired. The formatter doesn’t forget. The layered architecture doesn’t erode because someone was in a hurry, because the skill that builds endpoints won’t build them any other way. You’re not buying a one-time clean build; you’re buying a repo that <em>stays</em> clean because the rules are load-bearing, not decorative.</p><p><strong>You own all of it.</strong> No proprietary framework you keep paying for. The .claude/ folder is plain files — Markdown, shell, JSON — sitting in your repo under an MIT license. Clone it, fork it, change it. If you never call me again, you keep every bit of it.</p><h3>The honest caveats, and the contrarian close</h3><p>Two things I won’t pretend away. First, the same “verify before trusting” that’s stamped on the repo applies to this whole approach: Claude Code and Aspire both ship fast, and hook syntax, subagent frontmatter, and exact Aspire API names are the surface most likely to drift. Confirm against the current docs. A toolkit that assumes last quarter’s API is worse than no toolkit, because it fails in ways that look like your mistake.</p><p>Second — and this is the contrarian bit — none of this replaces judgment. It relocates the judgment. Every hour I no longer spend retyping Restrictions into prompts is an hour that moved <em>earlier</em>, into designing the constitution, scoping the skills, and deciding which guardrails deserve to be laws. The work didn’t get easier. It got front-loaded. That’s the same lesson every good architect teaches: the leverage is in the decisions you make before the code exists, made once, visibly, where they can’t quietly rot. Building the .claude/ folder is part of the architecture. The app is just what proves it works.</p><p>The prompt library was step one. The repository that makes the prompts unnecessary is step two. That’s where the leverage actually lives.</p><p><em>Robert Felkins is the principal architect at Architect4Hire — Chicago-based fractional and contract architecture for small and mid-sized teams. I design right-sized .NET and Azure systems, modernize the ones you already have, and bring AI-assisted development into teams in a way that survives contact with production: senior judgment without the full-time price tag. The build in this post is public at </em><a href="https://github.com/architect4hire/claudebox"><em>github.com/architect4hire/claudebox</em></a><em> — clone it before you decide anything. Reach out at </em><a href="/service/mailto:robert@architect4hire.com"><em>robert@architect4hire.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4baaab34af98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One Team, Three Projects, One Board: Building PlannerPro With Layered SCRUB]]></title>
            <link>https://medium.com/@robert_84835/one-team-three-projects-one-board-building-plannerpro-with-layered-scrub-5cb3c9539b65?source=rss-1a5e3f553f20------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cb3c9539b65</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[scrubs]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Robert Felkins]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 12:58:16 GMT</pubDate>
            <atom:updated>2026-07-08T13:10:35.274Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kaH-02ZaPs5d4Et5.png" /></figure><p>TL;DR — the code and the full prompt library live at <a href="https://github.com/architect4hire/plannerpro?ref=architect4hire-thoughts-and-musings.ghost.io">https://github.com/architect4hire/plannerpro</a>. The prompts document at docs/PLANNERPRO-SCRUB-PROMPTS.md is the interesting part. This post explains why.</p><p>I want to tell you about a standup.</p><p>Not a dramatic one. Nobody quit. Nothing shipped broken. The kind of standup that’s much worse than that — the kind that happens every single morning, takes forty minutes, and produces less clarity than it started with.</p><p>The client had one delivery team. Six people. Good people. And at the moment I was engaged, that one team was carrying three completely independent projects: a customer portal rebuild, an internal reporting migration, and a compliance-driven integration with a hard regulatory date. Three backlogs. Three stakeholders. Three sets of priorities that had never once been in the same room together.</p><p>Their tooling handled this the way every project management tool handles it: three boards. Because every tool on the market is built on the same silent assumption — that a project has a team. One project, one board, one team, tidy.</p><p>This team had the assumption backward. The <em>team</em> had projects. Three of them. And the tooling had no answer for that at all.</p><p>So, the standup was tab-switching. Board one, board two, board three, back to board one because someone remembered something. The team lead kept a spreadsheet on the side — the real board, the one that actually reflected reality — updated by hand, wrong by Wednesday. And the thing that finally made someone call me: their most senior developer had nine items in progress. Nine. Three per board, and each board looked completely reasonable in isolation. No single view existed anywhere in the company that could show that number. The person carrying the most risk in the org was invisible to every tool they’d paid for, precisely because the risk was spread across three views that never met.</p><p>That’s not a process problem. That’s a data model problem. The unit of capacity is the <em>person</em>, and every board they owned modeled capacity as a property of the <em>project</em>.</p><p>I couldn’t find a tool that modeled it correctly without an enterprise license and a consulting engagement to configure it. So I built one. It’s called PlannerPro; it’s small, and it does exactly one thing the big tools don’t: one board, columns for workflow state, swimlanes for projects, and work-in-progress limits that belong to the human being — enforced across every project simultaneously.</p><p>This post is about what I built, but mostly it’s about <em>how</em> I built it — because PlannerPro went from an empty repository to a working, tested product using a committed library of small, layered prompts, and the discipline behind those prompts is the part you can steal.</p><h3>SCRUB, For Those Just Joining Us</h3><p>If you read <a href="https://architect4hire-thoughts-and-musings.ghost.io/the-prompt-is-the-plan-how-i-built-a-1-200-line-angular-component-with-a-framework-youve-never-heard-of/">the BrandForge post</a>, you know the framework. Short version for everyone else.</p><p>AI coding tools have a failure mode I call the Plausibility Trap: the output isn’t wrong in ways that crash. It’s wrong in ways that compile, pass tests, look idiomatic, and quietly encode a domain decision you never made. The model knows how to write code. It does not know your domain. When your prompt leaves a gap, the model fills it with the most statistically common answer from training data — and the most common answer is, occasionally and silently, the wrong one for <em>you</em>.</p><p>SCRUB is the checklist that closes those gaps before you hit submit. Five elements, every prompt:</p><ul><li><strong>S — Scope.</strong> Exactly what you’re asking for. Named methods, named files, nothing else.</li><li><strong>C — Constraints.</strong> The technical rules: framework versions, architecture, naming, DI style. <em>Your</em> codebase, not the training-data average.</li><li><strong>R — Restrictions.</strong> What you explicitly do not want, tiered CRITICAL / IMPORTANT / PREFERRED, each with a reason. The element everyone skips. The element that matters most.</li><li><strong>U — Usage.</strong> Who runs this, under what conditions, with what compliance and audit expectations?</li><li><strong>B — Behavior.</strong> What must not change. The star of every edit to existing code.</li></ul><p>I’ve written a book about the full system — <em>Pratical AI Assisted Development</em>, out soon — which goes deep on tiered restrictions, Edit Mode patterns, prompt chaining, and applying the framework to codebases you inherited rather than started. But you don’t need the book to follow this post. You need one idea from it:</p><p><strong>A prompt is a specification, and specifications deserve engineering.</strong></p><p>PlannerPro is what that looks like on a greenfield project, end to end.</p><h3>The Architecture and the Choices Behind It</h3><p>Let me get the stack out of the way, then talk about the decisions that actually mattered.</p><p>.NET 10 Web API on the backend. EF Core 10 over SQL Server. Angular 20 on the front, standalone components, signals for all component state, Angular CDK for the drag-and-drop. If you’ve read anything else I’ve written, none of that surprises you.</p><p>Here’s the first real decision: <strong>PlannerPro is one API project.</strong> Not microservices. Not Aspire orchestration. One Web API, one database, one Angular app.</p><p>I want to dwell on that for a second, because I’ve spent a lot of this blog building distributed systems, and I can feel some of you raising an eyebrow. The honest architect’s answer is that this system has one team of users, one write path that matters, and no independent scaling or deployment pressures anywhere. Microservices are a solution to organizational and operational problems that PlannerPro lacks. Reaching for them anyway would have been resume-driven development, and the whole point of this engagement was to solve a problem in days, not to build a platform. Right-sizing is an architectural decision too — arguably the one clients pay me for most often.</p><p>Inside that one project, the layering is strict, and it’s the same layering I use everywhere: <strong>Controller → Facade → BusinessManager → DataManager → DbContext.</strong> Hand-rolled mapping extensions, no AutoMapper. Audit fields on every entity. Soft delete everywhere, enforced with a global query filter. Boring, deliberate, and — this matters for what comes later — <em>predictable enough that an AI can be pointed at it and told to conform</em>.</p><p>The domain model consists of three entities. Project. WorkItem. TeamMember. That’s it — no sprints, no epics, no comments, no attachments. Version one is the board and the rule, and everything I declined to build was declined on purpose.</p><p>And the rule is the whole product, so let me state it precisely:</p><p><strong>A team member’s WIP limit applies to their in-progress items across all projects.</strong> The query that backs it — CountInProgressForMemberAsync - deliberately has no project filter. There is a CRITICAL restriction in the prompt library that says exactly that: <em>do not filter this count by project</em>. Because an AI generating a data manager for a project-management tool will absolutely scope that query to the project. Every example in its training data does. Project-scoped WIP is the idiom. Project-scoped WIP is also, for this client, the <em>entire disease</em>. Their senior dev with nine in-progress items looked fine on every board precisely because every count was project-scoped. One .Where() clause, present or absent, is the difference between a tool that solves the problem and a tool that re-implements it with nicer CSS.</p><p>That’s the Plausibility Trap in one sentence, by the way. The wrong version compiles, passes tests, and demos beautifully.</p><p>Two more decisions worth naming:</p><p><strong>The board is one payload.</strong> A single GET /api/board returns everything the screen needs, grouped and ready to render - the Angular component does no client-side regrouping. When five people are staring at a shared screen in standup, you want one fetch, one render, one source of truth.</p><p><strong>The server is the transition authority.</strong> Status moves one step forward or one step back — Backlog → Ready → In Progress → Review → Done, no skipping — and the <em>server</em> enforces it. The UI does a drag with an optimistic update and rolls back on rejection. I explicitly restricted the AI from greying out “illegal” columns during a drag, which is the clever UX idea it will offer you unprompted. A greyed-out column that’s wrong is a lie with good intentions; an honest 422 toast after the fact is merely an inconvenience. When client-side cleverness and server truth disagree, cleverness loses.</p><p>One drag-and-drop restriction earns special mention because it’s my favorite in the whole library: <strong>drop lists are connected only within a swimlane.</strong> A card can move between columns, never between projects. Why CRITICAL and not IMPORTANT? Because cross-lane drag isn’t a UX bug — it’s a <em>data corruption</em> bug wearing a UX feature’s clothes. Dragging a card one lane down would silently reassign a work item to a different project, and the CDK will happily wire all the lists together if you don’t tell it otherwise, because connecting everything is what the examples do. One restriction. One line. An entire category of “why is this ticket in the wrong project” support conversations, never born.</p><h3>The Prompts: Small on Purpose</h3><p>Now the part I actually want to talk about.</p><p>There’s a file in the repository — <a href="https://github.com/architect4hire/plannerpro?ref=architect4hire-thoughts-and-musings.ghost.io">docs/PLANNERPRO-SCRUB-PROMPTS.md</a> - that existed before any of the code did. Nineteen prompts. It&#39;s the plan I worked from, committed alongside the code it produced, and it follows the same chain the BrandForge component did: <strong>Context → Plan → Execute → Verify.</strong></p><p>But the style of these prompts is different from what most people write, and the difference is the point. These are <em>micro</em> prompts. Every one of them fits in a paragraph. The Scope blocks name exact methods with exact signatures. The Restrictions come tiered, and every CRITICAL restriction carries its reason — not as documentation garnish, but because the reason is the thing that tells the model <em>why</em> the plausible default is wrong here.</p><p>Compare the mega-prompt approach — “build me a kanban tool with three projects and WIP limits, here are 40 requirements” — with what’s in that file. The mega-prompt produces two thousand lines in one shot. Somewhere in those two thousand lines, the WIP query has a project filter, the drop lists are cross-connected, and the rollback path doesn’t exist. You will find those problems the way my client found their nine-item developer: later, in production, by accident.</p><p>The micro prompts produce the same two thousand lines. But no single generation is ever more than a couple hundred of them, and every one of those chunks got a review that took two minutes instead of an afternoon.</p><p>Each prompt also names its <strong>mode</strong>, because the tools are not interchangeable. Claude Code Chat for the layers where thinking matters — contracts, business rules, orchestration methods. Copilot Agent Mode for the layers that are mechanical and multi-file — data access, template slices, CSS — where the autonomous build-and-verify loop earns its keep. Claude Code Edit Mode for surgery after the fact, with Behavior as the dominant element. Reasoning in Chat, generation in Agent, precision in Edit. Matching the mode to the cognitive work is half the discipline.</p><h3>Why Layers Are the Whole Ballgame</h3><p>If you take one thing from this post, take this section.</p><p>The single most important structural decision in the prompt library is not any individual restriction. It’s that <strong>the work is layered</strong>, and each layer constrains the next.</p><p>The backend is four layers. Layer 1 is contracts — interfaces, enums, entity skeletons, view model shapes. Signatures only, no bodies, maybe eighty lines. Layer 2 is data and mapping: the DbContext, the data managers, the mapping extensions. Layer 3 is the business rules — the transition table and the WIP check, the two things that <em>are</em> the product. Layer 4 is the HTTP surface and the wiring.</p><p>The frontend gets the same treatment, six layers deep: a signal skeleton with every method stubbed, then the template built in vertical slices — header and WIP strip, then the swimlane grid, then cards and drag wiring — then the method bodies, then the styles. The methods layer comes second to last deliberately: by the time the AI writes onDrop(), the entire template it orchestrates already exists in front of it. It is not writing orchestration in a vacuum and hoping the UI that arrives later happens to match.</p><p>Why does layering matter this much? Four reasons, in ascending order of importance.</p><p><strong>First, review becomes possible.</strong> Eighty lines of contracts is a code review. Two thousand lines of everything is a skim, and a skim is where the Plausibility Trap lives. Every ordering bug I’ve ever shipped from AI-generated code went out through a review I did too fast because the diff was too big.</p><p><strong>Second, errors stay local.</strong> When Layer 2 has a mapping bug — and mapping bugs are the most common failure at that layer — I fix it with a Layer 2 prompt. Layers 3 and 4 never hear about it, because they reference Layer 2 through its contracts, not its internals. In a one-shot generation, a bug in one region sprays corrections across the entire output, and every correction risks disturbing something that was right.</p><p><strong>Third, naming compounds.</strong> Layer 1 is where I spend disproportionate review time, because the names chosen there propagate through every subsequent layer. A bad facade method name in Layer 1 costs five minutes to fix in Layer 1 and a five-file threading exercise to fix after Layer 4. Cheap-to-fix and expensive-to-fix are the same mistake at different timestamps; layering lets you always pay the cheap price.</p><p><strong>Fourth — and this is the one that changes how you work — each layer constrains the next.</strong> By Layer 3, the AI isn’t inventing; it’s <em>conforming</em>. The contracts exist. The data managers exist. The custom-instruction files pre-load the conventions. The generation space has been narrowed, layer by layer, until the plausible output and the correct output are nearly the same thing. That’s the real trick. You’re not hoping the model guesses right. You’re removing its opportunities to guess.</p><p>The ordering echoes onion architecture, but the mapping isn’t the point — the <em>size</em> is the point, and the direction of dependency is the point. Small enough to read in two minutes. Ordered so the shape exists before the behavior, and the behavior exists before the wiring.</p><p>And it doesn’t feel slow. I expected it to, the first time. Nineteen prompts for a two-project solution? It felt fast, because I was never working on more than one small piece at a time, and I never once entered the mode every developer knows too well — spelunking through a giant generated diff looking for the line that’s lying to you.</p><p>Fix the plan, not the code. If the plan is wrong, you fix a paragraph.</p><h3>Verify: The Step That Catches You Moving Too Fast</h3><p>The chain ends with Verify prompts — one for the backend, one for the board component. Each is a list of specific PASS/FAIL checks the AI runs against the finished code, with file-and-line evidence required for any FAIL.</p><p>Not “does it work.” Specific. <em>Does the WIP count query have a project filter? Is any drop list connected across lanes? Does the rollback restore captured state, or does it cheat and re-fetch the whole board? Does any orchestration method contain a </em><em>.subscribe()?</em> Every check on those lists maps back to a CRITICAL or IMPORTANT restriction from an earlier layer, because the Verify step exists for exactly one scenario: the day you review a diff too fast. On BrandForge, Verify caught a real bug my eyes had slid over. It stays in the chain forever.</p><p>The Verify lists are also the maintenance contract. When PlannerPro grows — per-column WIP limits are the obvious next ask, and a “blocked” flag is right behind it — the prompts document gets updated <em>first</em>: new restrictions, new Verify checks, then run the prompts. The document is versioned, committed, and reviewed like the code, because it is the reason the code looks the way it does. Six months from now, when somebody wonders why CountInProgressForMemberAsync pointedly ignores the project, the answer isn&#39;t in a comment or in my head. It&#39;s in a file with a commit history.</p><h3>What the Client Got</h3><p>A board their standup actually runs on. Swimlanes for the three projects, five columns, drag-and-drop with honest server-side rules, and a WIP strip across the top showing every team member’s cross-project count — the number that used to live in a hand-maintained spreadsheet, wrong by Wednesday.</p><p>The nine-item developer, by the way, is now capped at three, and the standup conversation changed shape the first week: it stopped being three sequential status reports and started being an argument about which project gets the constrained person next. That’s the right argument. The tool didn’t resolve their priority conflict — no tool does — but it made the conflict <em>visible on one screen</em>, which is the precondition for resolving it like adults.</p><p>And I got a repository where every line of code traces back to a small, reviewed, committed prompt — which means the next feature starts from a plan, not from archaeology.</p><h3>The Practical Version</h3><p>If you want to run this pattern on your next greenfield build:</p><p><strong>Write the domain brief first, and make the AI recite it back.</strong> One paragraph. The Context step costs five minutes and catches misunderstandings while they cost one sentence to fix.</p><p><strong>Argue with the Plan.</strong> In prose, before any code exists. The plan step is the cheapest insurance in the entire chain, and it is the step everyone skips.</p><p><strong>Layer the Execute.</strong> Contracts, then data, then rules, then wiring. Four to seven layers, each describable in three sentences. If a layer needs a fourth sentence, split it.</p><p><strong>Write Restrictions before Scope, and tier them.</strong> Ask what could compile and still be wrong. CRITICAL means silent wrong data. IMPORTANT means debt. PREFERRED means style. Attach reasons to the CRITICAL ones — the reason is what teaches the model why the idiom is wrong here.</p><p><strong>Find your no-project-filter.</strong> Every domain has one: the single line where the training-data idiom and your business reality point in opposite directions. Yours might be a tip default, a rounding rule, a scoped query. Find it before the AI does, and pin it with a CRITICAL restriction.</p><p><strong>Match the mode to the work.</strong> Chat for contracts, rules, and orchestration. Agent for mechanical multi-file layers. Edit for surgery, with Behavior dominant.</p><p><strong>End with Verify, and keep it.</strong> Specific PASS/FAIL checks derived from your restrictions. Re-run it after every change.</p><p><strong>Commit the prompts.</strong> They’re not notes. They’re the architecture record.</p><p>The repo is at <a href="https://github.com/architect4hire/plannerpro?ref=architect4hire-thoughts-and-musings.ghost.io">github.com/architect4hire/plannerpro</a>, prompts and all. Read the prompts document before the code — it’s the better half of the repository, and it will make the code make sense in a way the code alone can’t.</p><p><em>Robert Felkins is the principal architect at Architect4Hire and the author of the upcoming book</em> Pratical AI Assisted Development, <em>which covers the full SCRUB system — tiered restrictions, layered generation, Edit Mode patterns, prompt chaining, and applying the framework to codebases you inherited rather than started.</em></p><p><em>And if your team is staring at a version of the three-boards problem — tooling, architecture, or an AI-assisted delivery practice that isn’t paying for itself yet — that’s the work I do. I take on fractional architecture engagements: a few days a month of senior architectural judgment without the full-time price tag, covering .NET and Azure platform work, team enablement, and AI-assisted development practices that survive contact with production. Reach out at </em><a href="/service/mailto:robert@architect4hire.com"><em>robert@architect4hire.com</em></a><em>.</em></p><p><em>Originally published at </em><a href="https://architect4hire-thoughts-and-musings.ghost.io/one-team-three-projects-one-board-building-plannerpro-with-layered-scrub/"><em>https://architect4hire-thoughts-and-musings.ghost.io</em></a><em> on July 8, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cb3c9539b65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Prompt Is the Plan: How I Built a 1,200-Line Angular Component With a Framework You’ve Never…]]></title>
            <link>https://medium.com/@robert_84835/the-prompt-is-the-plan-how-i-built-a-1-200-line-angular-component-with-a-framework-youve-never-075e78613172?source=rss-1a5e3f553f20------2</link>
            <guid isPermaLink="false">https://medium.com/p/075e78613172</guid>
            <category><![CDATA[scrubs]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Robert Felkins]]></dc:creator>
            <pubDate>Thu, 04 Jun 2026 13:05:54 GMT</pubDate>
            <atom:updated>2026-07-08T13:09:46.284Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Prompt Is the Plan: How I Built a 1,200-Line Angular Component With a Framework You’ve Never Heard Of</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mmxs9Ly_YaZYSJSk.png" /></figure><p>Or: what happens when you stop typing instructions at the AI and start engineering them*</p><p>TL;DR — wanna check out the framework and sample application I built, grab the code at <a href="https://github.com/Architect4Hire/BrandForge?ref=architect4hire-thoughts-and-musings.ghost.io">https://github.com/architect4hire/brandforge</a></p><p>I want to tell you about a bug.</p><p>Not a dramatic one. No crash. No stack trace. The kind that’s much worse than that — the kind where everything runs fine, the feature ships, and then three weeks later an operator notices that every single content card saved from the pipeline has the wrong social media copy attached to it.</p><p>Instagram post? Generic. TikTok hook? Missing. Pinterest description? Something the AI generated from the image name, not the actual image. The copy was there. It just belonged to the wrong image, from an earlier step in the workflow, because somewhere in twelve hundred lines of Angular TypeScript the social copy generation fired at the wrong moment. Before the operator had chosen an image. Before the system knew which image to describe.</p><p>The code compiled. The tests passed. The component ran. Nobody knew anything was wrong until they looked at the actual board cards.</p><p>That bug — or rather, the specific thing I did to prevent it from ever happening — is what this post is about.</p><h3>The AI Does Something I Find Genuinely Terrifying</h3><p>Before I get to the solution, I want to name the problem properly, because most people I talk to about AI-assisted development haven’t quite articulated it yet.</p><p>The problem isn’t that the AI gets things wrong. I can handle wrong. Wrong throws an error, wrong breaks a test, wrong crashes the app and puts a red line in the console. I can work with wrong.</p><p>The problem is that the AI gets things <em>plausibly right</em>.</p><p>Here’s what that looks like in practice. You paste a task into Claude — build me a service, write me a component, add a method to this class — and the AI produces twelve hundred lines that are idiomatic. They reference the right services. The types are correct. The naming follows your conventions. The structure looks exactly like what a senior developer would write. You do a quick scan, it looks good, you run it, it runs. You ship it.</p><p>And then three weeks later you find out that the component has been defaulting the tip amount to twenty percent, or storing a PII field it shouldn’t be touching, or firing an expensive AI call before the user has confirmed their intent, or — in my case — generating social copy off the wrong image because the ordering of two async calls was off by half a step.</p><p>I started calling this the Plausibility Trap. The output is so plausible-looking that you don’t examine it carefully enough to catch the domain error buried inside it. A junior developer would produce code that’s obviously wrong and you’d catch it in review. The AI produces code that’s only <em>subtly</em> wrong and you catch it in production.</p><p>The reason this happens is structural, not a flaw in the AI. The model is trained to produce idiomatic, coherent, conventionally-structured code. It has no idea what your product is actually supposed to do. It does not know that social copy should fire after image selection and not before. It doesn’t know that your food blogger operators are going to be looking at that copy on a desktop CMS and not a mobile device, and that the UX decisions that flow from that distinction are significant. It doesn’t know that your company had a legal incident around default values in financial fields. It knows how to write code. It does not know your domain.</p><p>So when you hand it a vague prompt and it fills in the gaps, it fills them with plausible defaults from training data. And the defaults are usually fine. Until they’re not.</p><h3>I Got Mad About This and Built a Framework</h3><p>I have been building software with AI tooling since before it was cool and after it got annoying. For a long time my standard approach was “write a really long prompt and hope for the best.” Which worked often enough to feel like a strategy, and failed spectacularly often enough that I spent a lot of time in debug mode wondering which part of my fifty-line prompt the AI had decided to ignore.</p><p>The thing I eventually figured out — the thing that changed how I work — is that the prompt failures are not random. They fall into patterns. And once you can see the pattern, you can address it systematically before you hit submit.</p><p>That systematic approach turned into a framework I call SCRUB.</p><p>It’s not a brand new category of idea. It’s a checklist. Five elements, every prompt. It forces you to address the five categories of AI-generated code failure before the code gets generated. I wrote a whole book about it — <em>Practical AI Assisted Development</em>, which covers the full framework plus a lot of the tooling philosophy around it. But the heart of it is five letters, and you can use it today, right now, without reading anything else I’ve written.</p><p>Let me explain what each one means, and why the one most people skip is the most important.</p><h3>What SCRUB Actually Is</h3><p><strong>S is Scope.</strong> What are you asking for, named precisely. Not “build me a service” but “build me exactly these four methods, with these exact signatures, in this file, and nothing else.” The AI will expand your Scope if you let it. It will add helper methods you didn’t ask for. It will create a base class when you just needed a concrete class. It will refactor adjacent code while it’s in there because the adjacent code could be cleaner and the AI finds mess uncomfortable. Scope is the fence around what you actually want. Build it tight.</p><p><strong>C is Constraints.</strong> The technical rules your output must respect. Framework version. Naming conventions. Architectural patterns. DI style. Which async pattern you use. The AI doesn’t know you’re on Angular 20 standalone with signals and @if/@for control flow unless you say so. If you don&#39;t say so, you&#39;ll get *ngFor in your template and a BehaviorSubject in your class because those are the idioms from the version of Angular that&#39;s most represented in training data. I&#39;ve rebuilt the same component three times before I started writing constraints explicitly. I&#39;ve been on Angular 20 with signals for months now. I still write the constraint every time. The AI does not have session memory that says &quot;this person uses signal-based state management, use that.&quot;</p><p><strong>R is Restrictions.</strong> This is the one everyone skips, and it is the single most important element in the entire framework. Pay attention here.</p><p>Restrictions are the things you explicitly do not want. Not what you want built, what you want avoided. This is where you prevent the Plausibility Trap, because the Plausibility Trap lives inside the gap between what you asked for and what you said was wrong.</p><p>Here’s the example from the book that sticks with me. Imagine you’re building a tip calculator UI. You write a great Scope block, solid Constraints, the AI produces a beautiful component. Clean code. Nice UI. Runs great. The default tip is twenty percent.</p><p>You didn’t specify the default. The AI picked twenty percent because twenty percent is the most common default in tip calculator UX in training data. Your company had a conversation six months ago about defaulting to fifteen percent because the restaurant group you work with operates in a market where twenty percent feels presumptuous and you got customer complaints. That decision is not in your codebase. It’s not in any document the AI can read. It’s in a Slack thread from March.</p><p>The Restriction is: “Do NOT default the tip percentage to any value — the field should start empty and require explicit operator input.” One line. Specific. With a reason.</p><p>That’s what Restrictions do. They close the gaps that Scope leaves open. They’re the part of the prompt that says “I know you’ll make a reasonable-sounding decision here — here’s what’s actually required.”</p><p>I tier my Restrictions:</p><ul><li><strong>CRITICAL</strong>: “Do NOT default the tip” — missing this produces wrong data in production, silently</li><li><strong>IMPORTANT</strong>: “Do NOT add helper methods to this file” — missing this creates tech debt I’ll pay later</li><li><strong>PREFERRED</strong>: “Do NOT abbreviate variable names” — style nit, not worth blocking on</li></ul><p>The CRITICAL ones are the ones that prevent the Plausibility Trap. Write them first. Write them with reasons. The reason is not documentation fluff — it’s what tells the AI why the seemingly-reasonable default is wrong for this domain.</p><p><strong>U is Usage.</strong> Who runs this, under what conditions. A component built for a food blogger operator on a desktop CMS is different from the same component built for a tablet-based POS during a morning rush, even if the API contracts are identical. Usage is usually three to five lines. It is not usually interesting to write. It shapes dozens of downstream decisions and you won’t notice most of them unless the AI gets them wrong.</p><p><strong>B is Behavior.</strong> What must not change. This is the element that stars in Edit Mode prompts — “I want you to add these two validation rules and change nothing else, method order preserved, XML doc comments byte-for-byte identical.” In greenfield work it’s often N/A. In layered greenfield work — building a complex component in sequential steps — it becomes “all signals and computed values from Layer 1 are preserved unchanged,” and it matters more than you think because the AI will cheerfully improve your earlier work if you don’t explicitly tell it not to.</p><p>Five elements. The discipline is not the template — it’s the habit of asking, before you hit submit, where is R? Because R is the one people skip. And R is what prevents the social copy from firing off the wrong image.</p><h3>RecipeForge, and Why This Component Specifically Was a Problem</h3><p>RecipeForge is a food blogger CMS. It runs on .NET 10 with Aspire 13.3 on the backend, Angular 20 standalone on the frontend. The idea is that a food blogger picks a channel — we have six of them: Cozy Kitchen, Baker’s Bench, Quick Bites, Grill Master, Plant Forward, World Flavors — picks a posting day, and the system walks them through building a ready-to-post image and full platform-tailored social copy in one workflow. Image generation via Venice.ai. Prompt composition via OpenAI. Copy for seven platforms: Instagram, TikTok, Pinterest, Facebook, X, Threads, and a blog intro paragraph. One screen, start to finish, everything saved to a Digital Asset Manager and dropped onto a Kanban board.</p><p>The content pipeline component is the centerpiece of that workflow. When I sat down to build it, here’s what I was looking at:</p><p>Nine discrete steps, represented as a TypeScript union: &#39;config&#39; | &#39;seeding&#39; | &#39;reviewSeed&#39; | &#39;composing&#39; | &#39;reviewPrompt&#39; | &#39;rendering&#39; | &#39;pickImage&#39; | &#39;social&#39; | &#39;done&#39;. Thirty-one signals. Six API calls - two to OpenAI, two to Venice.ai, one to the DAM, one to the Kanban service. Two deliberate human-in-the-loop checkpoints where the operator can intervene and edit before anything expensive fires. A variant grid showing up to four generated images. A full-screen lightbox with keyboard navigation. Drag-and-drop reference image upload with a &quot;reverse-engineer this image into a prompt&quot; button. State that cleans itself up completely between runs.</p><p>That’s not a complex component. That’s a complex workflow expressed as a component. There’s a difference. A complex component has a lot of moving parts. A complex workflow has ordering constraints — real business rules about what happens before what, enforced by the UI, with consequences if the ordering is wrong.</p><p>The consequence here, as I explained at the top, is social copy that doesn’t match the image. Because there are three plausible places in this workflow where you could call runSocial(), and two of them are wrong. The AI, given a loose prompt, will pick the one that looks most natural from a &quot;I&#39;m building a step machine&quot; perspective, which is &quot;fire social copy generation after the render step completes.&quot; Completely reasonable. Wrong. Social needs to fire after image selection, not after image rendering, because social copy has to be written to describe a specific image - the one the operator actually kept - not a batch that might include images they&#39;re about to discard.</p><p>If I one-shotted this component, I would have gotten that wrong. And I probably wouldn’t have caught it for days.</p><h3>The Document I Wrote Before I Wrote a Single Line of TypeScript</h3><p>There’s a file in the RecipeForge repository at docs/SCRUB-PIPELINE-PROMPTS.md. It exists before the component exists. The prompts document is not documentation of what I did - it&#39;s the plan I worked from. The thing I reviewed and revised before I opened Claude Code Chat.</p><p>The document follows a four-step chain: Context → Plan → Execute → Verify.</p><p>Context gets the AI oriented to the codebase. Plan aligns on architecture before code exists. Execute generates the code in layers. Verify confirms the invariants held. The whole chain took about half a day to run. The component compiled cleanly at each layer.</p><p>Let me walk through what’s in each step and why the decisions look the way they do.</p><h3>Pre-Load Context: Making the AI Read Before It Writes</h3><p>The very first thing in the document is a snippet I paste at the start of every Claude Code Chat session before doing anything else. It lists six files and tells the AI to read them:</p><ul><li>domain.models.ts - channel keys, pick lists, social platform definitions, all the seed and response types</li><li>scene-presets.ts - nineteen food photography scenes across four scene groups</li><li>workflow-api.service.ts - every API method the component will call, with their actual TypeScript signatures</li><li>dam-api.service.ts - the saveAsset method</li><li>kanban-api.service.ts - the createCard method</li><li>image.component.ts - an existing working component that already does a version of the seed-and-render flow</li></ul><p>That last one is pulling a lot of weight. The instruction doesn’t say “here are the patterns I want you to follow, let me describe them.” It says “here is a component that already does a version of this correctly, read it and match what you see.” That is the most reliable Constraint you can write. Not a description of the convention — a pointer to an exemplar. The AI reads the actual code and extracts the pattern from it. Every time I’ve tried to describe a pattern in prose versus pointing at a live example, the example wins. Not by a little. By a lot.</p><p>The last line of the pre-load is: “Do not generate any code yet.”</p><p>This matters because Claude will sometimes start generating the moment it finishes reading files. It’s being helpful. I don’t want helpful yet. I want understanding. “Do not generate any code yet” is four words that prevent a premature response and keep the session in the right state for the Context step.</p><h3>Step 1 — Context: Ask for Understanding Before You Ask for Code</h3><p>The Context prompt asks Claude to produce a structured summary. Not code — understanding. What signal and computed patterns does image.component.ts use? What are the exact shapes of ContentPromptSeedResult, ImageBatchResponse, and SocialWorkflowResponse? Which WorkflowApiService methods correspond to which pipeline stages?</p><p>There are two reasons I do this.</p><p>One: if the AI misunderstood something, I catch it here while it’s cheap. A misunderstanding in the Context step costs me a one-line correction. A misunderstanding in Layer 4 costs me a template rewrite.</p><p>Two: asking the model to synthesize what it read before it produces new code improves the quality of the production step. I know this sounds like folk magic. It isn’t. The model has to build an active representation of the relevant patterns before generating against them, and making that step explicit and separable — as a distinct prompt with a distinct deliverable — produces better output than jumping straight to execution. I noticed this pattern after running maybe thirty layered prompt chains. I tested it by removing the Context step and comparing results. The Context step wins.</p><p>I’ve caught two real errors in RecipeForge’s Context step — both about how firstValueFrom() was being used in the existing service layer. Both would have produced subtle async bugs in the methods layer if they&#39;d made it to Layer 6. One correction in prose, at the Context step, and neither showed up again.</p><h3>Step 2 — Plan: The Architecture Review Before the Build</h3><p>The Plan prompt asks for a prose proposal. The step union type. The thirty-one signals — which ones and what they represent. The two edit checkpoints and what state the operator needs editable at each. How the lightbox integrates with batch state. How social copy fits into the post-pick flow. All in prose, zero TypeScript.</p><p>This is the step everyone skips. I understand the impulse. You have the Context, you know what you want, just generate the code already. Skipping the Plan is how you get clean code that does the wrong thing.</p><p>A bad plan generates plausible code. A good plan generates code where the only surprises are in the formatting.</p><p>What I’m specifically probing in the Plan review: does the AI agree that social fires after image selection? Does it understand that reviewSeed and reviewPrompt are active edit windows and not loading spinners? Does it know that the variant discard happens inside selectImage(), not in a separate cleanup step? These are the decisions with ordering consequences. If the plan is wrong about any of them, the Execute prompts will generate wrong code from a correct-looking starting point.</p><p>I push back in prose when I disagree with the proposal. Sometimes I don’t push back — the AI’s proposal is better than my initial instinct, and I update the prompts document before running Execute. This has happened twice on RecipeForge. The AI suggested a derived computed signal for the visible-platforms list that I hadn’t thought of, and it was cleaner than what I had planned. The Plan step is not “convince the AI to do what I decided” — it’s alignment. It takes maybe fifteen minutes. On a component this size, it is the best-spent fifteen minutes in the whole build.</p><h3>Execute: Seven Layers, Each One Verifiable</h3><p>Execute is where the code gets built. Seven prompts, each one scoped to a piece of the component that can be checked independently, each one explicitly preserving what came before.</p><h3>Layer 1: The Signal Skeleton</h3><p>Layer 1 produces the class with all signals, computed derivations, constants, injected services, and read-only pick lists — and nothing else. The @Component decorator. An empty template. No method bodies. Every method a stub.</p><p>This is the most boring layer. It’s also the most important one.</p><p>If the signal names are wrong in Layer 1, every subsequent layer references the wrong names and you get a cascade of TypeScript errors that trace back to a naming decision that would have taken two minutes to get right at the start. The goal is a clean compile from Layer 1 onward. Everything on top of a passing build, never in the dark.</p><p>The CRITICAL restrictions here are blunt: “Do NOT write template HTML beyond the bare decorator” and “Do NOT write any method bodies.” The AI will try to fill these in because a component class with no template and no implementation is unusual-looking. “Helpful” means filling in what appears missing. Helpful is not what I want here. I want a typed signal inventory. I’ll take helpful in Layer 2.</p><p>The IMPORTANT restriction — “no RxJS Subject or BehaviorSubject for component state” — is there because Angular 20 with signals means exactly that. Signals for state, firstValueFrom() to bridge HTTP observables into async methods. Every time I&#39;ve run a pipeline-style prompt without this restriction, at least one BehaviorSubject appears. Not because the AI is doing something wrong - BehaviorSubject is a completely correct Angular state pattern, just from a slightly older era. Without the restriction, the training distribution wins.</p><h3>Layers 2 Through 5: Building the Template in Slices</h3><p>The template is four layers. Each one adds a vertical slice of the UI without touching what already exists.</p><p><strong>Layer 2</strong> is the page header and config card — channel selector, posting day, variant count, the Run Pipeline button. Unremarkable on its own. The important thing here is the Behavior block: “All signals and computed values from Layer 1 are preserved unchanged.” That one line stops the AI from quietly improving my signal initializations while it adds the template. Without it, you get a template that’s fine and a class that’s been silently refactored. I have spent an afternoon tracing that particular class of diff-confusion. Not fun.</p><p><strong>Layer 3</strong> adds the mid-workflow steps: the seeding spinner, the reviewSeed edit block with scene selector and reference image upload zone, the composing spinner, the reviewPrompt block with the Venice prompt textarea and the character counter. These are the two human-in-the-loop checkpoints. This is where the operator can intervene.</p><p>One restriction from this layer I want to call out because it’s a good illustration of how Restrictions work in practice: “Do NOT show the character counter outside the reviewPrompt step.”</p><p>The first time I generated this template without that restriction, the counter appeared in the reviewSeed block, attached to the concept text field. Which makes a certain template-generation logic — it’s a textarea, there’s a counter component nearby, they belong together. What the AI doesn’t know is that concept text has no character limit, and showing a counter on a field with no limit creates visual anxiety the operator doesn’t need at that stage of the workflow. They’re not trying to stay under a character budget there. They’re editing a concept description. The counter is noise.</p><p>That’s domain knowledge. The AI has no way to derive it from the code. The only way it ends up right is if I put it in the Restriction. I put it in the Restriction. Never saw the problem again.</p><p><strong>Layer 4</strong> is the variant grid and the lightbox overlay. This layer has what I consider the most important CRITICAL restriction in the entire prompts document:</p><p>“Do NOT allow the Keep button inside the lightbox to call saveAll() - it must call selectFromLightbox(), which chains to selectImage(), which chains to runSocial().&quot;</p><p>Let me explain why this is CRITICAL and not just IMPORTANT.</p><p>The lightbox Keep button is the moment the operator says “this is the image I want.” When they click Keep, three things need to happen in sequence: the selection gets recorded, the unchosen variants get discarded, and the social copy gets generated based on the selected image. That entire sequence lives inside selectImage().</p><p>If the Keep button calls saveAll() instead, the operator is saving a content card before the social copy has been generated. The DAM asset gets created. The Kanban card gets dropped. Both of them have empty or stale social copy fields because the social workflow hasn&#39;t run yet. No error. No warning. Just a board full of cards with wrong descriptions that an operator discovers weeks later.</p><p>Three words in a button binding. One CRITICAL restriction. The difference between a bug that’s embarrassing to discover and a bug that’s expensive to fix.</p><p><strong>Layer 5</strong> is the result grid — chosen image on the left, all seven platform copy blocks on the right, save bar below. The save bar has the platform selector, card title, scheduled date, and the Save button. The CRITICAL restriction: “Do NOT show the Save button as enabled while socialState() !== &#39;success&#39;.&quot;</p><p>The operator cannot save until social copy generation has succeeded. That’s not a UX detail — that’s the product rule. Without the restriction, the AI produces a Save button that’s enabled as soon as the step renders, because that’s what most forms in training data look like. Forms have submit buttons and submit buttons are available. The contextually-gated submit button requires the explicit rule.</p><h3>Layer 6: The Methods Layer</h3><p>Layer 6 drops method bodies into all the stubs Layer 1 created. run(), continueFromSeed(), renderImage(), selectImage(), runSocial(), saveAll(), the reference image handlers, the lightbox helpers, the copy button, the restart flow. Every orchestration method.</p><p>I put this layer last deliberately. The entire template exists before the method bodies are written. When the AI is building selectImage(), it can see the full template context it&#39;s operating in - it knows what the lightbox looks like, it knows what the social grid expects, it knows what the save bar requires. It&#39;s not writing methods in a vacuum and hoping the template that comes later matches.</p><p>The sequencing restrictions in this layer are the ones I care most about:</p><p>“Do NOT call runSocial() before selectImage() resolves - social fires inside selectImage() only.&quot; CRITICAL because the violation produces silent wrong data. Social firing too early generates copy that describes the wrong image. No exception. No test failure. Just bad content on your board.</p><p>“Do NOT delete the chosen image variant — delete only the unchosen variants.” This one seems obvious until you’re reading auto-generated code and find .forEach(f =&gt; api.deleteImage(f).subscribe()) iterating over all the filenames, including the one the operator just kept. The AI is pattern-matching on &quot;clean up after image selection&quot; from training data. The correct behavior requires saying it explicitly, because &quot;delete all but one&quot; is a restriction, not a convention.</p><p>The Constraint for async style: “All orchestration methods use async/await with firstValueFrom() - no .subscribe() inside orchestration logic.&quot; The reason is error handling. Async/await with try/catch in an orchestration method gives you predictable recovery - you know which step failed, you set the right error signal, you return the UI to the right state. A .subscribe() in the middle of an orchestration chain makes error recovery harder to reason about and harder to test. The rule isn&#39;t theoretical. Every time I&#39;ve let a .subscribe() sneak into orchestration code, I&#39;ve regretted it.</p><h3>Layer 7: Helpers and Styles</h3><p>Layer 7 adds the private derivation helpers and the full component CSS. Smaller than what came before, but pickLocation() is worth a mention because it&#39;s a clean example of domain knowledge that has to live in the prompt.</p><p>pickLocation() maps cooking method keywords to scene presets - grilling and smoking go to outdoor scenes with a grill-adjacent preference, baking goes to kitchen scenes with a rustic preference, no-cook and raw-prep go to table setups. The function is maybe twenty lines. The mapping inside it represents product decisions we made about how food photography should relate to cooking context. Without those decisions in the Restriction block, the AI produces either a random mapping or a plausible-looking one based on whatever associations are strongest in training data.</p><p>Writing the mapping down in the prompt is also writing it down as product documentation. Anyone who reads the prompts file six months from now understands not just how the function works but why it maps the way it does.</p><h3>The Verify Step: Thirteen Specific Checks</h3><p>After all seven layers compile, there’s a Verify prompt. It asks Claude to re-read the completed component and run thirteen specific checks, reporting each as PASS or FAIL.</p><p>The CRITICAL checks hit the exact failure modes I was most worried about:</p><p>Does any step transition skip a review checkpoint? Does runSocial() fire anywhere except inside selectImage()? Does selectImage() accidentally delete the chosen filename? Does saveAll() run while socialState() !== &#39;success&#39;? Is there any localStorage, sessionStorage, or document.cookie anywhere in the file? Does any orchestration method use .subscribe() instead of firstValueFrom()? Are all seven social platforms rendered in the result grid? Is the Venice prompt character limit enforced at 1499 characters? Is there any *ngIf or *ngFor in the template? Does the lightbox Keep button call saveAll()?</p><p>That last one is on the list specifically because in an early iteration, before I had the CRITICAL restriction nailed down, the Keep button did call saveAll(). I caught it in the Verify step, not the diff review, because I was scanning the diff too fast. The Verify step is there precisely for that situation - the one where you&#39;re moving quickly and you miss the thing that matters.</p><p>Thirteen checks. Roughly half a day of build time. Zero production incidents related to ordering bugs on this component.</p><h3>What I Would Do Differently</h3><p>A few things.</p><p>I would write the Restrictions for each layer before writing the Scope. My current habit is still backward sometimes — I write what I want built, then I think about what could go wrong. The right habit is Restrictions-first. Sit down with a blank [R] block and ask “what are the five most plausible ways this layer could compile and still be wrong?” The list is almost always longer than five, but asking the question surfaces the critical ones before they bite you in production.</p><p>I’d be more explicit about CSS variable usage in Layer 7. I had a restriction that said “no hardcoded color values except platform dot colors,” and the first pass had hex values showing up in animation keyframes and hover transitions. The restriction was right but not specific enough. Lesson filed: restrictions on styles should name specific properties, not just categories.</p><p>I would add a Known Limitations section to the prompts document earlier. I added it at the end. During the build I was tracking four edge cases in my head — the reference image .subscribe() pattern, the BRAND_ARCHETYPES dependency, the lightbox containing-block CSS caveat, the orphaned variants on navigation. Writing them down as I encountered them would have saved me the mental overhead of holding them until the build was done. The prompts document is not just a pre-build artifact. It&#39;s a living document you update as you learn things.</p><h3>Why This Matters More Than It Looks Like It Does</h3><p>I want to be clear about what the SCRUB prompts document actually is, because I’ve seen people mistake it for something else.</p><p>It is not documentation. It’s not a write-up of what I did after the fact. It is the plan I worked from before I generated a single line of code for this component. And because it exists as a versioned, committed file in the repository, it becomes the first place I look when the component needs to change, not the last.</p><p>Buffer integration is on the roadmap — a “Schedule in Buffer” button that pushes copy and images directly to Buffer from the pipeline save step. When I add that feature, I will update SCRUB-PIPELINE-PROMPTS.md first. The new Layer 5 restrictions, the new Layer 6 method contracts, the additional Verify check for the Buffer call. Then I run the updated prompts. The component is built and maintained with the same discipline.</p><p>This is what the framework means when it says to treat prompts like code. Not a metaphor. A literal practice. The prompts directory is in source control. The prompts have authors and commit history. When something goes wrong in the component — and something always goes wrong eventually — the prompts tell me exactly which element of which layer broke.</p><p>Wrong default? Missing Restriction. Wrong state transition? Vague Scope or missing Restriction. Broke something I didn’t touch? Weak Behavior block. The diagnostic card maps symptom to element. Element to fix. No hunting.</p><p>The other thing the prompts document gives me is a record of why the code is the way it is. Six months from now, when someone new is reading pipeline.component.ts and wondering why runSocial() only ever fires inside selectImage() and not in any of the three other plausible locations - the answer is in the prompts file. Not buried in a comment. Not in my head. In a file that&#39;s been reviewed, committed, and is available to anyone who runs git log.</p><p>That is worth the fifteen minutes it takes to write the plan before you write the code. Every time.</p><h3>The Practical Version</h3><p>If you want to try this on a component you’re building:</p><p><strong>Start with Pre-load Context.</strong> Name the files the AI needs to read. Tell it explicitly not to generate anything yet. Five minutes, not fifty.</p><p><strong>Run a Context step first.</strong> Ask for a summary of what it read before asking for code. Read the summary. Correct misunderstandings in prose. This is the cheapest error-catching stage in the whole chain.</p><p><strong>Write a Plan prompt and read the proposal.</strong> Push back on anything with wrong ordering or wrong behavior. Do not skip this step because it feels slow. It is the cheapest insurance in the whole process.</p><p><strong>Split Execute into layers.</strong> Four to seven is usually right. If you can’t describe what a layer produces in three sentences, the layer is too big. Split it.</p><p><strong>Write Restrictions before Scope.</strong> Ask yourself: what are the five ways this layer could compile and still be wrong? Write those down first. The Scope block is usually easier.</p><p><strong>Tier your Restrictions.</strong> CRITICAL means silent wrong data in production. IMPORTANT means technical debt you’ll pay. PREFERRED means style. Know which ones you can compromise on and which ones you absolutely cannot.</p><p><strong>Write a Verify prompt.</strong> Not “does it run” — specifically, does it have the behaviors you required? Thirteen specific PASS/FAIL checks on a twelve-hundred-line component caught a real bug I missed in review.</p><p><strong>Commit the prompts document alongside the code.</strong> Update it when the component changes. It is not overhead. It is the architectural record of the component.</p><p>The <a href="https://github.com/Architect4Hire/BrandForge/docs/SCRUB-PIPELINE-PROMPTS.md?ref=architect4hire-thoughts-and-musings.ghost.io">docs/SCRUB-PIPELINE-PROMPTS.md</a> file is in the RecipeForge repository if you want to read the actual prompts rather than my description of them. The component it produces - brandforge-ui/src/app/features/pipeline/pipeline.component.ts - is the result of running those prompts in sequence with the pre-loaded context. Clean compile at every layer. All thirteen Verify checks passed on first run.</p><p>That is what disciplined prompt engineering looks like. Not faster, necessarily. Not more impressive. Just fewer bugs that compile and run and don’t get caught until production. And when something does go wrong, a clear map back to the decision that produced it.</p><p>That’s a trade I’ll take every time.</p><p>*Robert Felkins is the principal architect at Architect4Hire and the author of Practical AI Assisted Development. If you want to go deeper on SCRUB — the full tiered restriction system, the Edit Mode prompt patterns, applying the framework to existing codebases — the book covers all of it. Find it at the companion repository, or reach out at <a href="/service/mailto:robert@architect4hire.com">robert@architect4hire.com</a>.</p><p><em>Originally published at </em><a href="https://architect4hire-thoughts-and-musings.ghost.io/the-prompt-is-the-plan-how-i-built-a-1-200-line-angular-component-with-a-framework-youve-never-heard-of/"><em>https://architect4hire-thoughts-and-musings.ghost.io</em></a><em> on June 4, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=075e78613172" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why We Built an Audit Trail into AspireHire (And Why You Should Care)]]></title>
            <link>https://medium.com/@robert_84835/why-we-built-an-audit-trail-into-aspirehire-and-why-you-should-care-01bb55f2e666?source=rss-1a5e3f553f20------2</link>
            <guid isPermaLink="false">https://medium.com/p/01bb55f2e666</guid>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[aspire]]></category>
            <dc:creator><![CDATA[Robert Felkins]]></dc:creator>
            <pubDate>Sun, 31 Aug 2025 16:37:35 GMT</pubDate>
            <atom:updated>2025-08-31T16:37:35.315Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9tfVgpSewzEoYu2UEHrmvQ.png" /></figure><p><em>Or: How I Learned to Stop Worrying and Love Data Accountability</em></p><p>Hey folks! So, I’ve been deep in the trenches building AspireHire lately, and I wanted to share something that might not seem sexy on the surface but is absolutely crucial for any serious application: our audit framework. Yeah, I know, “audit framework” sounds about as exciting as watching paint dry, but stick with me here — this stuff matters more than you think.</p><h3>The “Oh Shit” Moment That Started It All</h3><p>Picture this: You’re running a job platform where candidates are uploading resumes, employers are posting positions, and money is changing hands. Then one day, someone calls and says, “Hey, my job posting disappeared, and I need to know exactly what happened and when.”</p><p>Without an audit trail? You’re basically playing detective with a blindfold on. With one? You can tell them exactly who did what, when they did it, and what changed. That’s the difference between looking professional and looking like you’re running your platform out of a garage (even if you literally are).</p><h3>What We Actually Built</h3><p>Instead of reinventing the wheel or bolting on some third-party solution that would cost us an arm and a leg, we built our own AuditDBContext that sits right on top of Entity Framework Core. It&#39;s elegant, it&#39;s automatic, and it just works.</p><p>Here’s the beautiful part, every time someone saves changes to our database, our audit framework automatically kicks in and says, “Hold up, let me just record what’s happening here.” It captures:</p><ul><li><strong>What entity changed</strong> (User profile? Job posting? Application?)</li><li><strong>What type of action</strong> (Created, updated, deleted)</li><li><strong>The exact fields that changed</strong> (Old value vs. new value)</li><li><strong>When it happened</strong> (Down to the millisecond)</li></ul><p>The magic happens in our SaveChangesAsync override:</p><pre>public override async Task&lt;int&gt; SaveChangesAsync(CancellationToken cancellationToken = default)<br>{<br>    var entityEntries = ChangeTracker.Entries()<br>        .Where(x =&gt; x.State != EntityState.Unchanged &amp;&amp; x.State != EntityState.Detached);</pre><pre>    foreach (var entry in entityEntries)<br>    {<br>        var audit = new Audit<br>        {<br>            TableName = entry.Entity.GetType().Name,<br>            Action = entry.State.ToString(),<br>            KeyValues = GetKeyValues(entry),<br>            Changes = GetFieldChanges(entry) != null ? System.Text.Json.JsonSerializer.Serialize(GetFieldChanges(entry)) : null<br>        };<br>        Audits.Add(audit);<br>    }</pre><pre>    return await base.SaveChangesAsync(cancellationToken);<br>}</pre><p>Zero extra code in our business logic. Zero chance of forgetting to log something. It just happens automatically, like a good DevOps pipeline.</p><h3>Real Talk: Why This Matters for AspireHire</h3><h3>Trust is Everything in Hiring</h3><p>When you’re dealing with people’s careers and livelihoods, trust isn’t optional. Candidates need to know their data is safe. Employers need confidence that their job postings and candidate information are handled properly.</p><p>Having a complete audit trail means we can:</p><ul><li><strong>Prove compliance</strong> when auditors come knocking</li><li><strong>Investigate issues</strong> quickly and thoroughly</li><li><strong>Build trust</strong> by being transparent about data handling</li><li><strong>Prevent disputes</strong> by having the receipts</li></ul><h3>The Technical Benefits Are Real Too</h3><p>Beyond the obvious compliance stuff, our audit framework gives us superpowers:</p><p><strong>Debugging Production Issues</strong>: Ever had a bug report that starts with “Something weird happened last Tuesday”? With full audit trails, we can reconstruct exactly what “weird” means.</p><p><strong>Analytics and Insights</strong>: Want to know how users actually behave on the platform? Audit data is a goldmine for understanding user patterns and optimizing UX.</p><p><strong>Data Recovery</strong>: When (not if) someone accidentally deletes something important, we can see exactly what was deleted and potentially restore it.</p><h3>The Implementation That Actually Works</h3><p>Here’s what I love about our approach — it’s dead simple but incredibly powerful. We have three main pieces:</p><ol><li><strong>The </strong><strong>AuditDBContext</strong> - The orchestrator that captures everything</li><li><strong>The </strong><strong>Audit entity</strong> - Stores the high-level change information</li><li><strong>The </strong><strong>AuditFieldChange class</strong> - Captures field-level details</li></ol><p>The framework is smart about what it tracks. It doesn’t just dump everything into a log file like some solutions. Instead, it:</p><ul><li><strong>Serializes complex objects</strong> properly (goodbye, [object Object] logs)</li><li><strong>Handles collections</strong> intelligently</li><li><strong>Only tracks actual changes</strong> (not just “something was saved”)</li><li><strong>Maintains referential integrity</strong> with primary key tracking</li></ul><h3>Lessons Learned Building This</h3><h3>Start Simple, Stay Flexible</h3><p>We started with basic audit logging and gradually added sophistication. The framework can handle complex scenarios now (like tracking changes to collections of related entities), but it started life tracking simple property changes.</p><h3>Performance Matters</h3><p>Adding audit trails to every database operation could theoretically slow things down. In practice? We’ve seen zero noticeable impact. Entity Framework’s change tracking is already doing most of the heavy lifting, so we’re just piggyback riding on that work.</p><h3>JSON is Your Friend</h3><p>Storing field changes as JSON gives us incredible flexibility. We can query it, we can deserialize it for reports, and we don’t have to predict every possible audit scenario upfront.</p><h3>What’s Next</h3><p>The audit framework is just the foundation. We’re already thinking about:</p><ul><li><strong>Real-time audit dashboards</strong> for monitoring platform health</li><li><strong>AI-powered anomaly detection</strong> to catch suspicious patterns</li><li><strong>Automated compliance reporting</strong> for when we inevitably need SOC 2 certification</li><li><strong>User-facing audit logs</strong> so people can see their own activity</li></ul><h3>The Bottom Line</h3><p>Building AspireHire isn’t just about connecting job seekers with employers — it’s about doing it right. That means thinking about data integrity, compliance, and trust from day one, not retrofitting it later when some crisis forces our hand.</p><p>The audit framework might not be the flashiest feature we’ll ever build, but it’s the kind of foundational work that separates professional platforms from hobby projects. When candidates trust us with their career data and employers trust us with their hiring processes, we better have our act together.</p><p>And honestly? There’s something deeply satisfying about knowing that every single change in our system is tracked, auditable, and recoverable. It’s like having a really good backup strategy — you hope you never need it, but you sleep better knowing it’s there.</p><p><em>Building AspireHire has been a masterclass in balancing feature velocity with technical excellence. Want to follow along with our journey? Check out our other posts about the platform architecture, or better yet, come try the platform when we launch. We’re building something special here, one properly-audited database change at a time.</em></p><p>💡 Want to see how it all comes together in real code? The full implementation of the AspireHire audit framework complete with AuditDBContext, entity classes, and sample usage, is up on GitHub. Check it out, fork it, or even open an issue if you’ve got ideas for making it better.</p><p>👉 github.com/architect4hire/aspirehire</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01bb55f2e666" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Add a caption to the feature image]]></title>
            <link>https://medium.com/@robert_84835/add-a-caption-to-the-feature-image-1f16214681f4?source=rss-1a5e3f553f20------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f16214681f4</guid>
            <category><![CDATA[aspire]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <dc:creator><![CDATA[Robert Felkins]]></dc:creator>
            <pubDate>Sun, 31 Aug 2025 16:35:25 GMT</pubDate>
            <atom:updated>2025-08-31T16:35:25.671Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XMBD0NdfMFrJAoPm.png" /></figure><p>Add a caption to the feature image</p><h3>Building a Proof of Concept and Teaching Developers How to Master Modern ASP.NET Core, Aspire, and Azure Development</h3><h3>Setting the Stage</h3><p>Let’s be real for a second. The world does not need another side project that fizzles out after a GitHub repo and a half-finished README. What it does need is projects that actually push developers forward, projects that teach as they grow, and projects that solve a real problem.</p><p>That’s why I’m launching <strong>AspireHire</strong>. At the surface, AspireHire looks like another freelance platform. The twist is that this one is built for developers, by a developer, with the entire journey shared in public. AspireHire is a proof of concept that doubles as a teaching tool. Over the next series of posts, I am going to break down every architectural choice, every piece of code, and every pipeline step so you can learn exactly how to build modern, cloud-native applications with ASP.NET Core 9, .NET Aspire, and Azure.</p><p>Think of this as a mix between a product launch and a masterclass in distributed system design. By the end, you will not only understand what AspireHire is but also how to apply the same patterns in your own work.</p><h3>Why Build Another Freelance Platform?</h3><p>If you’ve ever used Upwork or Fiverr, you know how they work. Upwork focuses on long-term projects and proposals. Fiverr is all about fast gigs at fixed prices. Both serve their markets well, but they share one big flaw: they don’t let developers show off what makes them special.</p><p>On Upwork you can write a nice cover letter and maybe share a portfolio. On Fiverr you can list a gig with a fixed price. Neither really helps a client figure out who is a serious technical professional and who just knows how to fill out a profile.</p><p>AspireHire flips the script. Instead of treating developers like interchangeable parts, it highlights what makes each one unique. Profiles include real portfolios, skill tags, certifications, GitHub integrations, and even coding test results. Clients can finally see more than a name, a rating, and a price tag.</p><p>This niche focus matters. By building only for software and IT work, AspireHire avoids the trap of being too broad. Developers get tools designed for them, and clients get confidence that they are hiring skilled professionals.</p><p>And for me, this is not just a product idea. It is a chance to show developers how to build a system like this from the ground up.</p><h3>From Idea to Proof of Concept</h3><p>Here is the important thing to understand. AspireHire is not just about launching another app. This project is a <strong>playground for learning</strong>. It is where I get to show you how a professional architect thinks about requirements, system design, data modeling, microservices, observability, and DevOps pipelines.</p><p>Instead of just handing you a GitHub repo at the end, I am going to walk you through the entire build. You will see the mistakes, the fixes, and the tradeoffs. You will learn not just what works but why it works.</p><p>If you have ever wanted to level up from hobby projects and tutorials into building production-ready systems, this series is going to give you that push.</p><h3>What the Series Will Cover</h3><p>Let me give you a roadmap of what’s coming. Each post will dive into a piece of AspireHire, with real examples and code along the way.</p><ol><li><strong>From Requirements to Architecture</strong><br>How to translate a vision into a technical blueprint. We will break down roles, workflows, and data models, then map them to services.</li><li><strong>Setting Up .NET Aspire</strong><br>Why Aspire is a game-changer for cloud-native apps and how to use it for service discovery, observability, and local orchestration.</li><li><strong>Microservice by Microservice</strong><br>Building Auth, Profile, Job, Proposal, Contract, Payment, and Messaging services with ASP.NET Core 9 and Clean Architecture.</li><li><strong>Relational Data Models with EF Core</strong><br>Designing tables and relationships that support complex workflows like proposals, contracts, and reviews.</li><li><strong>Event-Driven Messaging</strong><br>Using Azure Service Bus to decouple services and handle workflows like notifications and escrow payments.</li><li><strong>CI/CD Pipelines with Azure DevOps</strong><br>Containerizing everything, pushing to Azure Container Registry, and deploying to AKS with zero downtime.</li><li><strong>Observability that Actually Works</strong><br>Logs, metrics, and traces using .NET Aspire defaults, OpenTelemetry, and Application Insights.</li><li><strong>Securing the Platform</strong><br>Authentication with Azure AD B2C, protecting secrets with Key Vault, and designing for PCI and GDPR compliance.</li><li><strong>Building a Developer-First UI</strong><br>Creating a web experience that makes sense for technical users, from dark mode to GitHub integrations.</li><li><strong>Scaling and Extending</strong><br>Planning for AI-powered recommendations, advanced search, and premium features once the core platform is solid.</li></ol><p>By the time we are done, you will have the skills and the code samples to build your own distributed system on Azure.</p><h3>The Starting Blueprint</h3><p>Every project starts with a mental picture of what it will look like in production. Here’s the high-level blueprint for AspireHire:</p><ul><li><strong>Platform</strong>: ASP.NET Core 9 with .NET Aspire</li><li><strong>Deployment</strong>: Azure Kubernetes Service</li><li><strong>Storage</strong>: Azure SQL for relational data, Blob Storage for files, Redis for caching</li><li><strong>Messaging</strong>: Azure Service Bus for events</li><li><strong>Observability</strong>: Application Insights with OpenTelemetry integration</li><li><strong>CI/CD</strong>: Azure DevOps Pipelines pushing Docker images to Azure Container Registry</li></ul><p><strong>The core microservices include:</strong></p><ul><li><strong>Auth Service</strong> for login and identity</li><li><strong>Profile Service</strong> for detailed freelancer and client profiles</li><li><strong>Job Service</strong> for creating and searching job postings</li><li><strong>Proposal Service</strong> for bids and negotiations</li><li><strong>Contract and Payment Service</strong> for escrow and transactions</li><li><strong>Messaging Service</strong> for real-time communication tied to jobs</li></ul><p>Each service owns its own data store and can scale independently in AKS. All of them get logging, tracing, and health checks out of the box with Aspire.</p><h3>Why Use .NET Aspire?</h3><p>If you have ever built microservices the old way, you know the pain. You spend hours wiring up logging, tracing, configuration, and health checks before you even start writing business logic. Local orchestration is a mess.</p><p>.NET Aspire fixes that. With one method call, AddServiceDefaults, you get logging, tracing, metrics, and health endpoints already wired. Service discovery and orchestration happen in the AppHost, so running your entire stack locally feels like magic.</p><p>When you combine Aspire with Azure’s managed services, you get speed and reliability. Developers spend less time on plumbing and more time building features. That is why AspireHire is the perfect project to showcase what Aspire brings to the table.</p><h3>Building with Azure in Mind</h3><p>This project is built on Azure from the start. Not bolted on later. Not a side thought. From day one the services run on AKS and integrate with managed Azure services.</p><ul><li><strong>AKS</strong> gives us container orchestration, scaling, and zero-downtime updates</li><li><strong>Azure SQL Database</strong> handles relational storage with built-in HA and backups</li><li><strong>Azure Blob Storage</strong> stores profile images, portfolio files, and message attachments</li><li><strong>Azure Service Bus</strong> manages asynchronous communication between services</li><li><strong>Application Insights</strong> collects telemetry and connects to Aspire’s OpenTelemetry pipeline</li><li><strong>Key Vault</strong> protects secrets and connects seamlessly to services through managed identities</li></ul><p>By designing cloud-first, we get to learn not just how to build apps but how to build apps that run reliably in the environments companies actually use.</p><h3>Teaching Through Real Problems</h3><p>One promise I want to make is this: I am not going to hide the rough edges. You will see the broken deployments. You will see the EF Core migrations that fail. You will see the pipeline steps that don’t work the first time.</p><p>Because that is how real projects go. The value is not in seeing a perfectly polished example. The value is in seeing how to troubleshoot and fix problems like a professional. That is how you level up as a developer.</p><h3>What You Will Get Out of This</h3><p>If you stick with this series, here is what you will walk away with:</p><ul><li>Confidence to design and implement distributed systems on Azure</li><li>Hands-on examples of microservice patterns in ASP.NET Core 9</li><li>Real pipelines you can adapt for your own projects</li><li>A clear mental model of how to debug, monitor, and scale apps in production</li><li>A stronger resume, GitHub portfolio, or skill set for your next role or contract</li></ul><p>This is not another “todo list in microservices.” This is the kind of project you can point to in an interview and say, “Yes, I know how to build that.”</p><h3>Where We Go Next</h3><p>This post is the kickoff. In the next one, we are going to dive into the architecture and requirements document in detail. I will show you how to take an idea like “freelance platform for developers” and turn it into concrete services, data models, and diagrams.</p><p>From there we will start building the services piece by piece. By the end, AspireHire will not only exist as a working app but also as a step-by-step guide to modern .NET cloud development.</p><h3>Wrapping Up</h3><p>AspireHire is both a product experiment and a learning journey. By focusing on developers as users, it solves a real gap in the freelance market. By building it out loud, it creates a chance for you to see exactly how modern cloud apps are designed and deployed.</p><p>If you have been waiting for a project that goes deeper than tutorials and takes you inside the head of an architect, this is it. The best way to learn is by building something real, and that is exactly what we are about to do together.</p><p>So grab your coffee, fire up your IDE, and get ready. This is going to be a fun ride.</p><p>💡 Want to see how it all comes together in real code? The full implementation of the AspireHire audit framework complete with AuditDBContext, entity classes, and sample usage, is up on GitHub. Check it out, fork it, or even open an issue if you’ve got ideas for making it better.</p><p>👉 github.com/architect4hire/aspirehire</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f16214681f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Outbox Pattern and the Two-Stage Commit Problem]]></title>
            <link>https://medium.com/@robert_84835/outbox-pattern-and-the-two-stage-commit-problem-7bcff6118ea8?source=rss-1a5e3f553f20------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bcff6118ea8</guid>
            <dc:creator><![CDATA[Robert Felkins]]></dc:creator>
            <pubDate>Thu, 21 Aug 2025 10:33:10 GMT</pubDate>
            <atom:updated>2025-08-21T10:33:10.400Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CS2FmZpOFqQbVCVWk4wJNQ.png" /></figure><p>In the world of microservices and distributed systems, ensuring reliable message delivery while maintaining data consistency is one of the most challenging problems developers face. The <strong>Outbox Pattern</strong> provides an elegant solution to this dual-write problem, guaranteeing that business operations and event publishing happen atomically. This comprehensive guide will walk you through the implementation of the Outbox Pattern step-by-step, discuss the requirements for success, and highlight critical considerations.</p><h3>Understanding the Problem: The Dual-Write Challenge</h3><p>Before diving into the solution, let’s understand the problem the Outbox Pattern solves. Consider this common scenario in a microservices architecture:</p><ol><li>A service processes a business operation (e.g., creating an order)</li><li>The service needs to persist data to a database</li><li>The service must publish an event to notify other services</li></ol><p>The challenge arises when trying to make both operations atomic. What happens if the database transaction succeeds but the message publishing fails? Or vice versa? This dual-write problem can lead to:</p><ul><li><strong>Data inconsistency</strong> between services</li><li><strong>Lost events</strong> that other services never receive</li><li><strong>Duplicate processing</strong> when retries occur</li><li>**System-wide reliability issues</li></ul><h3>The Outbox Pattern Solution</h3><p>The Outbox Pattern solves this by storing outbound messages in the same database transaction as the business data. A separate background process then reliably publishes these messages to the message broker. This approach ensures <strong>exactly-once delivery semantics</strong> and maintains consistency between local state changes and event publishing.</p><h3>System Components</h3><p>The solution consists of five main components:</p><ol><li><strong>OrderCoordinator</strong> — ASP.NET Core Web API (.NET 9)</li><li><strong>InventoryApi</strong> — ASP.NET Core Web API (.NET 9)</li><li><strong>PaymentsApi</strong> — ASP.NET Core Web API (.NET 9)</li><li><strong>RollbackWorker</strong> — Azure Functions (.NET 8)</li><li><strong>Contracts</strong> — Shared contract library (.NET 9)</li><li><strong>Azure Service Bus</strong> — Message broker for async communication</li></ol><h3>Architectural Patterns</h3><h4>1. Microservices Architecture</h4><ul><li>Each service owns its data (SQLite databases)</li><li>Services communicate via HTTP APIs and async messaging</li><li>Loose coupling through well-defined contracts</li></ul><h4>2. Outbox Pattern Implementation</h4><p>The <strong>Outbox Pattern</strong> is implemented in the OrderCoordinator service to ensure reliable message publishing:</p><pre>public sealed class OutboxMessage<br>{<br>    public Guid Id { get; init; } = Guid.NewGuid();<br>    public DateTime OccurredUtc { get; init; } = DateTime.UtcNow;<br>    public string Type { get; init; } = default!;<br>    public string PayloadJson { get; init; } = default!;<br>    public int AttemptCount { get; set; }<br>    public DateTime? LastAttemptUtc { get; set; }</pre><pre>    public static OutboxMessage From&lt;T&gt;(T payload) where T : class<br>        =&gt; new OutboxMessage<br>        {<br>            Type = typeof(T).FullName!,<br>            PayloadJson = JsonSerializer.Serialize(payload)<br>        };<br>}</pre><p><strong>Key Implementation Details:</strong></p><ol><li><strong>Transactional Consistency</strong>: Outbox messages are stored in the same database transaction as business operations</li><li><strong>Background Publisher</strong>: OutboxPublisher runs as a BackgroundService polling for pending messages</li><li><strong>Retry Logic</strong>: Failed messages track attempt counts and timestamps</li><li><strong>At-Least-Once Delivery</strong>: Messages are only removed after successful publishing</li></ol><h4>3. Orchestration-Based Saga Pattern</h4><p>The OrderCoordinator implements an orchestration saga with compensating transactions:</p><pre>// Try-Confirm-Cancel pattern<br>try<br>{<br>    // Try: Reserve inventory<br>    var resResp = await inventory.PostAsJsonAsync(&quot;inventory/reservations&quot;, ...);</pre><pre>    // Try: Authorize payment<br>    var authResp = await payments.PostAsJsonAsync(&quot;payments/authorize&quot;, ...);</pre><pre>    // Confirm both operations<br>    await inventory.PostAsJsonAsync(&quot;inventory/reservations/confirm&quot;, ...);<br>    await payments.PostAsJsonAsync(&quot;payments/capture&quot;, ...);<br>}<br>catch (Exception ex)<br>{<br>    // Compensate on failure<br>    db.Outbox.Add(OutboxMessage.From(new OrderRollbackRequested(...)));<br>}</pre><h4>4. Idempotency Pattern</h4><p>Both the order coordinator and downstream services implement idempotency:</p><pre>// Order coordinator uses idempotency keys<br>var idem = await db.Idempotency.FirstOrDefaultAsync(i =&gt; i.Key == idempotencyKey, ct);<br>if (idem is not null)<br>    return Results.Accepted($&quot;/orders/{idem.ResultOrderId}&quot;, new { orderId = idem.ResultOrderId });</pre><pre>// Downstream services check for existing operations<br>var existing = await db.Authorizations.FirstOrDefaultAsync(a =&gt; a.OrderId == req.OrderId);<br>if (existing is not null)<br>    return Results.Ok(new AuthorizePaymentResponse(existing.AuthorizationId));</pre><h3>Step-by-Step Implementation Guide</h3><h3>Step 1: Design the Outbox Message Entity</h3><p>The foundation of the Outbox Pattern is a database table that stores pending messages. Here’s a well-designed outbox entity:</p><pre>public sealed class OutboxMessage<br>{<br>    public Guid Id { get; init; } = Guid.NewGuid();<br>    public DateTime OccurredUtc { get; init; } = DateTime.UtcNow;<br>    public string Type { get; init; } = default!;<br>    public string PayloadJson { get; init; } = default!;<br>    public int AttemptCount { get; set; }<br>    public DateTime? LastAttemptUtc { get; set; }</pre><pre>    public static OutboxMessage From&lt;T&gt;(T payload) where T : class<br>        =&gt; new OutboxMessage<br>        {<br>            Type = typeof(T).FullName!,<br>            PayloadJson = JsonSerializer.Serialize(payload)<br>        };<br>}</pre><p><strong>Key Design Decisions:</strong></p><ul><li><strong>Immutable core properties</strong>: Id, OccurredUtc, Type, and PayloadJson are set once and never changed</li><li><strong>Tracking metadata</strong>: AttemptCount and LastAttemptUtc support retry logic and monitoring</li><li><strong>Generic serialization</strong>: The From&lt;T&gt; method provides type-safe message creation</li><li><strong>Type information</strong>: Storing the full type name enables proper deserialization</li></ul><h3>Step 2: Integrate with Your Data Model</h3><p>Add the outbox table to your existing DbContext:</p><pre>public sealed class AppDb(DbContextOptions&lt;AppDb&gt; opt) : DbContext(opt)<br>{<br>    public DbSet&lt;OrderRecord&gt; Orders =&gt; Set&lt;OrderRecord&gt;();<br>    public DbSet&lt;IdempotencyRecord&gt; Idempotency =&gt; Set&lt;IdempotencyRecord&gt;();<br>    public DbSet&lt;OutboxMessage&gt; Outbox =&gt; Set&lt;OutboxMessage&gt;();</pre><pre>    protected override void OnModelCreating(ModelBuilder modelBuilder)<br>    {<br>        // Add indexes for efficient querying<br>        modelBuilder.Entity&lt;OutboxMessage&gt;()<br>            .HasIndex(x =&gt; x.OccurredUtc)<br>            .HasDatabaseName(&quot;IX_OutboxMessage_OccurredUtc&quot;);</pre><pre>        modelBuilder.Entity&lt;OutboxMessage&gt;()<br>            .HasIndex(x =&gt; new { x.AttemptCount, x.LastAttemptUtc })<br>            .HasDatabaseName(&quot;IX_OutboxMessage_Retry&quot;);<br>    }<br>}</pre><h3>Step 3: Implement Transactional Message Storage</h3><p>The critical aspect is storing outbox messages within the same database transaction as your business operations:</p><pre>public async Task&lt;IResult&gt; PlaceOrderAsync(CreateOrderDto dto, string idempotencyKey, CancellationToken ct)<br>{<br>    // Check idempotency first<br>    var idem = await db.Idempotency.FirstOrDefaultAsync(i =&gt; i.Key == idempotencyKey, ct);<br>    if (idem is not null)<br>        return Results.Accepted($&quot;/orders/{idem.ResultOrderId}&quot;, new { orderId = idem.ResultOrderId });</pre><pre>    var order = new OrderRecord { Id = Guid.NewGuid(), Amount = dto.Amount, Status = &quot;Pending&quot; };<br>    db.Orders.Add(order);<br>    await db.SaveChangesAsync(ct);</pre><pre>    try<br>    {<br>        // Business logic with external services<br>        await ProcessInventoryReservation(order, dto.Items, ct);<br>        await ProcessPaymentAuthorization(order, ct);<br>        await ConfirmOrderComponents(order, ct);</pre><pre>        order.Status = &quot;Confirmed&quot;;<br>    }<br>    catch (Exception ex)<br>    {<br>        order.Status = &quot;Canceled&quot;;<br>        // Store rollback event in the same transaction<br>        db.Outbox.Add(OutboxMessage.From(new OrderRollbackRequested(<br>            order.Id, <br>            order.InventoryReservationId, <br>            order.PaymentAuthId, <br>            ex.Message)));<br>    }</pre><pre>    // Store idempotency record and save everything atomically<br>    db.Idempotency.Add(new IdempotencyRecord { Key = idempotencyKey, ResultOrderId = order.Id });<br>    await db.SaveChangesAsync(ct);</pre><pre>    return Results.Accepted($&quot;/orders/{order.Id}&quot;, new { orderId = order.Id });<br>}</pre><p><strong>Critical Points:</strong></p><ul><li>Outbox messages are added to the same DbContext as business entities</li><li>A single SaveChangesAsync() call ensures atomicity</li><li>If the transaction fails, neither business data nor outbox messages are persisted</li></ul><h3>Step 4: Build the Background Publisher</h3><p>The background service continuously polls for pending messages and publishes them:</p><pre>public class OutboxPublisher(IServiceProvider sp, IConfiguration cfg, ILogger&lt;OutboxPublisher&gt; log) : BackgroundService<br>{<br>    protected override async Task ExecuteAsync(CancellationToken stoppingToken)<br>    {<br>        var pollSeconds = cfg.GetValue&lt;int?&gt;(&quot;Outbox:PollSeconds&quot;) ?? 1;<br>        var batchSize = cfg.GetValue&lt;int?&gt;(&quot;Outbox:BatchSize&quot;) ?? 100;<br>        var topicName = cfg[&quot;ServiceBus:TopicName&quot;] ?? &quot;orders&quot;;</pre><pre>        while (!stoppingToken.IsCancellationRequested)<br>        {<br>            try<br>            {<br>                await ProcessPendingMessages(batchSize, topicName, stoppingToken);<br>            }<br>            catch (Exception ex)<br>            {<br>                log.LogError(ex, &quot;Outbox processing loop error&quot;);<br>            }</pre><pre>            await Task.Delay(TimeSpan.FromSeconds(pollSeconds), stoppingToken);<br>        }<br>    }</pre><pre>    private async Task ProcessPendingMessages(int batchSize, string topicName, CancellationToken stoppingToken)<br>    {<br>        using var scope = sp.CreateScope();<br>        var db = scope.ServiceProvider.GetRequiredService&lt;AppDb&gt;();<br>        var sbClient = scope.ServiceProvider.GetRequiredService&lt;ServiceBusClient&gt;();<br>        var sender = sbClient.CreateSender(topicName);</pre><pre>        var pending = await db.Outbox<br>            .OrderBy(x =&gt; x.OccurredUtc)<br>            .Take(batchSize)<br>            .ToListAsync(stoppingToken);</pre><pre>        foreach (var message in pending)<br>        {<br>            try<br>            {<br>                await PublishMessage(sender, message, stoppingToken);<br>                db.Outbox.Remove(message);<br>            }<br>            catch (Exception ex)<br>            {<br>                await HandlePublishFailure(message, ex);<br>            }<br>        }</pre><pre>        await db.SaveChangesAsync(stoppingToken);<br>    }</pre><pre>    private async Task PublishMessage(ServiceBusSender sender, OutboxMessage outboxMessage, CancellationToken ct)<br>    {<br>        var message = new ServiceBusMessage(outboxMessage.PayloadJson)<br>        {<br>            Subject = outboxMessage.Type,<br>            MessageId = outboxMessage.Id.ToString(),<br>            ContentType = &quot;application/json&quot;<br>        };</pre><pre>        await sender.SendMessageAsync(message, ct);<br>        log.LogInformation(&quot;Published message {MessageId} of type {Type}&quot;, <br>            outboxMessage.Id, outboxMessage.Type);<br>    }</pre><pre>    private async Task HandlePublishFailure(OutboxMessage message, Exception ex)<br>    {<br>        message.AttemptCount++;<br>        message.LastAttemptUtc = DateTime.UtcNow;</pre><pre>        log.LogWarning(ex, &quot;Failed to publish message {MessageId} (attempt {AttemptCount})&quot;, <br>            message.Id, message.AttemptCount);</pre><pre>        // Implement exponential backoff or dead letter logic here<br>        if (message.AttemptCount &gt;= 5)<br>        {<br>            log.LogError(&quot;Message {MessageId} exceeded max retry attempts&quot;, message.Id);<br>            // Consider moving to dead letter storage<br>        }<br>    }<br>}</pre><h3>Step 5: Configure Dependency Injection</h3><p>Register all components in your DI container:</p><pre>var builder = WebApplication.CreateBuilder(args);</pre><pre>// Database<br>builder.Services.AddDbContext&lt;AppDb&gt;(opt =&gt; <br>    opt.UseSqlite(builder.Configuration.GetConnectionString(&quot;AppDb&quot;)));</pre><pre>// Message Broker<br>builder.Services.AddSingleton(sp =&gt;<br>{<br>    var cfg = sp.GetRequiredService&lt;IConfiguration&gt;();<br>    var conn = cfg[&quot;ServiceBus:ConnectionString&quot;]!;<br>    return new ServiceBusClient(conn);<br>});</pre><pre>// Background Service<br>builder.Services.AddHostedService&lt;OutboxPublisher&gt;();</pre><pre>// HTTP Clients for external services<br>builder.Services.AddHttpClient(&quot;Inventory&quot;, c =&gt;<br>{<br>    c.BaseAddress = new Uri(builder.Configuration[&quot;Services:Inventory&quot;]!);<br>});<br>builder.Services.AddHttpClient(&quot;Payments&quot;, c =&gt;<br>{<br>    c.BaseAddress = new Uri(builder.Configuration[&quot;Services:Payments&quot;]!);<br>});</pre><pre>var app = builder.Build();</pre><pre>// Ensure database is created<br>await using (var scope = app.Services.CreateAsyncScope())<br>{<br>    var db = scope.ServiceProvider.GetRequiredService&lt;AppDb&gt;();<br>    await db.Database.EnsureCreatedAsync();<br>}</pre><h3>Step 6: Add Monitoring and Observability</h3><p>Create an endpoint to monitor outbox health:</p><pre>app.MapGet(&quot;/outbox&quot;, async (AppDb db) =&gt;<br>{<br>    var messages = await db.Outbox<br>        .AsNoTracking()<br>        .OrderBy(x =&gt; x.OccurredUtc)<br>        .ToListAsync();</pre><pre>    return Results.Ok(messages.Select(m =&gt; new <br>    { <br>        m.Id, <br>        m.Type, <br>        m.AttemptCount, <br>        m.LastAttemptUtc, <br>        m.OccurredUtc,<br>        Status = m.AttemptCount == 0 ? &quot;Pending&quot; : <br>                m.AttemptCount &lt; 5 ? &quot;Retrying&quot; : &quot;Failed&quot;<br>    }));<br>});</pre><pre>app.MapGet(&quot;/outbox/health&quot;, async (AppDb db) =&gt;<br>{<br>    var stats = await db.Outbox<br>        .GroupBy(m =&gt; m.AttemptCount == 0 ? &quot;Pending&quot; : <br>                     m.AttemptCount &lt; 5 ? &quot;Retrying&quot; : &quot;Failed&quot;)<br>        .Select(g =&gt; new { Status = g.Key, Count = g.Count() })<br>        .ToListAsync();</pre><pre>    var oldestPending = await db.Outbox<br>        .Where(m =&gt; m.AttemptCount == 0)<br>        .OrderBy(m =&gt; m.OccurredUtc)<br>        .Select(m =&gt; m.OccurredUtc)<br>        .FirstOrDefaultAsync();</pre><pre>    return Results.Ok(new <br>    { <br>        Statistics = stats,<br>        OldestPendingMessage = oldestPending,<br>        HealthStatus = oldestPending == default || <br>                      DateTime.UtcNow - oldestPending &lt; TimeSpan.FromMinutes(5) <br>                      ? &quot;Healthy&quot; : &quot;Warning&quot;<br>    });<br>});</pre><h3>Requirements for Success</h3><h3>1. Transactional Database Support</h3><p>The Outbox Pattern <strong>requires</strong> a database that supports ACID transactions. This includes:</p><ul><li><strong>Relational databases</strong>: PostgreSQL, SQL Server, MySQL, SQLite</li><li><strong>Document databases with transactions</strong>: MongoDB (with replica sets), Azure Cosmos DB</li></ul><p><strong>Note</strong>: Simple key-value stores or eventually consistent databases won’t work for this pattern.</p><h3>2. Exactly-Once Processing Logic</h3><p>Your business logic must be <strong>idempotent</strong> to handle potential duplicate processing:</p><pre>// Always check for existing records<br>var existing = await db.Orders.FirstOrDefaultAsync(o =&gt; o.Id == orderId);<br>if (existing != null)<br>{<br>    return existing; // Idempotent response<br>}</pre><pre>// Proceed with creation only if not exists<br>var order = new OrderRecord { Id = orderId, /* ... */ };</pre><h3>3. Message Ordering Considerations</h3><p>If message order matters, consider these strategies:</p><ul><li><strong>Partition by entity</strong>: Group related messages using partition keys</li><li><strong>Sequence numbers</strong>: Add ordering metadata to messages</li><li><strong>Single-threaded processing</strong>: Process messages sequentially (impacts throughput)</li></ul><h3>4. Error Handling and Dead Letter Management</h3><p>Implement robust retry logic with exponential backoff:</p><pre>private static readonly TimeSpan[] RetryDelays = <br>{<br>    TimeSpan.FromSeconds(1),<br>    TimeSpan.FromSeconds(5),<br>    TimeSpan.FromSeconds(30),<br>    TimeSpan.FromMinutes(5),<br>    TimeSpan.FromMinutes(30)<br>};</pre><pre>private bool ShouldRetry(OutboxMessage message)<br>{<br>    if (message.AttemptCount &gt;= RetryDelays.Length)<br>        return false;</pre><pre>    var nextRetryTime = message.LastAttemptUtc?.Add(RetryDelays[message.AttemptCount - 1]);<br>    return nextRetryTime == null || DateTime.UtcNow &gt;= nextRetryTime;<br>}</pre><h3>5. Performance and Scalability</h3><p>For high-throughput scenarios:</p><ul><li><strong>Batch processing</strong>: Process multiple messages in each iteration</li><li><strong>Parallel processing</strong>: Use multiple worker threads with proper coordination</li><li><strong>Database indexes</strong>: Ensure efficient querying of pending messages</li><li><strong>Message archival</strong>: Remove or archive successfully processed messages</li></ul><h3>Words of Caution</h3><h3>1. Storage Growth Management</h3><p><strong>Critical Warning</strong>: The outbox table can grow rapidly in high-volume systems. Without proper cleanup, it can:</p><ul><li>Consume excessive storage space</li><li>Degrade query performance</li><li>Impact application startup times</li></ul><p><strong>Solution</strong>: Implement message cleanup after successful publishing:</p><pre>// Remove successful messages immediately<br>db.Outbox.Remove(message);</pre><pre>// Or archive for audit purposes<br>message.ProcessedAt = DateTime.UtcNow;<br>message.Status = &quot;Completed&quot;;</pre><h3>2. Message Broker Dependency</h3><p>The background publisher creates a dependency on your message broker. Consider:</p><ul><li><strong>Circuit breaker patterns</strong> for broker outages</li><li><strong>Graceful degradation</strong> when messaging is unavailable</li><li><strong>Health checks</strong> to monitor broker connectivity</li></ul><h3>3. Delayed Message Processing</h3><p>Messages aren’t published immediately; there’s a delay based on your polling interval. This means:</p><ul><li><strong>Near real-time requirements</strong> may not be suitable for this pattern</li><li><strong>Dependent services</strong> must handle eventual consistency</li><li><strong>User expectations</strong> should account for processing delays</li></ul><h3>4. Database Transaction Size</h3><p>Including outbox messages in business transactions can:</p><ul><li><strong>Increase transaction size</strong> and duration</li><li><strong>Impact database performance</strong> under high load</li><li><strong>Create contention</strong> on the outbox table</li></ul><p><strong>Mitigation</strong>: Consider using separate transactions for outbox writes in extreme high-volume scenarios, accepting the risk of lost messages for performance gains.</p><h3>5. Message Duplication Scenarios</h3><p>Despite best efforts, duplicate messages can occur due to:</p><ul><li><strong>Publisher retries</strong> after timeout (message was actually sent)</li><li><strong>Database connection issues</strong> during acknowledgment</li><li><strong>Process crashes</strong> between publishing and cleanup</li></ul><p><strong>Solution</strong>: Always implement idempotent message handlers:</p><pre>public async Task HandleOrderCreated(OrderCreated orderEvent)<br>{<br>    // Check if already processed<br>    var existing = await db.ProcessedEvents<br>        .FirstOrDefaultAsync(e =&gt; e.EventId == orderEvent.Id);</pre><pre>    if (existing != null)<br>    {<br>        log.LogInformation(&quot;Event {EventId} already processed&quot;, orderEvent.Id);<br>        return; // Idempotent exit<br>    }</pre><pre>    // Process the event<br>    await ProcessOrder(orderEvent);</pre><pre>    // Record processing<br>    db.ProcessedEvents.Add(new ProcessedEvent <br>    { <br>        EventId = orderEvent.Id, <br>        ProcessedAt = DateTime.UtcNow <br>    });</pre><pre>    await db.SaveChangesAsync();<br>}</pre><h3>Conclusion</h3><p>The Outbox Pattern is a powerful solution for ensuring reliable message delivery in distributed systems. When implemented correctly, it provides:</p><ul><li><strong>Guaranteed message delivery</strong> with exactly-once semantics</li><li><strong>Data consistency</strong> between local and distributed state</li><li><strong>Resilience</strong> against partial failures</li><li><strong>Auditability</strong> of all system events</li></ul><p>However, success requires careful attention to transactional boundaries, idempotency, error handling, and performance considerations. The pattern is particularly valuable in mission-critical systems where data consistency and reliability are paramount.</p><p>Remember that the Outbox Pattern is one tool in the distributed systems toolkit. Evaluate whether its benefits outweigh the added complexity for your specific use case. For simple scenarios with relaxed consistency requirements, direct message publishing might suffice. For complex, business-critical systems, the Outbox Pattern provides the reliability guarantees that enable robust distributed architectures.</p><p>By following this guide and heeding the cautions outlined, you’ll be well-equipped to implement a production-ready Outbox Pattern that serves as a reliable foundation for your microservices communication strategy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bcff6118ea8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lessons Learned: Building Cloud-Native Microservices with ASP.NET Core 9 for Our Enterprise Client]]></title>
            <link>https://medium.com/@robert_84835/lessons-learned-building-cloud-native-microservices-with-asp-net-core-9-for-our-enterprise-client-5607f85c33ba?source=rss-1a5e3f553f20------2</link>
            <guid isPermaLink="false">https://medium.com/p/5607f85c33ba</guid>
            <dc:creator><![CDATA[Robert Felkins]]></dc:creator>
            <pubDate>Mon, 21 Jul 2025 12:40:53 GMT</pubDate>
            <atom:updated>2025-07-21T12:40:53.386Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MxqJoxGcnnXILP5ZV1GS-w.png" /></figure><p><em>A Real-World Journey from Requirements to Production</em></p><p>Hey fellow developers and architects! 👋</p><p>I am sharing some insights from a recent project we completed for a major retail client who needed to modernize their monolithic e-commerce platform. They came to us with a classic story: “Our system is slow, hard to scale, and every deployment is a nail-biting experience.” Sound familiar?</p><p>After six months of intense development, testing, and deployment, we successfully delivered a cloud-native microservices architecture using ASP.NET Core 9, .NET Aspire, and Kubernetes. Here are the key lessons we learned along the way — the good, the challenging, and the “wish we’d known this earlier” moments.</p><h3>The Client Challenge: Why We Chose ASP.NET Core 9</h3><p>Our client, a mid-size retail company, was struggling with their legacy .NET Framework application. Peak traffic during sales events would bring their system to its knees, and adding new features required coordinating deployments across multiple teams. They needed something modern, scalable, and maintainable.</p><p>After evaluating several options, we landed on ASP.NET Core 9 for several compelling reasons:</p><ul><li><strong>Performance</strong>: The client’s existing .NET expertise meant easier team adoption</li><li><strong>Container-First Approach</strong>: Perfect fit for their cloud-native aspirations</li><li><strong>Microsoft Ecosystem</strong>: They were already invested in Azure</li><li><strong>Long-term Support</strong>: .NET 9’s roadmap aligned with their strategic plans</li></ul><p>But here’s the first lesson: <strong>choose your stack based on team capabilities, not just technical superiority</strong>. We could have gone with Go or Node.js, but the learning curve would have extended our timeline by months.</p><h3>Lesson #1: .NET Aspire is a Game-Changer (But Mind the Learning Curve)</h3><p>When we first heard about .NET Aspire, I’ll be honest — I was skeptical. “Another framework to learn?” But after our initial spike, it became clear this wasn’t just hype.</p><h3>What Aspire Got Right</h3><p>Here’s how we structured our Aspire host for the client’s catalog and inventory services:</p><pre>var builder = DistributedApplication.CreateBuilder(args);</pre><pre>// Infrastructure components<br>var postgres = builder.AddPostgres(&quot;postgres&quot;, port: 5432)<br>    .WithDatabase(&quot;catalogdb&quot;)<br>    .WithDatabase(&quot;inventorydb&quot;);</pre><pre>var redis = builder.AddRedis(&quot;cache&quot;);</pre><pre>var serviceBus = builder.AddAzureServiceBus(&quot;messaging&quot;);</pre><pre>// Our microservices<br>var catalogApi = builder.AddProject&lt;Projects.CatalogApi&gt;(&quot;catalog-api&quot;)<br>    .WithReference(postgres.GetDatabase(&quot;catalogdb&quot;))<br>    .WithReference(redis)<br>    .WithReference(serviceBus);</pre><pre>var inventoryApi = builder.AddProject&lt;Projects.InventoryApi&gt;(&quot;inventory-api&quot;)<br>    .WithReference(postgres.GetDatabase(&quot;inventorydb&quot;))<br>    .WithReference(redis)<br>    .WithReference(serviceBus);</pre><pre>var webApp = builder.AddProject&lt;Projects.WebApp&gt;(&quot;webapp&quot;)<br>    .WithReference(catalogApi)<br>    .WithReference(inventoryApi)<br>    .WithExternalHttpEndpoints();</pre><pre>builder.Build().Run();</pre><p><strong>The Magic</strong>: With just this configuration, we got:</p><ul><li>Automatic service discovery</li><li>Centralized configuration management</li><li>Built-in observability with OpenTelemetry</li><li>A gorgeous dashboard for local development</li></ul><p><strong>The Reality Check</strong>: Our junior developers initially struggled with the “magic.” When things worked, they worked beautifully. When they didn’t, debugging required understanding several abstraction layers.</p><p><strong>Lesson Learned</strong>: Invest time upfront training your team on Aspire’s internals. The productivity gains are massive once everyone understands what’s happening under the hood.</p><h3>Lesson #2: Container Optimization Matters More Than You Think</h3><p>One of our early mistakes was treating containerization as an afterthought. “We’ll just add a Dockerfile at the end,” we thought. Wrong approach.</p><h3>The Problem We Hit</h3><p>Our initial container images were over 1GB, and startup times were exceeding 30 seconds in production. For a retail client expecting sub-second response times, this was unacceptable.</p><h3>The Solution: Multi-Stage Builds and Alpine Images</h3><p>Here’s the optimized Dockerfile we ended up with:</p><pre># Build stage<br>FROM mcr.microsoft.com/dotnet/sdk:9.0-alpine AS build<br>WORKDIR /src</pre><pre># Copy project files and restore dependencies<br>COPY [&quot;CatalogApi/CatalogApi.csproj&quot;, &quot;CatalogApi/&quot;]<br>COPY [&quot;CatalogApi.ServiceDefaults/CatalogApi.ServiceDefaults.csproj&quot;, &quot;CatalogApi.ServiceDefaults/&quot;]<br>RUN dotnet restore &quot;CatalogApi/CatalogApi.csproj&quot;</pre><pre># Copy source and build<br>COPY . .<br>WORKDIR &quot;/src/CatalogApi&quot;<br>RUN dotnet build &quot;CatalogApi.csproj&quot; -c Release -o /app/build</pre><pre># Publish stage<br>FROM build AS publish<br>RUN dotnet publish &quot;CatalogApi.csproj&quot; -c Release -o /app/publish /p:UseAppHost=false</pre><pre># Runtime stage<br>FROM mcr.microsoft.com/dotnet/aspnet:9.0-alpine AS final<br>RUN apk add --no-cache icu-libs<br>ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=false<br>WORKDIR /app<br>COPY --from=publish /app/publish .</pre><pre># Create non-root user<br>RUN adduser -D -s /bin/sh appuser<br>USER appuser</pre><pre>EXPOSE 8080<br>ENTRYPOINT [&quot;dotnet&quot;, &quot;CatalogApi.dll&quot;]</pre><p><strong>Results</strong>: Image size dropped to 180MB, startup time reduced to under 5 seconds.</p><p><strong>Lesson Learned</strong>: Container optimization isn’t just about size — it’s about security, startup time, and resource utilization. Start optimizing from day one, not as an afterthought.</p><h3>Lesson #3: Service Communication Strategy is Critical</h3><p>Initially, we went HTTP-everywhere. Every service talked to every other service via HTTP APIs. This seemed clean and RESTful, but we quickly ran into issues during peak loads.</p><h3>The HTTP-Only Approach (Our First Attempt)</h3><pre>// This seemed fine initially...<br>public class OrderService<br>{<br>    private readonly HttpClient _inventoryClient;<br>    private readonly HttpClient _catalogClient;<br>    private readonly HttpClient _paymentClient;</pre><pre>    public async Task&lt;OrderResult&gt; CreateOrderAsync(CreateOrderRequest request)<br>    {<br>        // Check inventory<br>        var inventory = await _inventoryClient.GetAsync($&quot;api/inventory/{request.ProductId}&quot;);<br>        <br>        // Get product details<br>        var product = await _catalogClient.GetAsync($&quot;api/products/{request.ProductId}&quot;);<br>        <br>        // Process payment<br>        var payment = await _paymentClient.PostAsync(&quot;api/payments&quot;, paymentData);<br>        <br>        // Create order...<br>    }<br>}</pre><p><strong>The Problem</strong>: During Black Friday testing, we discovered cascade failures. One slow service would cause timeouts across the entire chain.</p><h3>The Hybrid Approach (Our Solution)</h3><p>We implemented a hybrid communication strategy:</p><p><strong>Synchronous (HTTP) for</strong>:</p><ul><li>User-facing operations requiring immediate response</li><li>Operations needing strong consistency</li></ul><p><strong>Asynchronous (Message Bus) for</strong>:</p><ul><li>Business events and notifications</li><li>Operations that can be eventually consistent</li></ul><pre>public class OrderService<br>{<br>    private readonly IInventoryService _inventoryService;<br>    private readonly IMessageBus _messageBus;</pre><pre>    public async Task&lt;OrderResult&gt; CreateOrderAsync(CreateOrderRequest request)<br>    {<br>        // Sync: Check inventory (needs immediate response)<br>        var inventoryStatus = await _inventoryService.CheckAvailabilityAsync(request.ProductId);<br>        <br>        if (!inventoryStatus.IsAvailable)<br>            return OrderResult.Failed(&quot;Product not available&quot;);</pre><pre>        // Create order first<br>        var order = await CreateOrderRecordAsync(request);</pre><pre>        // Async: Publish events for other services to handle<br>        await _messageBus.PublishAsync(new OrderCreatedEvent <br>        { <br>            OrderId = order.Id,<br>            ProductId = request.ProductId,<br>            Quantity = request.Quantity,<br>            CustomerId = request.CustomerId<br>        });</pre><pre>        return OrderResult.Success(order.Id);<br>    }<br>}</pre><p><strong>Lesson Learned</strong>: Don’t default to all-sync or all-async. Choose the right communication pattern based on business requirements, not technical preferences.</p><h3>Lesson #4: Observability Can’t Be Bolted On Later</h3><p>We initially focused on getting features working, planning to “add monitoring later.” This was a mistake that cost us significant debugging time during UAT.</p><h3>What We Should Have Done From Day One</h3><p>Aspire gives you observability out of the box, but you need to instrument your business logic properly:</p><pre>public class ProductService<br>{<br>    private static readonly ActivitySource ActivitySource = new(&quot;CatalogApi.Products&quot;);<br>    private static readonly Counter&lt;int&gt; ProductsCreated = <br>        Meter.CreateCounter&lt;int&gt;(&quot;products_created_total&quot;);<br>    <br>    public async Task&lt;Product&gt; CreateProductAsync(CreateProductRequest request)<br>    {<br>        using var activity = ActivitySource.StartActivity(&quot;CreateProduct&quot;);<br>        activity?.SetTag(&quot;product.category&quot;, request.Category);<br>        activity?.SetTag(&quot;product.price&quot;, request.Price);</pre><pre>        try <br>        {<br>            var product = new Product <br>            {<br>                Name = request.Name,<br>                Category = request.Category,<br>                Price = request.Price<br>            };</pre><pre>            await _context.Products.AddAsync(product);<br>            await _context.SaveChangesAsync();</pre><pre>            ProductsCreated.Add(1, <br>                new KeyValuePair&lt;string, object&gt;(&quot;category&quot;, request.Category));</pre><pre>            _logger.LogInformation(&quot;Product created: {ProductId} in category {Category}&quot;, <br>                product.Id, product.Category);</pre><pre>            activity?.SetStatus(ActivityStatusCode.Ok);<br>            return product;<br>        }<br>        catch (Exception ex)<br>        {<br>            activity?.SetStatus(ActivityStatusCode.Error, ex.Message);<br>            _logger.LogError(ex, &quot;Failed to create product&quot;);<br>            throw;<br>        }<br>    }<br>}</pre><p><strong>The Aspire Dashboard Advantage</strong>: During development, we could see all our traces, metrics, and logs in one place. No more switching between multiple tools or guessing which service was causing issues.</p><p><strong>Lesson Learned</strong>: Build observability into your code from the first commit. The Aspire dashboard makes local development debugging incredibly efficient, and the same instrumentation works in production.</p><h3>Lesson #5: Kubernetes Deployment Complexity is Real</h3><p>Moving from local Aspire development to Kubernetes production was our biggest challenge. The gap between “works on my machine with Aspire” and “works in Kubernetes” was larger than expected.</p><h3>The Configuration Management Challenge</h3><p>In Aspire, configuration “just works”:</p><pre>// This works magically in Aspire<br>builder.AddNpgsqlDbContext&lt;CatalogDbContext&gt;(&quot;catalogdb&quot;);</pre><p>In Kubernetes, you need explicit configuration:</p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: catalog-api-config<br>data:<br>  ConnectionStrings__CatalogDb: &quot;Host=postgres-service;Port=5432;Database=catalogdb;Username=cataloguser&quot;<br>  Redis__ConnectionString: &quot;redis-service:6379&quot;<br>  ServiceBus__ConnectionString: &quot;Endpoint=sb://myservicebus.servicebus.windows.net/&quot;<br>---<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: catalog-api<br>spec:<br>  replicas: 3<br>  template:<br>    spec:<br>      containers:<br>      - name: catalog-api<br>        image: myregistry.azurecr.io/catalog-api:latest<br>        envFrom:<br>        - configMapRef:<br>            name: catalog-api-config<br>        - secretRef:<br>            name: catalog-api-secrets<br>        ports:<br>        - containerPort: 8080<br>        livenessProbe:<br>          httpGet:<br>            path: /health/live<br>            port: 8080<br>          initialDelaySeconds: 30<br>        readinessProbe:<br>          httpGet:<br>            path: /health/ready<br>            port: 8080<br>          initialDelaySeconds: 10</pre><h3>Health Checks Saved Our Deployment</h3><p>We learned the hard way that proper health checks are essential:</p><pre>// In Program.cs<br>builder.Services.AddHealthChecks()<br>    .AddCheck(&quot;self&quot;, () =&gt; HealthCheckResult.Healthy())<br>    .AddNpgSql(connectionString, name: &quot;database&quot;)<br>    .AddRedis(redisConnectionString, name: &quot;redis&quot;)<br>    .AddCheck&lt;InventoryServiceHealthCheck&gt;(&quot;inventory-service&quot;);</pre><pre>app.MapHealthChecks(&quot;/health/live&quot;, new HealthCheckOptions<br>{<br>    Predicate = check =&gt; check.Name == &quot;self&quot;<br>});</pre><pre>app.MapHealthChecks(&quot;/health/ready&quot;, new HealthCheckOptions<br>{<br>    Predicate = check =&gt; check.Tags.Contains(&quot;ready&quot;)<br>});</pre><p><strong>Lesson Learned</strong>: Aspire generates Kubernetes manifests, but you’ll still need to understand and customize them. Don’t assume the generated manifests are production-ready without review.</p><h3>Lesson #6: Performance Testing Early Prevents Late Surprises</h3><p>We thought our microservices would naturally be more performant than the monolith. We were wrong.</p><h3>The Latency Discovery</h3><p>During load testing, we discovered that our microservices architecture had introduced significant latency:</p><ul><li><strong>Monolith</strong>: Average response time 200ms</li><li><strong>Our Microservices</strong>: Average response time 800ms</li></ul><p>The culprit? Network calls and serialization overhead.</p><h3>Our Performance Recovery Strategy</h3><ol><li><strong>Caching Strategy</strong>: Implemented Redis caching at multiple levels</li></ol><pre>public class CachedProductService : IProductService<br>{<br>    private readonly IProductService _productService;<br>    private readonly IDistributedCache _cache;<br>    private readonly TimeSpan _cacheDuration = TimeSpan.FromMinutes(15);</pre><pre>    public async Task&lt;Product&gt; GetProductAsync(int productId)<br>    {<br>        var cacheKey = $&quot;product:{productId}&quot;;<br>        var cachedProduct = await _cache.GetStringAsync(cacheKey);<br>        <br>        if (cachedProduct != null)<br>            return JsonSerializer.Deserialize&lt;Product&gt;(cachedProduct);</pre><pre>        var product = await _productService.GetProductAsync(productId);<br>        <br>        if (product != null)<br>        {<br>            var serializedProduct = JsonSerializer.Serialize(product);<br>            await _cache.SetStringAsync(cacheKey, serializedProduct, <br>                new DistributedCacheEntryOptions <br>                { <br>                    AbsoluteExpirationRelativeToNow = _cacheDuration <br>                });<br>        }</pre><pre>        return product;<br>    }<br>}</pre><ol><li><strong>Connection Pooling</strong>: Properly configured database connections</li></ol><pre>builder.Services.AddNpgsqlDbContext&lt;CatalogDbContext&gt;(connectionString, options =&gt;<br>{<br>    options.EnableSensitiveDataLogging(false);<br>    options.EnableServiceProviderCaching();<br>    options.EnableDetailedErrors(false);<br>});</pre><pre>// Configure connection pool<br>builder.Services.Configure&lt;NpgsqlDbContextOptionsBuilder&gt;(options =&gt;<br>{<br>    options.EnableRetryOnFailure(maxRetryCount: 3, maxRetryDelay: TimeSpan.FromSeconds(5), null);<br>});</pre><ol><li><strong>Async All the Way</strong>: Eliminated blocking calls</li></ol><p><strong>Final Results</strong>: Brought average response time down to 250ms — better than the original monolith.</p><p><strong>Lesson Learned</strong>: Microservices don’t automatically mean better performance. You need to be intentional about latency, caching, and resource utilization.</p><h3>Lesson #7: The Deployment Pipeline is as Important as the Code</h3><p>Setting up a reliable CI/CD pipeline took almost as much effort as writing the application code, but it was absolutely worth it.</p><h3>Our Final Pipeline Strategy</h3><pre># .github/workflows/deploy-production.yml<br>name: Production Deployment</pre><pre>on:<br>  push:<br>    branches: [main]<br>    tags: [&#39;v*&#39;]</pre><pre>jobs:<br>  test:<br>    runs-on: ubuntu-latest<br>    steps:<br>    - uses: actions/checkout@v4<br>    - name: Setup .NET<br>      uses: actions/setup-dotnet@v4<br>      with:<br>        dotnet-version: &#39;9.0.x&#39;<br>    <br>    - name: Run tests<br>      run: |<br>        dotnet restore<br>        dotnet test --configuration Release --logger trx --collect:&quot;XPlat Code Coverage&quot;<br>    <br>    - name: Upload test results<br>      uses: actions/upload-artifact@v3<br>      with:<br>        name: test-results<br>        path: &#39;**/*.trx&#39;</pre><pre>  security-scan:<br>    runs-on: ubuntu-latest<br>    steps:<br>    - uses: actions/checkout@v4<br>    - name: Run security scan<br>      uses: securecodewarrior/github-action-add-sarif@v1<br>      with:<br>        sarif-file: &#39;security-scan-results.sarif&#39;</pre><pre>  build-and-deploy:<br>    needs: [test, security-scan]<br>    runs-on: ubuntu-latest<br>    steps:<br>    - name: Build and push images<br>      run: |<br>        docker build -t $REGISTRY/catalog-api:$GITHUB_SHA .<br>        docker build -t $REGISTRY/inventory-api:$GITHUB_SHA .<br>        docker push $REGISTRY/catalog-api:$GITHUB_SHA<br>        docker push $REGISTRY/inventory-api:$GITHUB_SHA<br>    <br>    - name: Deploy to staging<br>      run: |<br>        kubectl set image deployment/catalog-api catalog-api=$REGISTRY/catalog-api:$GITHUB_SHA<br>        kubectl rollout status deployment/catalog-api<br>    <br>    - name: Run smoke tests<br>      run: |<br>        npm install<br>        npm run test:smoke<br>    <br>    - name: Deploy to production<br>      if: startsWith(github.ref, &#39;refs/tags/v&#39;)<br>      run: |<br>        kubectl set image deployment/catalog-api catalog-api=$REGISTRY/catalog-api:$GITHUB_SHA --namespace=production</pre><p><strong>Lesson Learned</strong>: Invest in your deployment pipeline early. Automated testing, security scanning, and staged deployments saved us from multiple production incidents.</p><h3>What We’d Do Differently Next Time</h3><h3>1. Start with Aspire Service Defaults Earlier</h3><p>We initially wrote a lot of boilerplate configuration code that Aspire’s service defaults would have handled for us:</p><pre>// Instead of writing all this manually...<br>builder.Services.AddOpenTelemetry()<br>    .WithMetrics(...)<br>    .WithTracing(...);<br>    <br>builder.Services.AddServiceDiscovery();<br>builder.Services.AddHealthChecks();</pre><pre>// Just use this from day one:<br>builder.AddServiceDefaults();</pre><h3>2. Plan Data Consistency Strategy Upfront</h3><p>We underestimated the complexity of managing data consistency across microservices. Implementing the saga pattern later was painful.</p><h3>3. Invest in Contract Testing</h3><p>API contract changes between services caused integration issues. Tools like Pact would have caught these earlier.</p><h3>4. Set Resource Limits from the Beginning</h3><p>We experienced resource contention in Kubernetes because we didn’t set proper CPU and memory limits initially.</p><h3>The Bottom Line: Was It Worth It?</h3><p>Absolutely. Six months later, our client is seeing:</p><ul><li><strong>99.9% uptime</strong> (vs. 95% with the monolith)</li><li><strong>50% faster feature delivery</strong> (independent service deployments)</li><li><strong>3x better performance</strong> during peak traffic</li><li><strong>Reduced operational costs</strong> (better resource utilization)</li></ul><p>But more importantly, their development teams are happier and more productive.</p><h3>Final Thoughts for Fellow Consultants</h3><p>Building microservices with ASP.NET Core 9 and .NET Aspire isn’t just about the technology — it’s about the entire ecosystem:</p><ol><li><strong>Team Readiness</strong>: Ensure your team understands distributed systems concepts</li><li><strong>Client Education</strong>: Help clients understand the complexity trade-offs</li><li><strong>Incremental Approach</strong>: Don’t try to rebuild everything at once</li><li><strong>Observability First</strong>: Build monitoring and logging from day one</li><li><strong>Performance Testing</strong>: Load test early and often</li></ol><p>.NET Aspire genuinely changes the game for building cloud-native applications, but it’s not a silver bullet. Success still requires solid architecture decisions, proper testing, and a team that understands distributed systems.</p><p>Would I recommend ASP.NET Core 9 and Aspire for similar projects? Absolutely. The developer experience improvements and production-ready defaults make it a compelling choice for teams building modern, cloud-native applications.</p><p>What’s your experience been with ASP.NET Core 9 or .NET Aspire? I’d love to hear about your lessons learned in the comments!</p><p><em>Want to discuss this project or need help with your own microservices architecture? Feel free to reach out — always happy to chat about .NET, architecture, and lessons learned in the trenches.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5607f85c33ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supercharge Your Testing with GitHub Copilot: Generating MSTest DataRows for an Onion Style…]]></title>
            <link>https://medium.com/@robert_84835/supercharge-your-testing-with-github-copilot-generating-mstest-datarows-for-an-onion-style-08cf924b9f44?source=rss-1a5e3f553f20------2</link>
            <guid isPermaLink="false">https://medium.com/p/08cf924b9f44</guid>
            <dc:creator><![CDATA[Robert Felkins]]></dc:creator>
            <pubDate>Fri, 11 Jul 2025 19:38:00 GMT</pubDate>
            <atom:updated>2025-07-11T19:38:00.177Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HCpBzRxhOK19Mm_GeMOv8Q.png" /></figure><h3>Supercharge Your Testing with GitHub Copilot: Generating MSTest DataRows for an Onion Style Architecture</h3><p>Testing is the backbone of reliable software development, yet it’s often the most time-consuming aspect of building robust applications. Suppose you’re working with an Onion Architecture (also known as Clean Architecture) service and need to test both your controller and business layers thoroughly. In that case, GitHub Copilot can be your secret weapon for generating comprehensive MSTest suites with DataRows that efficiently cover multiple test scenarios.</p><p>In this comprehensive guide, we’ll explore how to leverage GitHub Copilot’s AI-powered code generation to create sophisticated test suites that validate your onion architecture’s controller and business layers. We’ll cover practical techniques, provide real-world examples, and share expert tips to maximize your testing productivity.</p><h3>Understanding Onion Architecture Testing Challenges</h3><p>Before diving into Copilot techniques, let’s briefly review the testing challenges in onion architecture:</p><ol><li><strong>Controller Layer</strong>: HTTP concerns, request/response mapping, validation, authorization</li><li><strong>Business Layer</strong>: Core business logic, domain rules, orchestration between services</li><li><strong>Data Layer</strong>: Repository patterns, data access, entity mapping</li></ol><p>Each layer requires different testing approaches, and DataRows help us test multiple scenarios without code duplication.</p><h3>Setting Up Your Testing Environment</h3><p>First, ensure your test project has the necessary NuGet packages:</p><pre>&lt;PackageReference Include=&quot;Microsoft.NET.Test.Sdk&quot; Version=&quot;17.6.0&quot; /&gt;<br>&lt;PackageReference Include=&quot;MSTest.TestAdapter&quot; Version=&quot;3.0.4&quot; /&gt;<br>&lt;PackageReference Include=&quot;MSTest.TestFramework&quot; Version=&quot;3.0.4&quot; /&gt;<br>&lt;PackageReference Include=&quot;Moq&quot; Version=&quot;4.20.69&quot; /&gt;<br>&lt;PackageReference Include=&quot;Microsoft.AspNetCore.Mvc.Testing&quot; Version=&quot;7.0.0&quot; /&gt;</pre><h3>Effective Prompts for Controller Layer Testing</h3><h3>Basic Controller Test Generation</h3><p><strong>Prompt:</strong></p><pre>Generate MSTest with DataRows for testing a UserController PostUser action that accepts CreateUserRequest and returns UserResponse. Test cases should include valid user creation, invalid email format, missing required fields, and duplicate username scenarios. Use AAA pattern and include proper assertions.</pre><p><strong>Generated Result:</strong></p><pre>[TestClass]<br>public class UserControllerTests<br>{<br>    private UserController _controller;<br>    private Mock&lt;IUserService&gt; _mockUserService;</pre><pre>    [TestInitialize]<br>    public void Setup()<br>    {<br>        _mockUserService = new Mock&lt;IUserService&gt;();<br>        _controller = new UserController(_mockUserService.Object);<br>    }</pre><pre>    [TestMethod]<br>    [DataRow(&quot;john.doe@email.com&quot;, &quot;John&quot;, &quot;Doe&quot;, &quot;johndoe&quot;, true, &quot;User created successfully&quot;)]<br>    [DataRow(&quot;invalid-email&quot;, &quot;John&quot;, &quot;Doe&quot;, &quot;johndoe&quot;, false, &quot;Invalid email format&quot;)]<br>    [DataRow(&quot;&quot;, &quot;John&quot;, &quot;Doe&quot;, &quot;johndoe&quot;, false, &quot;Email is required&quot;)]<br>    [DataRow(&quot;john.doe@email.com&quot;, &quot;&quot;, &quot;Doe&quot;, &quot;johndoe&quot;, false, &quot;First name is required&quot;)]<br>    [DataRow(&quot;john.doe@email.com&quot;, &quot;John&quot;, &quot;Doe&quot;, &quot;&quot;, false, &quot;Username is required&quot;)]<br>    [DataRow(&quot;existing@email.com&quot;, &quot;John&quot;, &quot;Doe&quot;, &quot;existinguser&quot;, false, &quot;Username already exists&quot;)]<br>    public async Task PostUser_WithVariousInputs_ReturnsExpectedResults(<br>        string email, string firstName, string lastName, string username, <br>        bool shouldSucceed, string expectedMessage)<br>    {<br>        // Arrange<br>        var request = new CreateUserRequest<br>        {<br>            Email = email,<br>            FirstName = firstName,<br>            LastName = lastName,<br>            Username = username<br>        };</pre><pre>        if (shouldSucceed)<br>        {<br>            _mockUserService.Setup(x =&gt; x.CreateUserAsync(It.IsAny&lt;CreateUserRequest&gt;()))<br>                .ReturnsAsync(new UserResponse { Id = 1, Message = expectedMessage });<br>        }<br>        else<br>        {<br>            _mockUserService.Setup(x =&gt; x.CreateUserAsync(It.IsAny&lt;CreateUserRequest&gt;()))<br>                .ThrowsAsync(new ValidationException(expectedMessage));<br>        }</pre><pre>        // Act<br>        var result = shouldSucceed <br>            ? await _controller.PostUser(request) as OkObjectResult<br>            : await _controller.PostUser(request) as BadRequestObjectResult;</pre><pre>        // Assert<br>        Assert.IsNotNull(result);<br>        if (shouldSucceed)<br>        {<br>            var response = result.Value as UserResponse;<br>            Assert.AreEqual(expectedMessage, response.Message);<br>        }<br>        else<br>        {<br>            Assert.IsTrue(result.Value.ToString().Contains(expectedMessage));<br>        }<br>    }<br>}</pre><h3>Advanced Authorization Testing</h3><p><strong>Prompt:</strong></p><pre>Create MSTest DataRows for testing authorization in ProductController GetProducts action. Include test cases for admin role (full access), user role (own products only), guest (no access), expired token, and invalid token scenarios. Mock IAuthorizationService and include proper HTTP status code assertions.</pre><h3>Business Layer Testing Strategies</h3><h3>Domain Logic Validation</h3><p><strong>Prompt:</strong></p><pre>Generate MSTest with DataRows for OrderService CalculateTotal method in business layer. Test scenarios: normal order with multiple items, order with discounts, order with tax calculations, empty order, order with invalid quantities, and order with expired promotions. Include edge cases and boundary conditions.</pre><p><strong>Generated Result:</strong></p><pre>[TestClass]<br>public class OrderServiceTests<br>{<br>    private OrderService _orderService;<br>    private Mock&lt;IDiscountRepository&gt; _mockDiscountRepo;<br>    private Mock&lt;ITaxCalculator&gt; _mockTaxCalculator;</pre><pre>    [TestInitialize]<br>    public void Setup()<br>    {<br>        _mockDiscountRepo = new Mock&lt;IDiscountRepository&gt;();<br>        _mockTaxCalculator = new Mock&lt;ITaxCalculator&gt;();<br>        _orderService = new OrderService(_mockDiscountRepo.Object, _mockTaxCalculator.Object);<br>    }</pre><pre>    [TestMethod]<br>    [DataRow(new double[] { 10.00, 20.00, 15.00 }, new int[] { 2, 1, 3 }, 0.0, 0.10, 96.25)]<br>    [DataRow(new double[] { 100.00 }, new int[] { 1 }, 10.0, 0.08, 97.20)]<br>    [DataRow(new double[] { 50.00, 30.00 }, new int[] { 1, 2 }, 15.0, 0.12, 100.80)]<br>    [DataRow(new double[] { }, new int[] { }, 0.0, 0.0, 0.0)]<br>    [DataRow(new double[] { 25.00 }, new int[] { 0 }, 0.0, 0.0, 0.0)]<br>    public void CalculateTotal_WithVariousOrderConfigurations_ReturnsCorrectTotal(<br>        double[] itemPrices, int[] quantities, double discountPercent, <br>        double taxRate, double expectedTotal)<br>    {<br>        // Arrange<br>        var orderItems = new List&lt;OrderItem&gt;();<br>        for (int i = 0; i &lt; itemPrices.Length; i++)<br>        {<br>            if (i &lt; quantities.Length &amp;&amp; quantities[i] &gt; 0)<br>            {<br>                orderItems.Add(new OrderItem <br>                { <br>                    Price = itemPrices[i], <br>                    Quantity = quantities[i] <br>                });<br>            }<br>        }</pre><pre>        var order = new Order { Items = orderItems };</pre><pre>        _mockDiscountRepo.Setup(x =&gt; x.GetApplicableDiscount(It.IsAny&lt;Order&gt;()))<br>            .Returns(discountPercent);<br>        _mockTaxCalculator.Setup(x =&gt; x.CalculateTax(It.IsAny&lt;double&gt;()))<br>            .Returns&lt;double&gt;(amount =&gt; amount * taxRate);</pre><pre>        // Act<br>        var result = _orderService.CalculateTotal(order);</pre><pre>        // Assert<br>        Assert.AreEqual(expectedTotal, result, 0.01);<br>    }<br>}</pre><h3>Complex Business Rules Testing</h3><p><strong>Prompt:</strong></p><pre>Create comprehensive MSTest DataRows for InventoryService ProcessRestockOrder method. Test scenarios include: sufficient stock levels, insufficient stock with backorder, priority customer handling, seasonal restrictions, vendor availability, quantity limits, and concurrent stock updates. Use realistic business scenarios and include proper exception handling tests.</pre><h3>Advanced Copilot Techniques</h3><h3>Using Context-Aware Prompts</h3><p><strong>Effective Strategy:</strong> Start your prompts with existing code context to get more accurate results.</p><p><strong>Prompt:</strong></p><pre>Based on this existing UserService interface:<br>```csharp<br>public interface IUserService<br>{<br>    Task&lt;UserResponse&gt; CreateUserAsync(CreateUserRequest request);<br>    Task&lt;UserResponse&gt; GetUserByIdAsync(int id);<br>    Task&lt;bool&gt; DeleteUserAsync(int id);<br>}</pre><p>Generate MSTest with DataRows for UserService implementation testing all methods. Include positive cases, negative cases, async exception handling, and edge cases. Mock dependencies appropriately.</p><pre>### Chaining Prompts for Complex Scenarios</pre><pre>**Initial Prompt:**</pre><p>Generate MSTest DataRows for PaymentService ProcessPayment method with basic scenarios: successful payment, insufficient funds, invalid card, expired card.</p><pre>**Follow-up Prompt:**</pre><p>Extend the previous PaymentService tests with additional DataRows for: fraud detection triggers, currency conversion scenarios, refund processing, partial payments, and payment gateway timeout handling.</p><pre>### Integration Testing with Copilot</pre><pre>**Prompt:**</pre><p>Create MSTest integration tests with DataRows for e-commerce checkout workflow spanning controller and business layers. Test complete user journey: add to cart, apply discount, calculate shipping, process payment, update inventory. Use TestServer and realistic data scenarios.</p><pre>## Best Practices and Pro Tips</pre><pre>### 1. Structure Your Prompts Effectively</pre><pre>**Good Prompt Structure:**<br>- Context (what you&#39;re testing)<br>- Specific requirements (DataRows, scenarios)<br>- Technical constraints (frameworks, patterns)<br>- Expected outcomes (assertions, exceptions)</pre><pre>### 2. Leverage Copilot for Test Data Generation</pre><pre>**Prompt:**</pre><p>Generate realistic test data objects for e-commerce testing including: valid/invalid credit cards, international addresses, product catalogs with various categories, user profiles with different roles, and order histories with edge cases.</p><pre>### 3. Use Copilot for Mock Setup</pre><pre>**Prompt:**</pre><p>Generate Moq setup code for testing OrderController that depends on IOrderService, IPaymentService, and IInventoryService. Include different return scenarios for each dependency and proper verify calls.</p><pre>### 4. Exception Testing Patterns</pre><pre>**Prompt:**</pre><p>Create MSTest DataRows for testing exception scenarios in UserRegistrationService. Include: ArgumentNullException for null inputs, ValidationException for invalid data, DuplicateUserException for existing users, and ServiceUnavailableException for external service failures.</p><pre>## Complex Real-World Example</pre><pre>Let&#39;s create a comprehensive test suite for an order processing system:</pre><pre>**Prompt:**</pre><p>Generate a complete MSTest suite with DataRows for OrderProcessingService in an e-commerce onion architecture. Include controller tests for OrderController endpoints and business layer tests for OrderService. Cover scenarios: new order creation, order status updates, inventory validation, payment processing, shipping calculations, order cancellation, refund processing, and concurrent order handling. Use realistic e-commerce data and include proper mocking of dependencies.</p><pre>**Generated Result Structure:**<br>```csharp<br>[TestClass]<br>public class OrderProcessingIntegrationTests<br>{<br>    // Controller Layer Tests<br>    [TestMethod]<br>    [DataRow(&quot;valid-order.json&quot;, 201, &quot;Order created successfully&quot;)]<br>    [DataRow(&quot;invalid-payment.json&quot;, 400, &quot;Payment method invalid&quot;)]<br>    [DataRow(&quot;insufficient-inventory.json&quot;, 409, &quot;Insufficient stock&quot;)]<br>    public async Task CreateOrder_WithVariousScenarios_ReturnsExpectedResults(<br>        string testDataFile, int expectedStatusCode, string expectedMessage)<br>    {<br>        // Implementation here<br>    }</pre><pre>    // Business Layer Tests<br>    [TestMethod]<br>    [DataRow(OrderStatus.Pending, OrderStatus.Processing, true)]<br>    [DataRow(OrderStatus.Processing, OrderStatus.Shipped, true)]<br>    [DataRow(OrderStatus.Shipped, OrderStatus.Delivered, true)]<br>    [DataRow(OrderStatus.Delivered, OrderStatus.Processing, false)]<br>    public void UpdateOrderStatus_WithStatusTransitions_ValidatesBusinessRules(<br>        OrderStatus currentStatus, OrderStatus newStatus, bool shouldSucceed)<br>    {<br>        // Implementation here<br>    }<br>}</pre><h3>Debugging and Refinement Tips</h3><h3>1. Iterative Improvement</h3><p>Start with basic tests and refine:</p><p><strong>Initial Prompt:</strong></p><pre>Generate basic MSTest for UserController Login method</pre><p><strong>Refinement Prompt:</strong></p><pre>Add DataRows to the previous UserController Login test for: valid credentials, invalid password, non-existent user, locked account, expired password, and rate limiting scenarios</pre><h3>2. Copilot-Assisted Test Maintenance</h3><p><strong>Prompt:</strong></p><pre>Update the existing UserService tests to include new DataRows for: two-factor authentication scenarios, OAuth login, password reset workflows, and account verification steps</pre><h3>Performance Considerations</h3><h3>1. Efficient Test Data</h3><p><strong>Prompt:</strong></p><pre>Generate MSTest DataRows using object arrays for complex scenarios in ProductCatalogService. Optimize for test execution speed while maintaining comprehensive coverage of product search, filtering, sorting, and pagination scenarios.</pre><h3>2. Parallel Test Execution</h3><p><strong>Prompt:</strong></p><pre>Create thread-safe MSTest DataRows for concurrent testing of OrderService methods. Include proper test isolation and avoid shared state issues.</pre><h3>Conclusion</h3><p>GitHub Copilot transforms the traditionally tedious task of writing comprehensive test suites into an efficient, AI-assisted process. By crafting effective prompts and leveraging Copilot’s understanding of testing patterns, you can generate robust MSTest suites with DataRows that thoroughly validate both your controller and business layers.</p><p>The key to success lies in:</p><ol><li><strong>Clear, contextual prompting</strong> that provides Copilot with sufficient information</li><li><strong>Iterative refinement</strong> of generated tests to match your specific requirements</li><li><strong>Strategic use of DataRows</strong> to maximize test coverage with minimal code duplication</li><li><strong>Proper separation of concerns</strong> between controller and business layer tests</li></ol><p>Remember that while Copilot excels at generating boilerplate test code and common patterns, you should always review and customize the generated tests to ensure they align with your specific business requirements and testing standards.</p><p>Start implementing these techniques in your next project, and you’ll find that comprehensive testing becomes not just manageable, but genuinely productive and even enjoyable. Your onion architecture will be more robust, your code more reliable, and your development velocity significantly increased.</p><p>Happy testing with GitHub Copilot!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08cf924b9f44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Modern, Observable .NET]]></title>
            <link>https://medium.com/@robert_84835/building-modern-observable-net-0899dfb9e358?source=rss-1a5e3f553f20------2</link>
            <guid isPermaLink="false">https://medium.com/p/0899dfb9e358</guid>
            <category><![CDATA[net-development]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Robert Felkins]]></dc:creator>
            <pubDate>Fri, 11 Jul 2025 16:42:35 GMT</pubDate>
            <atom:updated>2025-07-11T16:42:35.718Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9v4h2yrrZX1zPUuqnBBgxA.png" /></figure><h3>Building Modern, Observable .NET Applications: A Deep Dive into OpenTelemetry, Scalar, and OpenAPI Integration</h3><p>In today’s distributed application landscape, observability isn’t just a nice-to-have — it’s an absolute necessity. When you’re running multiple microservices across different environments, understanding what’s happening inside your applications becomes critical for maintaining performance, debugging issues, and ensuring reliability. In this article, I’ll walk you through how we’ve integrated OpenTelemetry, Scalar, and OpenAPI technologies into our .NET 9 solution to create a comprehensive observability and documentation strategy that scales with our microservices architecture.</p><h3>The Foundation: .NET Aspire and Service Defaults</h3><p>Our journey begins with .NET Aspire, Microsoft’s opinionated stack for building observable, production-ready cloud applications. At the heart of our implementation lies the ServiceDefaults project—a centralized configuration hub that standardizes observability across all our microservices.</p><p>The ServiceDefaults project serves as our single source of truth for common configurations. Every service in our solution references this project, ensuring consistent telemetry collection, health checks, and service discovery patterns. This approach eliminates configuration drift and makes it incredibly easy to add new services that automatically inherit our observability standards.</p><pre>public static TBuilder AddServiceDefaults&lt;TBuilder&gt;(this TBuilder builder) <br>    where TBuilder : IHostApplicationBuilder<br>{<br>    builder.ConfigureOpenTelemetry();<br>    builder.AddDefaultHealthChecks();<br>    builder.Services.AddServiceDiscovery();</pre><pre>    builder.Services.ConfigureHttpClientDefaults(http =&gt;<br>    {<br>        http.AddStandardResilienceHandler();<br>        http.AddServiceDiscovery();<br>    });</pre><pre>    return builder;<br>}</pre><p>This extension method is called in every service’s Program.cs, immediately providing OpenTelemetry instrumentation, health checks, and service discovery capabilities. It&#39;s a perfect example of how .NET Aspire promotes best practices by making the right thing the easy thing.</p><h3>OpenTelemetry: The Observability Backbone</h3><p>OpenTelemetry forms the cornerstone of our observability strategy. Rather than relying on proprietary monitoring solutions that lock us into specific vendors, we’ve embraced the open standard that provides vendor-neutral instrumentation for metrics, logs, and traces.</p><h3>Comprehensive Instrumentation Strategy</h3><p>Our OpenTelemetry configuration captures three critical signals:</p><p><strong>Tracing</strong> helps us understand request flows across our distributed system. We instrument ASP.NET Core applications to automatically capture incoming HTTP requests, and we track outgoing HTTP client calls to understand inter-service dependencies. Each trace creates a complete picture of how a user request travels through our system, making it invaluable for debugging performance bottlenecks and understanding system behavior.</p><p><strong>Metrics</strong> provide the quantitative data we need for monitoring system health. We collect ASP.NET Core metrics for request rates and response times, HTTP client metrics for outbound call performance, and .NET runtime metrics for garbage collection and memory usage patterns. This gives us both application-level and infrastructure-level insights.</p><p><strong>Logging</strong> integrates seamlessly with .NET’s built-in logging framework. OpenTelemetry automatically correlates log entries with traces, so when we’re debugging an issue, we can see exactly which log entries belong to a specific request trace.</p><pre>builder.Services.AddOpenTelemetry()<br>    .WithMetrics(metrics =&gt;<br>    {<br>        metrics.AddAspNetCoreInstrumentation()<br>            .AddHttpClientInstrumentation()<br>            .AddRuntimeInstrumentation();<br>    })<br>    .WithTracing(tracing =&gt;<br>    {<br>        tracing.AddSource(builder.Environment.ApplicationName)<br>            .AddAspNetCoreInstrumentation()<br>            .AddHttpClientInstrumentation();<br>    });</pre><h3>Flexible Export Strategy</h3><p>One of OpenTelemetry’s greatest strengths is its vendor-neutral approach to data export. Our configuration supports multiple export targets depending on the environment and requirements:</p><p>For development and testing environments, we can export to any OTLP-compatible endpoint by setting the OTEL_EXPORTER_OTLP_ENDPOINT environment variable. This might be a local Jaeger instance, a Grafana stack, or any other OpenTelemetry-compatible tool.</p><p>For production workloads, we integrate with Azure Monitor, leveraging Microsoft’s OpenTelemetry distro to send telemetry data directly to Application Insights. This provides us with enterprise-grade monitoring capabilities while maintaining the flexibility to switch monitoring backends if needed.</p><pre>private static TBuilder AddOpenTelemetryExporters&lt;TBuilder&gt;(this TBuilder builder) <br>    where TBuilder : IHostApplicationBuilder<br>{<br>    var useOtlpExporter = !string.IsNullOrWhiteSpace(<br>        builder.Configuration[&quot;OTEL_EXPORTER_OTLP_ENDPOINT&quot;]);</pre><pre>    if (useOtlpExporter)<br>    {<br>        builder.Services.AddOpenTelemetry().UseOtlpExporter();<br>    }</pre><pre>    if(builder.Environment.IsDevelopment() || builder.Environment.IsProduction())<br>    {<br>        if (!string.IsNullOrEmpty(<br>            builder.Configuration[&quot;APPLICATIONINSIGHTS_CONNECTION_STRING&quot;]))<br>        {<br>            builder.Services.AddOpenTelemetry().UseAzureMonitor();<br>        }<br>    }</pre><pre>    return builder;<br>}</pre><p>This dual-export capability means our development teams can use lightweight, local observability tools during development while production systems benefit from Azure’s robust monitoring infrastructure.</p><h3>Custom Instrumentation Through Action Filters</h3><p>Beyond automatic instrumentation, we’ve implemented custom telemetry collection through our ActionControllerLogging filter. This filter captures detailed audit information for every API call, including user context, session information, request bodies, and routing data.</p><pre>public class ActionControllerLogging : IAsyncActionFilter<br>{<br>    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)<br>    {<br>        HttpAuditEntryMessageModel msg = new HttpAuditEntryMessageModel();</pre><pre>        msg.UserName = context.HttpContext.Request.Headers<br>            .Where(w =&gt; w.Key.ToLower() == &quot;username&quot;).FirstOrDefault().Value;<br>        msg.Controller = ((ControllerBase)context.Controller)<br>            .ControllerContext.ActionDescriptor.ControllerName;<br>        msg.ActionMethod = ((ControllerBase)context.Controller)<br>            .ControllerContext.ActionDescriptor.ActionName;</pre><pre>        // Additional audit data collection...</pre><pre>        await next();<br>    }<br>}</pre><p>This filter demonstrates how OpenTelemetry’s extensible nature allows us to capture domain-specific telemetry that goes beyond standard web framework metrics. The audit data flows through Azure Service Bus to dedicated audit storage, creating a complete audit trail for compliance and security analysis.</p><h3>Scalar: Modern API Documentation</h3><p>While OpenTelemetry handles observability, Scalar addresses another critical need: comprehensive, developer-friendly API documentation. Traditional Swagger UI, while functional, often feels outdated and lacks the polish that modern development teams expect. Scalar provides a beautiful, responsive interface that makes API exploration intuitive and enjoyable.</p><h3>Seamless Integration with OpenAPI</h3><p>Our Scalar integration builds on .NET 9’s native OpenAPI support. The Microsoft.AspNetCore.OpenApi package automatically generates OpenAPI specifications from our controller definitions, and Scalar consumes these specifications to create interactive documentation.</p><pre>public static WebApplication ConfigureOpenApiAndScaler(this WebApplication app)<br>{<br>    app.MapOpenApi();<br>    app.MapScalarApiReference(options =&gt;<br>    {<br>        options.WithPreferredScheme(&quot;Bearer&quot;)<br>            .WithHttpBearerAuthentication(bearer =&gt;<br>            {<br>                bearer.Token = &quot;your-bearer-token&quot;;<br>            });<br>        options.Title = $&quot;{app.Environment.EnvironmentName} - {app.Environment.ApplicationName}&quot;;<br>    });<br>    return app;<br>}</pre><p>This configuration provides several key benefits. The documentation automatically stays in sync with our code — when we add new endpoints or modify existing ones, the documentation updates automatically. Scalar’s interface allows developers to test APIs directly from the documentation, eliminating the need to switch between documentation and testing tools.</p><h3>Security-Aware Documentation</h3><p>Our Scalar configuration includes built-in authentication support. The Bearer token authentication is pre-configured, so developers can easily test secured endpoints. In development environments, this dramatically reduces the friction involved in API testing and exploration.</p><p>The environment-aware titles ({app.Environment.EnvironmentName} - {app.Environment.ApplicationName}) help developers immediately understand which environment and service they&#39;re working with, reducing confusion when working across multiple environments.</p><h3>Strategic Documentation Deployment</h3><p>We only expose Scalar documentation in non-production environments, maintaining security best practices while maximizing developer productivity:</p><pre>if (!app.Environment.IsProduction())<br>{<br>    app.ConfigureOpenApiAndScaler();<br>}</pre><p>This approach ensures that our production endpoints remain secure while development and staging environments provide rich documentation experiences for both internal teams and external API consumers.</p><h3>OpenAPI: The Contract-First Approach</h3><p>OpenAPI serves as the foundation for both our documentation and our inter-service communication strategy. By leveraging .NET 9’s built-in OpenAPI support, we ensure that our API contracts are automatically generated, accurate, and versioned.</p><h3>API Versioning Strategy</h3><p>Our solution implements comprehensive API versioning through the Asp.Versioning libraries. This allows us to evolve our APIs while maintaining backward compatibility for existing consumers.</p><pre>builder.Services.AddApiVersioning(options =&gt;<br>{<br>    options.DefaultApiVersion = new ApiVersion(primaryVersion, 0);<br>    options.ReportApiVersions = true;<br>    options.AssumeDefaultVersionWhenUnspecified = true;<br>    options.ApiVersionReader = ApiVersionReader.Combine(<br>        new UrlSegmentApiVersionReader(),<br>        new HeaderApiVersionReader(&quot;x-api-version&quot;),<br>        new QueryStringApiVersionReader(&quot;api-version&quot;)<br>    );<br>});</pre><p>This configuration supports multiple versioning strategies — URL segments, headers, and query strings — giving API consumers flexibility in how they specify version requirements. The ReportApiVersions setting ensures that API responses include version information, helping consumers understand what versions are available.</p><h3>Code Generation and Type Safety</h3><p>While not explicitly shown in our current codebase, our OpenAPI specifications enable powerful code generation scenarios. Teams can generate strongly-typed HTTP clients using tools like Refit (which we include in our shared project) or NSwag, ensuring that inter-service communication is type-safe and automatically stays in sync with API changes.</p><p>The presence of Refit in our dependencies suggests we’re using this approach for HTTP client generation:</p><pre>&lt;PackageReference Include=&quot;Refit&quot; Version=&quot;8.0.0&quot; /&gt;<br>&lt;PackageReference Include=&quot;Refit.HttpClientFactory&quot; Version=&quot;8.0.0&quot; /&gt;</pre><p>This enables us to define HTTP APIs as C# interfaces and let Refit handle the HTTP implementation details, creating a more maintainable and less error-prone approach to service communication.</p><h3>Architectural Integration: How It All Works Together</h3><p>The true power of our observability and documentation strategy emerges from how these technologies work together to support our microservices architecture.</p><h3>Service-to-Service Communication</h3><p>When a request flows through our system, OpenTelemetry automatic instrumentation creates a distributed trace that spans multiple services. If our User Service calls the Profile Service, which then calls the Image Service, we get a complete trace showing the entire request flow, including timing information for each service call.</p><p>The OpenAPI specifications for each service define clear contracts, while Refit-generated clients provide type-safe communication. If the Profile Service needs to call the User Service, it uses a strongly-typed interface generated from the User Service’s OpenAPI specification.</p><h3>Development Workflow</h3><p>During development, our setup provides an exceptional developer experience. Developers can:</p><ol><li><strong>Explore APIs</strong> using Scalar’s beautiful interface, testing endpoints directly from the documentation</li><li><strong>Monitor request flows</strong> using local OpenTelemetry exporters to understand how their changes affect the broader system</li><li><strong>Debug issues</strong> using correlated logs and traces that show exactly what happened during a specific request</li><li><strong>Ensure compatibility</strong> by testing against versioned APIs that clearly communicate breaking changes</li></ol><h3>Production Operations</h3><p>In production, our observability stack provides operations teams with the insights they need to maintain system reliability:</p><ul><li><strong>Azure Monitor integration</strong> provides enterprise-grade alerting, dashboards, and analysis capabilities</li><li><strong>Distributed tracing</strong> enables rapid root cause analysis when issues occur across service boundaries</li><li><strong>Comprehensive metrics</strong> support proactive monitoring and capacity planning</li><li><strong>Structured logging</strong> with trace correlation makes troubleshooting specific customer issues straightforward</li></ul><h3>Security and Compliance</h3><p>Our ActionControllerLogging filter creates detailed audit trails for compliance requirements, while the audit data flows through Azure Service Bus to ensure reliable delivery and processing. The combination of OpenTelemetry traces and custom audit logs provides both technical observability and business-level audit capabilities.</p><h3>Performance and Overhead Considerations</h3><p>Implementing comprehensive observability always raises questions about performance impact. OpenTelemetry is designed with performance in mind, using efficient sampling strategies and asynchronous export mechanisms to minimize impact on application performance.</p><p>Our instrumentation focuses on high-value, low-overhead data collection. ASP.NET Core instrumentation adds minimal latency to request processing, while HTTP client instrumentation helps us identify slow downstream dependencies. Runtime instrumentation provides valuable insights into garbage collection and memory usage with negligible overhead.</p><p>The key is selective instrumentation — we capture the telemetry that provides actionable insights while avoiding over-instrumentation that could impact performance or create overwhelming amounts of data.</p><h3>Future Enhancements and Roadmap</h3><p>Looking ahead, our observability and documentation strategy continues to evolve. Some areas we’re exploring include:</p><p><strong>Enhanced Custom Metrics</strong>: Adding business-specific metrics that help us understand not just technical performance but business outcomes.</p><p><strong>Improved Documentation</strong>: Exploring ways to include more context in our API documentation, such as usage examples and integration guides.</p><p><strong>Advanced Tracing</strong>: Investigating custom span creation for critical business processes to provide even more detailed insights into application behavior.</p><p><strong>Multi-Environment Correlation</strong>: Developing strategies to correlate telemetry across development, staging, and production environments to better understand how code changes affect system behavior.</p><h3>Conclusion</h3><p>The integration of OpenTelemetry, Scalar, and OpenAPI in our .NET 9 solution creates a powerful foundation for building and operating modern microservices. OpenTelemetry provides vendor-neutral observability that scales with our application, Scalar delivers beautiful, developer-friendly API documentation, and OpenAPI ensures our service contracts are clear, versioned, and automatically maintained.</p><p>This combination supports both development velocity and operational excellence. Developers get the tools they need to understand and test APIs, while operations teams get the observability data required to maintain reliable, performant systems.</p><p>Most importantly, this approach is future-proof. By embracing open standards like OpenTelemetry and OpenAPI, we avoid vendor lock-in while still benefiting from excellent tooling and integrations. As our architecture evolves and new requirements emerge, our observability and documentation strategy can adapt without requiring fundamental changes.</p><p>The investment in proper observability and documentation pays dividends throughout the application lifecycle — from initial development through production operations to long-term maintenance and evolution. In today’s fast-paced development environment, these capabilities aren’t just helpful; they’re essential for building systems that teams can confidently develop, deploy, and operate at scale.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0899dfb9e358" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>