<?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 Ivan Ball-llovera on Medium]]></title>
        <description><![CDATA[Stories by Ivan Ball-llovera on Medium]]></description>
        <link>https://medium.com/@ivanball76?source=rss-b79b63d05524------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*jP5q95j-f0XnbsR3</url>
            <title>Stories by Ivan Ball-llovera on Medium</title>
            <link>https://medium.com/@ivanball76?source=rss-b79b63d05524------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 14:14:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ivanball76/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The MMCA series: every pattern, one place]]></title>
            <link>https://medium.com/@ivanball76/the-mmca-series-every-pattern-one-place-28cf2cee7be8?source=rss-b79b63d05524------2</link>
            <guid isPermaLink="false">https://medium.com/p/28cf2cee7be8</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[cqrs]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Ivan Ball-llovera]]></dc:creator>
            <pubDate>Thu, 20 Aug 2026 12:18:00 GMT</pubDate>
            <atom:updated>2026-08-22T01:51:26.459Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A single map of the whole series. Start at the top if MMCA.Common is new to you, or jump straight to the pattern you came for.</em></p><p><em>Part of the MMCA.Common series · Article 50 of 50. One pattern at a time.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dn7eqOEv76Ksp9dq46BYmQ.png" /></figure><p>MMCA.Common is an Apache-2.0 licensed .NET 10 framework that gives you DDD, Clean Architecture, and CQRS as a modular monolith that extracts to microservices without a rewrite, and it grades itself against a 34-category architecture rubric in the open. This series teaches it one pattern at a time: the failure mode each pattern fixes, the real type and ADR behind the MMCA.Common implementation, the honest trade-offs, and how to apply the idea even if you never install the package.</p><p>Each article stands on its own if you land on it from a search. This page is the index that ties them together. The groups below run roughly from “why this exists” to “how to build with it,” so reading top to bottom is a reasonable curriculum, but every link is also a fine place to start.</p><h3>Start here</h3><p>The thesis and the framing. Read these first if you have not met the framework.</p><ul><li>01 · <a href="https://medium.com/@ivanball76/i-open-sourced-the-enterprise-net-77f9200f3728">I open-sourced the enterprise .NET plumbing I never want to rewrite, and graded it against 34 categories</a></li><li>02 · <a href="https://medium.com/@ivanball76/modular-monolith-to-microservices-without-the-rewrite-8c3603614f12">Modular monolith to microservices, without the rewrite</a></li><li>03 · <a href="https://medium.com/@ivanball76/what-good-architecture-actually-means-a-34-category-rubric-you-can-score-yourself-against-4002291a6b6a">What good architecture actually means: a 34-category rubric you can score yourself against</a></li></ul><h3>Core patterns</h3><p>The day-one building blocks. Error handling, the domain model, query intent, the handler pipeline, the reliability backbone that ties them together, and the compensating handlers that undo a step no transaction can roll back.</p><ul><li>04 · <a href="https://medium.com/@ivanball76/stop-throwing-exceptions-for-control-flow-the-result-railway-in-c-7a02050b554e">Stop throwing exceptions for control flow: the Result railway in C#</a></li><li>05 · <a href="https://medium.com/@ivanball76/kill-the-anemic-domain-model-rich-aggregates-with-factory-methods-that-return-result-44f2e3d89794">Kill the anemic domain model</a></li><li>06 · <a href="https://medium.com/@ivanball76/specifications-over-linq-spaghetti-composable-reusable-query-intent-8a40dafcbd3d">Specifications over LINQ spaghetti</a></li><li>07 · <a href="https://medium.com/@ivanball76/the-cqrs-decorator-pipeline-logging-caching-and-transactions-without-touching-a-handler-fb7679b8bde8">The CQRS decorator pipeline</a></li><li>08 · <a href="https://medium.com/@ivanball76/compose-validators-dont-copy-them-a-reusable-fluentvalidation-kit-8865a6003a9c">Compose validators, don’t copy them: a reusable validation kit</a></li><li>09 · <a href="https://medium.com/@ivanball76/the-transactional-outbox-in-net-10-never-lose-an-event-again-f5a9b7a89e51">The transactional outbox in .NET 10</a></li><li>45 · <a href="https://medium.com/@ivanball76/feature-flags-in-the-cqrs-pipeline-gate-commands-not-code-e58b9ea8d098">Feature Flags in the CQRS Pipeline: Gate Commands, Not Code</a></li><li>49 · <a href="https://medium.com/@ivanball76/undo-is-a-feature-saga-compensation-and-the-reconciliation-backstop-fa017f9591b8">Undo Is a Feature: Saga Compensation and the Reconciliation Backstop</a></li></ul><h3>Data and persistence</h3><p>How the data layer is built so a module owns its own database, and even its own storage engine, and can become its own service later without a rewrite.</p><ul><li>10 · <a href="https://medium.com/@ivanball76/database-per-service-inside-a-monolith-and-why-265092eb03f1">Database-per-service inside a monolith</a></li><li>11 · <a href="https://medium.com/@ivanball76/one-entity-model-three-databases-polyglot-persistence-behind-a-single-attribute-760e77974d5d">Polyglot persistence: one entity model, three storage engines</a></li><li>12 · <a href="https://medium.com/@ivanball76/ef-core-include-chains-are-a-trap-navigation-populators-decouple-eager-loading-c378fa4497ac">EF Core Include chains are a trap: navigation populators</a></li><li>13 · <a href="https://medium.com/@ivanball76/optimistic-concurrency-that-survives-the-round-trip-rowversion-from-database-to-dto-and-back-93d4a794716f">Optimistic concurrency: RowVersion round-trips through DTOs</a></li><li>14 · <a href="https://medium.com/@ivanball76/self-ordering-modules-discovered-kahn-ordered-and-extractable-2ce7283a26b5">Self-ordering modules</a></li><li>15 · <a href="https://medium.com/@ivanball76/event-schema-versioning-never-silently-reshape-an-event-93cd5d4a156d">Event-schema versioning</a></li></ul><h3>Auth, the API edge, and cross-cutting</h3><p>The concerns that sit across every module: authentication between services, authorization (by role, by permission, and by row ownership), password storage, safe retries, caching, error contracts, notifications, DTO mapping, browser session auth, the generic REST surface, defending the edge, encrypting PII columns at rest, and the hardened response headers every host stamps.</p><ul><li>16 · <a href="https://medium.com/@ivanball76/cross-service-auth-without-a-shared-secret-jwks-dual-fetch-478e6f688c7e">Cross-service auth without a shared secret: JWKS dual-fetch</a></li><li>17 · <a href="https://medium.com/@ivanball76/password-hashing-done-right-pbkdf2-sha512-600k-iterations-timing-safe-d64ddb802403">Password hashing done right</a></li><li>18 · <a href="https://medium.com/@ivanball76/idempotency-in-one-attribute-safe-retries-for-http-apis-065848fd03f4">Idempotency in one attribute</a></li><li>19 · <a href="https://medium.com/@ivanball76/the-self-invalidating-cache-that-lives-in-the-pipeline-not-your-handlers-e11548062d2f">The self-invalidating cache</a></li><li>20 · <a href="https://medium.com/@ivanball76/problem-details-across-http-and-grpc-rfc-9457-9f20157cf7de">Problem Details across HTTP and gRPC</a></li><li>21 · <a href="https://medium.com/@ivanball76/notifications-as-a-vertical-slice-in-app-inbox-real-time-push-native-push-and-email-c59d5a4f3b69">Notifications as a vertical slice</a></li><li>22 · <a href="https://medium.com/@ivanball76/ephemeral-by-design-sub-second-live-channels-over-one-signalr-hub-0248050e0c8b">Ephemeral by design: sub-second live channels over one SignalR hub</a></li><li>23 · <a href="https://medium.com/@ivanball76/delete-automapper-explicit-compile-time-dto-mapping-that-you-can-actually-test-9c7013cc5d3f">Delete AutoMapper: explicit, compile-time DTO mapping</a></li><li>24 · <a href="https://medium.com/@ivanball76/permission-based-authorization-capabilities-over-role-checks-ea6574cbee27">Permission-based authorization: capabilities over role checks</a></li><li>25 · <a href="https://medium.com/@ivanball76/browser-session-cookie-auth-for-blazor-ssr-surviving-the-f5-eb0ea317820e">Browser session-cookie auth for Blazor SSR: surviving the F5</a></li><li>26 · <a href="https://medium.com/@ivanball76/google-and-github-login-without-leaking-tokens-external-oauth-behind-your-own-jwts-d68ba5e3aca4">External OAuth login: Google/GitHub behind your own JWTs</a></li><li>27 · <a href="https://medium.com/@ivanball76/one-rotating-refresh-token-and-reuse-detection-that-makes-theft-self-limiting-fab42234a04a">One rotating refresh token, and reuse detection that makes theft self-limiting</a></li><li>28 · <a href="https://medium.com/@ivanball76/generic-entity-controllers-and-the-dynamic-query-contract-adr-034-2b5c799bc69f">Generic entity controllers and the dynamic query contract</a></li><li>29 · <a href="https://medium.com/@ivanball76/resource-ownership-authorization-which-rows-you-may-touch-not-just-which-actions-cb8e78867bae">Resource-ownership authorization: which rows you may touch, not just which actions</a></li><li>30 · <a href="https://medium.com/@ivanball76/defending-the-api-edge-three-controls-that-cover-the-whole-surface-d958ecae1091">Defending the API edge: rate limiting and brute-force protection</a></li><li>46 · <a href="https://medium.com/@ivanball76/field-level-encryption-in-ef-core-aes-gcm-for-pii-columns-06ece340ea25">Field-Level Encryption in EF Core: AES-GCM for PII Columns</a></li><li>47 · <a href="https://medium.com/@ivanball76/security-headers-and-csp-for-blazor-one-middleware-every-host-af82df95236e">Security Headers and CSP for Blazor: One Middleware, Every Host</a></li></ul><h3>Run, extract, and harden</h3><p>Bring the whole stack up with one command, then cut a module out into its own service, make the running system survive failure, and see what it is doing in production. Read these in order: Aspire first, then extraction, then resilience, then observability.</p><ul><li>31 · <a href="https://medium.com/@ivanball76/aspire-one-command-brings-up-the-whole-distributed-app-379b5cffdeed">Aspire: one command</a></li><li>32 · <a href="https://medium.com/@ivanball76/extracting-a-module-to-a-grpc-service-live-799926cf8a32">Extracting a module to a gRPC service, live</a></li><li>33 · <a href="https://medium.com/@ivanball76/retries-are-not-a-recovery-plan-resilience-handlers-rto-rpo-and-a-restore-you-actually-drilled-3c7474814123">Retries are not a recovery plan: resilience handlers, RTO/RPO, and a drilled restore</a></li><li>48 · <a href="https://medium.com/@ivanball76/observability-by-default-opentelemetry-and-azure-monitor-in-mmca-673c1886e9e0">Observability by Default: OpenTelemetry and Azure Monitor in MMCA</a></li></ul><h3>Proof, front end, and getting started</h3><p>The evidence that the patterns hold (fitness functions, the test pyramid, the erasure pathway), the reusable Blazor UI framework and the internationalization and theming that ride on it, the hands-on path from dotnet new mmca-app to your first module, your first fitness test, and the two real apps that run on all of it, the device-capability layer that lets one Blazor UI run in a browser and inside a native phone app, and two later additions that round out the framework surface: managed file storage with untrusted-upload handling, and provable HTTP API versioning.</p><ul><li>34 · <a href="https://medium.com/@ivanball76/architecture-fitness-functions-rules-that-fail-the-build-not-a-wiki-page-6562940deceb">Architecture fitness functions: rules that fail the build</a></li><li>35 · <a href="https://medium.com/@ivanball76/the-test-pyramid-not-the-ice-cream-cone-1-880-fast-tests-zero-docker-cb459fda73d9">The test pyramid, not the ice-cream cone</a></li><li>36 · <a href="https://medium.com/@ivanball76/soft-delete-vs-the-right-to-erasure-the-gdpr-conflict-and-the-erasure-pathway-e1d350007509">Soft-delete vs the right to erasure</a></li><li>37 · <a href="https://medium.com/@ivanball76/a-list-page-in-a-few-lines-a-reusable-blazor-ui-framework-with-the-same-discipline-as-the-backend-c66fa16cd561">A reusable Blazor UI framework: a list page in a few lines</a></li><li>38 · <a href="https://medium.com/@ivanball76/one-preference-two-switches-shipping-i18n-and-dark-mode-on-a-single-cookie-and-profile-pipeline-f97186038909">Internationalization and theming on one cookie-and-profile pipeline</a></li><li>39 · <a href="https://medium.com/@ivanball76/scaffold-a-net-modular-monolith-in-one-command-then-build-your-first-module-b10aacd16d33">Scaffold a .NET modular monolith in one command, then build your first module</a></li><li>40 · <a href="https://medium.com/@ivanball76/write-your-first-architecture-fitness-test-d4e25e6a4741">Write your first architecture fitness test</a></li><li>41 · <a href="https://medium.com/@ivanball76/two-real-apps-on-one-framework-a-conference-platform-and-a-store-12f694d2a361">Two real apps on one framework</a></li><li>42 · <a href="https://medium.com/@ivanball76/one-blazor-ui-two-hosts-a-device-capability-layer-that-stays-resolvable-everywhere-b85444693161">One Blazor UI, two hosts: a device-capability layer that stays resolvable everywhere</a></li><li>43 · <a href="https://medium.com/@ivanball76/managed-file-storage-uploads-you-dont-have-to-trust-8dfe8bf016bc">Managed file storage: uploads you don’t have to trust</a></li><li>44 · <a href="https://medium.com/@ivanball76/http-api-versioning-proven-not-just-claimed-2b0381e4b533">HTTP API versioning, proven not just claimed</a></li></ul><h3>Where to go next</h3><p>If you are evaluating the framework, read 01 then 03 then 41: the thesis, the rubric, and the proof. If you are here to solve a specific problem, the core-patterns and cross-cutting groups are the toolbox. If you want to build, start at 39: it scaffolds the whole solution in one command, then explains what you were handed. Then 40, to make the conventions fail the build.</p><p><em>MMCA.Common is Apache-2.0 licensed and open source. Star the repo, read the scorecard (the gaps are the honest part), or </em><em>dotnet add package MMCA.Common.API and tell me what breaks. New patterns land regularly, then monthly evergreen.</em></p><ul><li>The 34-category scorecard (<a href="https://ivanball.github.io/docs/governance/common-ArchitectureScorecard.html">https://ivanball.github.io/docs/governance/common-ArchitectureScorecard.html</a>) and the ADRs (<a href="https://ivanball.github.io/docs/adr/">https://ivanball.github.io/docs/adr/</a>) are committed in the docs site.</li></ul><p><strong>About the author</strong></p><p>Ivan Ball-llovera is a senior software architect working in enterprise .NET. This series is built on <strong>MMCA.Common</strong>, the open-source framework behind it: fifteen NuGet packages for a modular monolith you can extract services out of later, scored in public against a 34-category architecture rubric, gaps included.</p><ul><li>The framework: <a href="https://github.com/ivanball/MMCA.Common">https://github.com/ivanball/MMCA.Common</a></li><li>Start a new app: dotnet new install MMCA.Templates then dotnet new mmca-app -n Your.App</li><li>Add it to an existing solution: dotnet add package MMCA.Common.API</li><li>The full series index and the architecture docs: <a href="https://ivanball.github.io/writing.html">https://ivanball.github.io/writing.html</a></li></ul><p>Follow along here for one pattern a week.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28cf2cee7be8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Undo Is a Feature: Saga Compensation and the Reconciliation Backstop]]></title>
            <link>https://medium.com/@ivanball76/undo-is-a-feature-saga-compensation-and-the-reconciliation-backstop-fa017f9591b8?source=rss-b79b63d05524------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa017f9591b8</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Ivan Ball-llovera]]></dc:creator>
            <pubDate>Wed, 19 Aug 2026 12:56:23 GMT</pubDate>
            <atom:updated>2026-08-22T01:50:47.765Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A cancelled order has to give back stock that a transaction closed minutes ago already took, and a payment confirmation that never arrives strands the order forever. Here is compensation as its own event handler, idempotency as a persisted marker committed by the same </em><em>SaveChanges as the writes it guards, and a periodic sweep as the saga-timeout backstop.</em></p><p><em>Part of the MMCA.Common series · Article 49 of 50. One pattern at a time.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QJCAubQ2ORLT0OUOsTdG2w.png" /></figure><p>Checkout is the easy part. In MMCA.Store’s Sales module it is genuinely atomic: the order insert, the cart transition, and the conditional stock decrements all commit inside one explicit local transaction, and a failed decrement returns a failed Result that rolls the whole thing back. One database, one transaction, no drama.</p><p>Then the money moves at Stripe, and the confirmation comes back later, as a webhook, from outside your database entirely. And two things go wrong that no transaction can fix:</p><ol><li><strong>A later step invalidates an earlier one.</strong> The customer cancels. The stock that checkout committed is still decremented, and you cannot roll that decrement back, because its transaction closed minutes ago.</li><li><strong>The external confirmation never arrives.</strong> An endpoint outage that outlasts Stripe’s retry window, a misconfigured webhook secret, and the order sits in PaymentInitiated forever with its stock held.</li></ol><p>The instinct is to reach for a transaction that spans both, and there isn’t one. There is no two-phase commit across a database and a payment provider, and there would not be one worth having even if the provider could enlist. So the question is not “how do I roll this back.” It is “what do I do instead, and how do I make it disciplined enough to trust.” That is the decision recorded in <strong>ADR-054</strong>.</p><h3>Why it matters</h3><p>The rubric has two categories aimed straight at this. §6 (CQRS and Event-Driven Design) asks for idempotent consumers and for eventual-consistency boundaries that are <strong>explicit and documented in an ADR</strong>, with “consumers that aren’t idempotent and break on redelivery” listed as a red flag. §29 (Resilience, Reliability and Business Continuity) is a weight-3 category that asks for graceful degradation and failure isolation, and names “retries without backoff/idempotency (retry storms, duplicate side effects)” as its own red flag.</p><p>Note what those two demand together: not just that you retry, but that retrying is <strong>safe</strong>. That is the hard half. Delivering an event at least once is a solved problem (the transactional outbox, ADR-003). Making the handler survive being run twice is where systems quietly rot.</p><p>And it is the question the neighbouring records leave open on purpose. ADR-003 gets an event out of the process at least once. ADR-021 stops a broker redelivery from being applied twice at the consume edge. ADR-006 decides database-per-service and records “no cross-database transactions, no two-phase commit” only as a <strong>cost it accepts</strong>, without saying how that cost gets paid. None of them says what a multi-step workflow does when step two fails or step three never reports back.</p><h3>The MMCA answer: compensation is a handler, not a branch in the command</h3><p>The command handler does one thing. CancelOrderHandler loads the order, stamps the client&#39;s last-seen rowversion back as the original so a stale-view cancellation fails with a conflict (ADR-035), calls the guarded transition, and saves. It does not touch inventory. Its own comment says so.</p><p>The guarded transition is where the workflow advances: Order.MarkAsCancelled() asks the current state object whether the transition is legal and, on success, records a domain event. OrderCancelled is a plain BaseDomainEvent, not an integration event, so it dispatches in-process after the save.</p><p>Restoring the stock is a separate class: OrderCancelledSagaHandler : IDomainEventHandler&lt;OrderCancelled&gt;. Notifying the customer of a failed payment is another one, OrderPaymentFailedSagaHandler. This is the choreographed shape: each step raises an event, and each follow-up or compensating action lives in its own handler. A new compensating action (a refund, another notification) is a new handler, not an edit to the command.</p><p><strong>Each handler runs in its own DI scope.</strong> Domain-event handlers are registered as singletons by the framework’s convention scan, with the comment “Domain event handlers are singletons, they create their own DI scopes internally”, so every handler opens a scope through IServiceScopeFactory and resolves its own IUnitOfWork. The consequence is the important part: compensation commits <strong>on its own, after</strong> the originating save, rather than joining the transaction it is compensating for. That is what makes it compensation rather than a rollback.</p><h3>The marker: idempotency as a database invariant</h3><p>Here is the part worth stealing even if you never touch this framework.</p><p>At-least-once delivery means the compensating handler will eventually run twice. If restoring stock is not idempotent, the second run inflates inventory, and you have turned a reliability mechanism into a data-corruption mechanism.</p><p>MMCA.Store makes it idempotent with a persisted marker on the aggregate. Order.InventoryRestored is a boolean with a private setter, and MarkInventoryRestored() is a guarded transition like any other: it refuses on a non-cancelled order and refuses a second call, both as Result.Failure with named invariant codes.</p><p>The handler then does four things in order:</p><ol><li>Loads the order with its lines, tracked, in its own scope.</li><li>Checks the marker first and returns without saving if it is already set.</li><li>Loads the matching inventory rows <strong>with the soft-delete filter deliberately turned off</strong> (ignoreQueryFilters: true), then applies the increases through a pure domain service with no infrastructure dependencies, InventoryRestorationDomainService.RestoreInventory, which hands back the variant ids it could not match so the handler can log them by name.</li><li>Sets the marker and calls <strong>one</strong> SaveChangesAsync.</li></ol><p>That last step is the whole design. The inventory increases and the marker are written by the same SaveChanges against the same database, in one transaction. So the marker cannot exist without the writes it guards, and the writes cannot land unmarked. Idempotency stops being handler discipline and becomes a database invariant.</p><p>Step 3’s filter override is a smaller decision with a real consequence. A retired variant is soft-deleted, not removed, and the stock a cancelled order is returning still belongs to that row: without ignoreQueryFilters, the row is invisible to the handler and the returned quantity is silently dropped.</p><p>This is why ADR-054 says the marker is <strong>strictly stronger than the ADR-021 inbox</strong>. The inbox records a message id after the handlers have succeeded, which leaves a narrow crash window between the handler’s commit and the inbox write. A marker committed <em>with</em> the writes has no such window. The two are complementary rather than competing: the inbox dedups broker redeliveries between services, the aggregate marker dedups in-process handler re-runs.</p><p><strong>Concurrent redeliveries are handled by a different mechanism.</strong> The marker check is a read, so two deliveries can both pass it. Every auditable entity carries a RowVersion concurrency token, configured automatically on every non-owned auditable type by ConfigureConcurrencyTokens (ADR-035). Both deliveries carry the same original token into their update: one commits, the other gets DbUpdateConcurrencyException, and its outbox retry then finds the committed marker and skips. Sequential redelivery is handled by the marker, concurrent redelivery by the token.</p><pre>// Condensed from OrderCancelledSagaHandler.HandleAsync (most logging trimmed).<br>public async Task HandleAsync(OrderCancelled domainEvent, CancellationToken cancellationToken = default)<br>{<br>    using var scope = serviceScopeFactory.CreateScope();<br>    var unitOfWork = scope.ServiceProvider.GetRequiredService&lt;IUnitOfWork&gt;();<br>    <br>    var orderRepository = unitOfWork.GetRepository&lt;Order, OrderIdentifierType&gt;();<br>    var order = await orderRepository.GetByIdAsync(<br>        domainEvent.OrderId, includes: [nameof(Order.OrderLines)], asTracking: true,<br>        cancellationToken: cancellationToken);<br>    if (order is null)<br>        return;<br>    <br>    // Idempotency guard: a redelivered OrderCancelled event (outbox is at-least-once)<br>    // must not restore the same stock twice.<br>    if (order.InventoryRestored)<br>        return;<br>    <br>    var inventoryRepo = unitOfWork.GetRepository&lt;InventoryItem, ProductVariantIdentifierType&gt;();<br>    var variantIds = order.OrderLines.Select(ol =&gt; ol.ProductVariantId).Distinct().ToArray();<br>    var allItems = await inventoryRepo.GetAllAsync(<br>        includes: [], where: i =&gt; variantIds.Contains(i.Id), asTracking: true,<br>        // A soft-deleted inventory row is still the row this stock belongs to.<br>        ignoreQueryFilters: true,<br>        cancellationToken: cancellationToken).ConfigureAwait(false);<br>    <br>    var restoreResult = inventoryRestorationDomainService.RestoreInventory(<br>        order.OrderLines, allItems.ToDictionary(i =&gt; i.Id));<br>    if (restoreResult.Value is { Count: &gt; 0 } unmatchedVariantIds)<br>        LogInventoryItemsNotFound(logger, domainEvent.OrderId, string.Join(&quot;, &quot;, unmatchedVariantIds));<br>    <br>    // The marker is set even when some variants had no inventory record: withholding it would<br>    // re-apply every MATCHED increase on the next redelivery. The warning is the record.<br>    var markResult = order.MarkInventoryRestored();<br>    if (markResult.IsFailure)<br>        return;<br>    <br>    // ONE save: the restoration and the idempotency marker commit atomically (same DB).<br>    await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);<br>}</pre><h3>Redelivery is the retry mechanism, so throwing is correct</h3><p>A compensating handler needs no retry loop of its own, because it already sits on one.</p><p>When in-process dispatch fails, the domain-event interceptor logs the failure and signals the outbox rather than swallowing the work. FlushStateAsync dispatches the save&#39;s local events and only then marks their outbox entries processed, so a throwing handler never reaches the mark, and the catch below it logs and signals the processor. The OutboxProcessor re-dispatches the pure domain event on a later cycle with the bounded retries, backoff, and dead-lettering ADR-003 already defines. So a handler that cannot complete its work should fail loudly and let redelivery re-run it. Inventing local retries would just duplicate a policy that already exists one layer down.</p><p>The framework takes that same position in its own base class. SafeDomainEventHandler&lt;TDomainEvent&gt; runs your HandleSafelyAsync inside an exception filter, LogAndRethrow, which writes one error line naming the handler and the event type and then returns false, so the exception keeps travelling with its original stack intact. A cancellation during host shutdown passes straight through unlogged, because that is not a delivery failure. The class documentation records why rethrowing is required: a handler that reports success has its outbox row marked processed, so nothing retries and the side effect is lost with only a log line to show for it. The base class is not a way to absorb a failure. It is a way to fail with context, and its tests assert exactly that, including that the log lands before the caller sees the exception.</p><p>The documentation also names the consequence to design for. The interceptor dispatches every local event of one save in a single call, so one rethrowing handler skips the mark-processed step for the <strong>whole</strong> local batch: every event that save raised comes back, not only the one whose handler failed. A subclass has to be idempotent about its own event and about its siblings.</p><p>The mirror case is now hand-rolled, deliberately. A handler whose work is a pure side effect, where a redelivery would be worse than a loss, should <strong>not</strong> force one. OrderPaymentFailedSagaHandler catches its own exceptions, sparing OperationCanceledException so a shutdown is not filed as a notification failure, because the order has already been persisted as PaymentFailed and a failed email must not drag the event back through the pipeline. It implements IDomainEventHandler&lt;OrderPaymentFailed&gt; directly: there is no packaged base class for the swallow side, and no production handler in the four repos derives from SafeDomainEventHandler today, its only subclass being the test double in that base class&#39;s own unit tests.</p><p>The choice is therefore explicit per handler: <strong>throw to get a redelivery, or swallow to refuse one.</strong> What you cannot do is neither.</p><h3>The inbound edge: a webhook is a delivery contract, not an API call</h3><p>Everything so far is about a message leaving the process (ADR-003, at-least-once out) or a broker redelivery arriving at a consumer (ADR-021, dedup on the way in). The Stripe webhook is the third leg of that family and it matches neither: an inbound call from a third party you do not control, which cannot authenticate as an application user, does not send an Idempotency-Key, and never touches your broker. <strong>ADR-084</strong> records that contract, and it is worth reading before the backstop, because the backstop exists for the deliveries this contract loses.</p><p>The endpoint is one anonymous POST that reads the body raw, because signature verification needs the unmodified payload and model binding would destroy it, with the Stripe-Signature header read alongside it. That signature is the only authentication there is.</p><p>The load-bearing decision is what the status code <em>means</em>. <strong>It encodes ACCEPTED, not PROCESSED.</strong> Exactly three failure codes return 400, held in a FrozenSet named RejectionCodes: signature verification failed, the signed payload could not be parsed, and no signing secret is configured. Everything past acceptance returns 200, <strong>including an event for an order that cannot be found</strong>. That reads as wrong until you read the status code the way the caller does: Stripe treats a non-2xx as &quot;retry me&quot;, and sustained failures make it <strong>disable the endpoint</strong>, which silently stops every payment status update for the whole store. Mapping an application failure to 400 would be locally honest and globally catastrophic. So a post-acceptance failure logs at Warning and still returns 200, while a rejection logs at Critical with the consequence spelled out in the message text. Critical is deliberate, not drama: this ran at Warning for weeks while the configured signing secret did not match the live endpoint, so 100% of deliveries were rejected and nothing surfaced it.</p><p>The provider-side half is that the endpoint registers itself. StripeWebhookRegistrationService is a BackgroundService registered by the Sales module in the same method that registers the reconciliation sweep below. It skips entirely when no WebhookBaseUrl is set, which is the local path where the Stripe CLI forwards instead, and warns and skips with no SecretKey; it subscribes exactly three event types; and it stamps every endpoint it creates with the description prefix Auto-registered by MMCA. That prefix is the whole reason an automated delete is acceptable: IsStaleAutoRegistered returns false for any endpoint lacking it, so an operator-created endpoint is never touched, and true only for one of its own whose URL has moved or whose status is no longer enabled. The disabled-but-still-present duplicate that predicate collapses is a real incident, not a hypothetical: a second endpoint got created at the same URL with a brand-new signing secret, invalidating the configured one.</p><p>The secret is the honest ugly part. Stripe reveals a signing secret only at creation time, so the created value is written to a volatile-backed singleton that the payment service prefers over configuration on every incoming event, announced at Critical, and written to stderr for an operator to copy into Stripe:WebhookSecret. That is live credential material in the log pipeline, on purpose: the alternative is a first boot where the endpoint exists and every single delivery is rejected. ADR-084 files it as a trade-off, not a feature, along with the fact that a configured secret is trusted and never validated, because the provider will not re-reveal it.</p><h3>The backstop: a periodic sweep against the provider</h3><p>Compensation answers “step two failed.” It does not answer “step three never reported back.” A webhook that is never delivered, or that arrives and is rejected because the signing secret is stale, produces no event to compensate, so no handler ever runs.</p><p>PaymentReconciliationService is the saga-timeout backstop, registered as a hosted service by the Sales module&#39;s infrastructure. Its loop shape is deliberate, and it is deliberately not its own. The sweep derives from the framework&#39;s PeriodicBackgroundService, whose ExecuteAsync owns the enablement gate, the 15-second startup delay that lets the host finish initializing, the per-cycle try/catch that logs and never kills the loop, and every wait through TimeProvider so the cycle is testable without real time.</p><p>The sweep overrides exactly three members: Interval, read from configuration; IsEnabled, which refuses to run when the toggle is off or when no Stripe key is configured, logging which of the two it was because those are very different situations to find in a log; and ExecuteCycleAsync, which delegates to an internally visible ReconcileOnceAsync so one cycle is testable without the timer. That is also the base class&#39;s only subclass in any of the four repos, apart from the test double in PeriodicBackgroundService&#39;s own unit tests: one adopter, not yet a convention.</p><p>Each cycle does three things.</p><p><strong>It bounds the work in SQL, not in memory.</strong> The query selects orders that are PaymentInitiated, have a Stripe session id, and last changed before the cutoff, orders them oldest-first, takes the batch size, and projects to ids, all server-side, over a dedicated filtered index IX_Order_Status_Modified. The comment above the query explains why: materializing every stuck order and taking the batch in memory would make the batch size a Stripe-call budget rather than a query bound, and the exact failure this sweep exists to handle (a prolonged webhook outage) is the one that strands a large backlog.</p><p><strong>It reloads each order in its own scope and re-checks.</strong> ReconcileOrderAsync opens a scope per order so one order&#39;s failure never poisons the batch, reloads the order tracked, and returns immediately if it is no longer PaymentInitiated, because a webhook may have arrived between the id query and now.</p><p><strong>It asks Stripe and applies the same guarded transitions the webhook would have.</strong> The session status maps to exactly three outcomes: paid to MarkAsPaid, expired to MarkAsPaymentFailed, still open to nothing at all, left for a later cycle. Those are the identical Result-returning methods called by the webhook handler and by the client-initiated check. The sweep gets no private path into the aggregate, so it cannot reach a state the webhook could not.</p><p><strong>And it loses races on purpose.</strong> If a webhook transitions the order between the sweep’s load and its save, the save throws DbUpdateConcurrencyException, which is logged and skipped, not retried. The concurrent writer is authoritative; the next cycle sees the final state.</p><p>The whole thing is configuration-gated by PaymentReconciliationSettings: Enabled defaults true, a 10-minute poll interval, a 30-minute stuck age, and a 50-order batch, carried as those exact values in the Sales service&#39;s appsettings.json. The stuck age is documented to sit comfortably above normal webhook latency so the sweep never races a healthy delivery.</p><p>Both mechanisms are covered by tests that assert the behavior, not the wiring: seven cases on the saga handler including a redelivered event that must not restore stock twice, the lookup that has to ignore the soft-delete filter, and the missing-inventory case that must warn and still mark the order restored; and seven on the sweep including the lost race and the bound-the-query-not-the-list case. The ingress contract has its own pair: three cases pinning the controller’s accept-versus-reject mapping and five on the deletion predicate, including the operator-created endpoint that must never be judged stale.</p><h3>Trade-offs, honestly</h3><ul><li><strong>Adoption is one module, and the record says so.</strong> This pattern lives in MMCA.Store’s Sales module only: the two saga handlers and the one reconciliation sweep above. MMCA.ADC and MMCA.Helpdesk have no compensating saga handler and no reconciliation sweep today. The record exists because the mechanism is the framework’s stated answer to cross-boundary consistency, not because it is broadly adopted. Read this article as one worked implementation, not a fleet-wide convention.</li><li><strong>There is no orchestrator, and that is now a written deferral rather than a silence.</strong> Choreography is correct for this workflow because Order.Status plus Order.InventoryRestored already <em>are</em> the saga state, and <strong>ADR-086</strong> records what would replace it when that stops being true: a MassTransit v8 saga state machine, durable per-instance correlation state in the owning service&#39;s own database, and per-instance deadlines instead of this fixed-interval sweep. The technology is already pinned, because MassTransit is held at v8 (v9 requires a commercial license). The trigger is specific: a workflow with three or more steps across two or more services, state that does not fit one aggregate, and at least one per-instance deadline. It ships no code today, and even after a coordinator exists the sweep stays underneath it for the external system that never replies.</li><li><strong>Inconsistency is bounded, not eliminated.</strong> Between the cancellation commit and the compensation commit, stock is held against a cancelled order. Between a dropped webhook and the sweep, an order sits in PaymentInitiated with stock held for up to the stuck age plus one poll interval: 30 plus 10 minutes at the shipped defaults. That window is the price of not having a distributed transaction, and it should be a number you choose, not one you discover.</li><li><strong>Compensation is best-effort per line, and the skip is now reported rather than silent.</strong> RestoreInventory cannot restore an order line whose InventoryItem row is missing, so it collects those variant ids and returns them instead of skipping quietly, and the handler logs them as a warning naming the order and the variants. The behavior underneath is unchanged: the marker still commits, that quantity is never restored, and nothing retries it. The comment above the marker says why: the increases and the marker land in the same save, so withholding the marker would re-apply every <strong>matched</strong> increase on the next redelivery, and because the lookup already ignores the soft-delete filter, an unmatched variant means the row never existed at all. The warning is the record, not a repair. (ADR-054&#39;s own trade-off bullet still describes the older silent skip.)</li><li><strong>Redelivery re-runs every handler of the event, not the failed one.</strong> The dispatcher iterates handlers sequentially with no per-handler isolation, so one throwing handler also skips the handlers after it, and a redelivery re-runs the ones that already succeeded. The mark-processed step covers the save’s whole local batch, so what comes back is every event that save raised, not just the failed one. Every handler on a shared event must be idempotent or must swallow.</li><li><strong>The sweep is not replica-leased.</strong> The outbox processor claims rows with a lease before working them (ADR-003); the sweep takes no such claim, so at the configured maxReplicas: 2 two replicas can pick the same stuck order and each spend a Stripe status call. Correctness holds through the concurrency token; the duplicated external call does not deduplicate.</li><li><strong>The webhook ingress trades visibility for endpoint survival.</strong> A post-acceptance failure returns 200, so it is invisible in Stripe’s delivery view and has to surface through our own Warning log or through the sweep above. The endpoint is also anonymous and internet-reachable, with signature verification as its only authentication, so a hostile caller can generate Critical log volume one rejected request at a time.</li><li><strong>Every compensating action needs its own marker.</strong> There is no generic mechanism here. A second compensating action means a second persisted marker or a naturally idempotent operation, decided by the author of that handler.</li></ul><h3>Apply this even without MMCA</h3><p>The mechanism ports to any stack that has events, a database, and an external dependency:</p><ol><li><strong>Put the compensating action in its own handler</strong>, triggered by the event the first step raised, not in an else branch of the command. It commits after the originating transaction, in its own scope, which is what makes it compensation instead of an impossible rollback.</li><li><strong>Make idempotency a persisted marker that commits with the writes it guards.</strong> One SaveChanges, one database, one transaction. A flag written after the work is a narrower version of the same bug; a flag written with the work is an invariant. Guard the marker in the aggregate so a second call is a typed failure, not a silent overwrite.</li><li><strong>Add an optimistic-concurrency token</strong> so two simultaneous deliveries cannot both pass the marker check and both commit. The marker handles sequential re-runs, the token handles concurrent ones. You need both.</li><li><strong>Let your delivery layer own retry.</strong> If your event transport already retries with backoff and dead-letters, throw and let it re-run you. Decide explicitly, per handler, whether failure should force a redelivery (throw) or be absorbed (catch and log). A shared base class that logs the handler and event context and then rethrows makes the honest option the default one; absorbing a failure should be a visible catch in the handler that chose it. Then check what your delivery layer actually redelivers: if it acknowledges a batch in one step, one thrown exception brings the whole batch back, not just your event.</li><li><strong>Decide what your inbound webhook’s status code means, and write it down.</strong> A third-party caller reads it as a delivery instruction (“retry me” or “stop”), not as an application result, and providers disable endpoints that keep failing. Return the error code only for the failures a retry could fix (bad signature, unparseable body, missing secret), accept everything else and surface the failure through your own telemetry, and log a rejection at a level your production log floor actually emits.</li><li><strong>Back every externally-confirmed step with a periodic reconciliation sweep</strong>, because a confirmation that never arrives produces no event to compensate. Bound the query in the database, reload and re-check each item in its own scope, drive the <strong>same</strong> guarded transitions the primary path uses, and let it lose races to the primary path rather than fighting them.</li></ol><p>The rule of thumb: <strong>any step you cannot roll back needs an explicit undo, and any step you cannot confirm needs an explicit timeout. Write both down as code, or your consistency story is hope with extra steps.</strong></p><p><strong>What we covered:</strong> why a cross-boundary workflow has no transaction to roll it back, how MMCA.Store puts compensation in its own domain-event handler running in its own DI scope, how the Order.InventoryRestored marker committed by the same SaveChanges as the inventory increases turns idempotency into a database invariant (and why that is stronger than a record-after-success inbox), how the RowVersion token serializes concurrent redeliveries, why throwing is the correct failure mode when the outbox already owns retry, why the inbound webhook&#39;s status code encodes acceptance rather than success and registers its own endpoint (ADR-084), and how PaymentReconciliationService acts as the saga-timeout backstop by asking Stripe for authoritative status and driving the same guarded transitions a lost webhook would have.</p><p><strong>Next in the series:</strong> Article 50, the series index: every pattern in one place, from the Result railway to this one.</p><p><em>MMCA.Common is open source. Star the repo, read the 2-minute ADR-054 behind this pattern, or </em><em>dotnet add package MMCA.Common.API and build the monolith you can extract later.</em></p><p><strong>About the author</strong></p><p>Ivan Ball-llovera is a senior software architect working in enterprise .NET. This series is built on <strong>MMCA.Common</strong>, the open-source framework behind it: fifteen NuGet packages for a modular monolith you can extract services out of later, scored in public against a 34-category architecture rubric, gaps included.</p><ul><li>The framework: <a href="https://github.com/ivanball/MMCA.Common">https://github.com/ivanball/MMCA.Common</a></li><li>Start a new app: dotnet new install MMCA.Templates then dotnet new mmca-app -n Your.App</li><li>Add it to an existing solution: dotnet add package MMCA.Common.API</li><li>The full series index and the architecture docs: <a href="https://ivanball.github.io/writing.html">https://ivanball.github.io/writing.html</a></li></ul><p>Follow along here for one pattern a week.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa017f9591b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Observability by Default: OpenTelemetry and Azure Monitor in MMCA]]></title>
            <link>https://medium.com/@ivanball76/observability-by-default-opentelemetry-and-azure-monitor-in-mmca-673c1886e9e0?source=rss-b79b63d05524------2</link>
            <guid isPermaLink="false">https://medium.com/p/673c1886e9e0</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[opentelemetry]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Ivan Ball-llovera]]></dc:creator>
            <pubDate>Tue, 18 Aug 2026 11:47:53 GMT</pubDate>
            <atom:updated>2026-08-22T01:50:00.711Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Auto-instrumentation gives you HTTP and runtime signals for free, but it is blind to the two paths that carry almost all of your framework’s own work: the CQRS pipeline and the outbox. Here is how one shared hosting call wires OpenTelemetry logs, metrics, and traces, ships to the Aspire dashboard locally and to Azure Monitor in the cloud with no code change, and filters idle outbox-poll spans so telemetry does not quietly become your biggest cloud line item.</em></p><p><em>Part of the MMCA.Common series · Article 48 of 50. One pattern at a time.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NiXtpN9ECMrobnDrcGLdZA.png" /></figure><p>You split the monolith into a handful of services, wire up OpenTelemetry because that is what you are supposed to do, deploy, and open the dashboard. HTTP spans are there. Runtime counters are there. Then someone asks the two questions that actually matter in an incident: “how long is this command taking and how often is it failing” and “is the outbox dead-lettering.” And you realize the traces cannot answer either one.</p><p>That is not a gap in your setup. It is the ceiling of auto-instrumentation. The ASP.NET Core, HttpClient, and .NET-runtime instrumentations give you generic transport and process signals, but they are structurally blind to the two paths that carry almost all of a CQRS-and-outbox framework&#39;s real work: the use-case pipeline and the background message drain. Nobody instruments those unless the framework does it for them.</p><p>And then the first Application Insights bill arrives. A deployed fleet polls every relational outbox table around the clock, and if every idle poll ships a span (plus the SqlClient child the Azure Monitor distro attaches to it), steady-state nothing becomes the loudest thing in your telemetry. Full-fidelity tracing is already the single largest observability line item; idle polling piles on top of it.</p><p>MMCA.Common treats observability as a hosting-layer default: one call on the host builder, and every service in the model gets the same logs, metrics, and traces, the same framework-specific instrumentation where auto-instrumentation is blind, and the same cost knobs that fail toward keeping data.</p><h3>Why it matters</h3><p>Observability is the category you do not miss until production, and by then retrofitting it is expensive. The rubric names the bar directly: structured logging with correlation IDs across boundaries, distributed tracing and RED metrics wired to a backend, health checks for orchestrators, and (the part most teams skip) deliberate noise control so high-volume low-value telemetry does not run up the bill. It is a weight-2 category.</p><p>Two forces pull against each other here. You want enough signal to operate the system, and you do not want the signal to cost more than the system. Most teams pick one end: they either instrument everything at full fidelity and get a telemetry invoice that rivals compute, or they trim so hard that an incident becomes a guessing game. The interesting engineering is in wiring the useful signal by default while making the expensive fidelity a knob you turn per host, not a rewrite.</p><p>The other reason it matters: in a modular monolith that extracts into services, the same telemetry has to make sense whether a request stays in one process or crosses a gateway and three service hosts. If observability is bolted on per app, it drifts. If it lives in the shared hosting defaults, every host, in-process or extracted, tells the same story the same way.</p><h3>The MMCA answer: one call, one baseline, on every host</h3><p>Every framework-consuming host calls AddServiceDefaults() first in Program.cs, and that method calls ConfigureOpenTelemetry() before anything module-specific. So a host opts in once and every project in the Aspire model inherits the identical telemetry pipeline. There is no per-app ServiceDefaults copy: all four ADC services and all three Store services consume this one implementation directly, as do both gateways and both web UIs.</p><p>ConfigureOpenTelemetry does four things.</p><p><strong>It wires logging, metrics, and tracing.</strong> Logs go through the OpenTelemetry logger with IncludeFormattedMessage and IncludeScopes on so a scope carries its structured state. Metrics start from ASP.NET Core instrumentation, always on. Tracing starts from ASP.NET Core and HttpClient instrumentation. That is the free auto-instrumentation floor.</p><p><strong>It instruments only where auto-instrumentation is blind.</strong> Seven framework-owned meters carry custom signals, subscribed here by literal name because the Aspire package deliberately has no project reference to the assemblies that define them:</p><ul><li>The CQRS pipeline publishes RED metrics through a single meter MMCA.Common.Cqrs: two duration histograms, cqrs.command.duration and cqrs.query.duration, both in milliseconds, recorded by the logging decorators and tagged by the operation name and an outcome tag. Count gives rate, the tag gives errors, the histogram gives duration. RED falls out of a pipeline layer that already exists (the logging decorator), so there is no per-handler discipline to keep up. The same meter carries cqrs.query.cache.hit and cqrs.query.cache.miss counters, recorded by the caching query decorator, so a hit ratio per query is chartable off the same subscription, plus two short-circuit counters recorded by the authorization and timeout decorators: cqrs.authorization.denied.count and cqrs.timeout.count, both tagged request_type, so a permission denying more traffic than expected or a handler that keeps exhausting its execution budget is visible as a metric rather than only as a client-side error rate.</li><li>The outbox owns a meter MMCA.Common.Outbox, declared with all of its instruments in a dedicated OutboxMetrics class rather than in the processor: a dead-letter counter outbox.dead_letter.count, a success counter outbox.processed.count, an end-to-end dispatch-lag histogram in seconds, and an ObservableGauge for pending depth, published each cycle from the depth the processor observed. The dead-letter counter has two increment sites, tagged event_type and reason: an unresolvable event type (reason type_unresolvable) and an exhausted retry budget (reason retries_exhausted). The same activity source emits outbox spans.</li><li>The API idempotency filter owns a meter MMCA.Common.Idempotency with three counters: idempotency.replayed, idempotency.conflict tagged by kind, and idempotency.degraded for a request that ran without the guarantee because the cache or lock faulted.</li><li>The recurring job scheduler owns a meter MMCA.Common.Scheduler with three instruments: a scheduler.job.runs counter tagged by job name and by outcome, Succeeded, Failed or Skipped, a scheduler.job.duration histogram in seconds measured around the job&#39;s own execution, and a scheduler.job.lag histogram in seconds between an occurrence becoming due and actually starting, which is the number that answers &quot;is the scheduler keeping up.&quot; A host that never enables the scheduler simply publishes nothing on that meter, so the subscription costs it nothing.</li><li>Three more meters cover paths a host opts into, and they are the newest additions to the list. The broker transport owns MMCA.Common.Broker with two counters tagged event_type: broker.fault.count for integration events that exhausted their retry policy and were published as a MassTransit Fault&lt;TEvent&gt;, which is the natural alert target for consumer health, and broker.circuit.open.count for outbox publishes the open circuit breaker rejected before they ever reached the broker. The output-cache eviction consumer owns MMCA.Common.OutputCache with one counter, cache.eviction.failed tagged cache_tag: a non-zero rate means this host is still serving cached responses it was told to drop, so it is the alert target for cross-service cache coherence. And best-effort side effects own MMCA.Common.BestEffort with besteffort.dispatch.failed tagged operation, the count of failures that were deliberately swallowed. That last one is a meter of its own rather than a counter folded into MMCA.Common.Cqrs precisely because best-effort dispatch is not part of the CQRS pipeline (hosts call it from handlers, hosted services and consumers alike), so an operator can drop or keep it independently of the RED metrics. All three publish nothing in a host that stays on the in-process bus, takes no output cache, and dispatches no best-effort work.</li></ul><p>The Aspire defaults subscribe all seven meters and the outbox trace source by literal name, with a comment enumerating what each one carries.</p><p><strong>It exposes cost knobs that default to safe.</strong> The two heaviest metric families on a low-traffic multi-service deployment are conditional. HttpClient connection and request metrics are added only when Telemetry:DisableHttpClientMetrics is unset or false, and .NET runtime metrics (dotnet.gc.*, jit.*, thread_pool.*) only when Telemetry:DisableRuntimeMetrics is unset or false. Both keys are read by IsInstrumentationDisabled, which drops the family only when the value parses as boolean true; absent, blank, or unparseable keeps the instrumentation, so a typo cannot silently blind a whole metric family. Head-based trace sampling is the third knob: Telemetry:TracesSampleRatio, parsed by TryGetTraceSampleRatio, is unset by default so a host samples everything. Set a ratio in the open interval (0,1) and it installs a TraceIdRatioBasedSampler wrapped in a ParentBasedSampler so a sampled-in request keeps its whole trace intact across service boundaries. A value that is absent, unparseable, or outside (0,1) falls back to sample-all, so a typo can never silently drop all telemetry.</p><p><strong>It filters idle outbox-poll spans out of export.</strong> More on this below; it is the sharpest decision in the file.</p><p>Then AddOpenTelemetryExporters decides where telemetry goes, from the environment, with no code change: OTLP when OTEL_EXPORTER_OTLP_ENDPOINT is present (the Aspire dashboard sets it locally) and Azure Monitor via UseAzureMonitor when APPLICATIONINSIGHTS_CONNECTION_STRING is present (set by the cloud deployment). Both can be active at once. Local development ships to the Aspire dashboard; production ships to workspace-based Application Insights; the same binary does both depending on which variable is set.</p><p>Here is the shape of the pipeline (condensed from the real source, comments trimmed, body faithful):</p><pre>public TBuilder ConfigureOpenTelemetry()<br>{<br>    builder.Logging.AddOpenTelemetry(logging =&gt;<br>    {<br>        logging.IncludeFormattedMessage = true;<br>        logging.IncludeScopes = true;<br>    });<br>    <br>    builder.Services.AddOpenTelemetry()<br>        .WithMetrics(metrics =&gt;<br>        {<br>            metrics.AddAspNetCoreInstrumentation();<br>            <br>            // Two highest-volume families, on by default, each behind a cost knob:<br>            if (!IsInstrumentationDisabled(builder.Configuration, &quot;Telemetry:DisableHttpClientMetrics&quot;))<br>                metrics.AddHttpClientInstrumentation();<br>            if (!IsInstrumentationDisabled(builder.Configuration, &quot;Telemetry:DisableRuntimeMetrics&quot;))<br>                metrics.AddRuntimeInstrumentation();<br>            <br>            // Framework meters, subscribed by literal name:<br>            metrics.AddMeter(&quot;MMCA.Common.Outbox&quot;)<br>                   .AddMeter(&quot;MMCA.Common.Cqrs&quot;)<br>                   .AddMeter(&quot;MMCA.Common.Idempotency&quot;)<br>                   .AddMeter(&quot;MMCA.Common.Scheduler&quot;)<br>                   .AddMeter(&quot;MMCA.Common.Broker&quot;)<br>                   .AddMeter(&quot;MMCA.Common.OutputCache&quot;)<br>                   .AddMeter(&quot;MMCA.Common.BestEffort&quot;);<br>        })<br>        .WithTracing(tracing =&gt;<br>        {<br>            tracing.AddSource(builder.Environment.ApplicationName)<br>                   .AddSource(&quot;MMCA.Common.Outbox&quot;)<br>                   .AddAspNetCoreInstrumentation()<br>                   .AddHttpClientInstrumentation()<br>                   // Drop idle poll spans before the exporters see them:<br>                   .AddProcessor(new Telemetry.OutboxPollFilterProcessor());<br>            <br>            // Off by default; a deployed host opts into head-based sampling:<br>            if (TryGetTraceSampleRatio(builder.Configuration, out var ratio))<br>                tracing.SetSampler(new ParentBasedSampler(new TraceIdRatioBasedSampler(ratio)));<br>        });<br>    <br>    builder.AddOpenTelemetryExporters(); // OTLP and/or Azure Monitor, by env var<br>    return builder;<br>}</pre><h3>The one that pays for itself: filtering idle poll spans</h3><p>The OutboxProcessor polls every relational outbox table on a recurring cycle (both deployment templates push the interval to 300 seconds precisely so idle polls cost less, against a 2-second default in the settings class). Each poll runs inside an OutboxPoll activity, and under the Azure Monitor distro that span gets a child SqlClient dependency span for the poll query. A second OutboxPoll activity wraps the backlog-depth count that feeds the pending-depth gauge, deliberately reusing the same name so the same filter suppresses it. At fleet scale, that steady stream of idle-poll spans would dominate Application Insights ingestion and spam the local dashboard, telemetry about nothing happening, priced like something happening.</p><p>OutboxPollFilterProcessor is a BaseProcessor&lt;Activity&gt; that drops exactly those spans. Its OnEnd walks the ending span&#39;s in-process parent chain and, if any ancestor matches both OperationName == &quot;OutboxPoll&quot; and Source.Name == &quot;MMCA.Common.Outbox&quot; (checking both avoids suppressing an unrelated span that happens to be named &quot;OutboxPoll&quot;), clears the Recorded flag. Clearing Recorded makes the batch exporters skip the activity, which is why the processor is registered before the exporters: its OnEnd runs first, and the exporters never see the span.</p><p>Real work survives untouched. Each per-message OutboxProcess span is started under an explicit parent context rebuilt from the message&#39;s stored trace and span ids and passed straight into StartActivity, so it is never a child of the poll span and never matched by the parent-chain walk. The outbox counters, the lag histogram, and the pending-depth gauge are metrics, not spans, so they are unaffected too. You lose the noise and keep the signal.</p><p>The OutboxPoll and MMCA.Common.Outbox literals live on both sides of the package boundary: the filter, and the outbox, which now declares them across three sites (the poll-activity name and the activity source in OutboxProcessor, the meter name in OutboxMetrics). They are duplicated on purpose, with a sync comment on both sides, because the Aspire package must not take a project reference on Infrastructure. That is the honest price of a decoupled package graph, and it is a trade-off, not an accident.</p><h3>The other half: which signal wakes a human</h3><p>Everything above is emission. Which of those signals pages somebody, at what threshold, at what severity, is a separate decision, and for a long time it lived in the deployment templates and an operations runbook with no record behind it. That decision is now written down.</p><p>Each consuming app declares its SLO alerts as <strong>data in its Bicep template</strong>. sloAlertSpecs is one array of records carrying key, description, query, timeAggregation, metricMeasureColumn, threshold, and severity, materialized one-for-one into Log Analytics scheduledQueryRules named ${prefix}-alert-${spec.key}-v2 and evaluated every 5 minutes over a 15-minute window. Both apps declare the same three SLOs with the same numbers: failed-requests at severity 2, server-response-time at severity 3, and dependency-failures at severity 2. An alert clicked together in the portal is invisible to review, absent from the next environment, and impossible to diff; an array in the template that provisions the workloads is all three.</p><p><strong>Why log-search rules and not metric alerts.</strong> This is the decision worth stealing. The originals were metric alerts on requests/failed, requests/duration, and dependencies/failed, and they paged on completely routine traffic. A 401 (expired or absent auth) and a 499 (client disconnected mid-request) both count as failed requests, and a long-lived SignalR hub connection reports its <strong>connection lifetime</strong> as request duration. The template records the two pages that made the case: one window held eight 401s plus two 499s plus a single readiness 503 and zero other failures, all from one browser session retrying with an expired token, while five hub connections averaging 11.3 seconds dragged the fleet-wide average to 5539ms against a 3000ms threshold with every real request fast. A metric alert has no way to say &quot;exclude 401 and 499&quot; or &quot;exclude /hubs/ before averaging&quot;; a KQL query says exactly that. Thresholds and severities did not move, so this is a precision fix, not a sensitivity cut: a genuine 400 or 500 burst still pages at the same number as before.</p><p><strong>The operational trap: disabled beats deleted.</strong> An incremental ARM deployment never removes a resource just because it left the template. A metric alert dropped from the Bicep stays live in the resource group, still firing next to the query rule that covers the same signal, and nothing in the deploy tells you. So the metric alerts stay declared under their unsuffixed names with enabled: false and an empty actions array, and the query rules carry the -v2 suffix so that reusing a name cannot rename a live metric alert instead of disabling it. Silencing in place is declarative, needs no portal step, and reverts in one line.</p><p>Two smaller properties matter as much. Every active rule routes to <strong>one unconditional action group</strong>: the alert email address is a required parameter with no default, so the email receiver is never conditional and every rule points at it. An alert wired to no channel is worse than no alert, because it looks like coverage and pages nobody. And a saved workbook renders the same signals off the same workspace, embedded at compile time from a JSON file in the repo, so the dashboard cannot drift from the alerts by being maintained somewhere else.</p><p>The other half of this decision is a build gate that fails when an alert has no severity-matching runbook section, or when a runbook section outlives its alert. That belongs with the rest of the fitness tier, so it is Article 34’s subject rather than this one’s.</p><p>Two honest limits. The gate covers only what sits inside the parsed spec window, and both apps provision alerts outside it. The conference app has three: the outbox-dead-letter and sql-dependency-failures scheduled query rules, and a severity 1 gateway-availability alert over a three-location URL ping web test. The store app now carries two of the same three: its own outbox-dead-letter scheduled query rule and a severity 1 gateway-availability alert over the same three-location /health web test. Only the sql-dependency-failures companion is deliberately not ported, because the store&#39;s generic dependency-failures SLO rule already spans SQL, gRPC and HTTP. All of them can be added, renamed, or re-tiered with no runbook consequence. And the minimal reference app has no infra/ template at all, so it has neither the alerts nor anything for a pairing gate to check.</p><h3>Trade-offs, honestly</h3><ul><li><strong>The literal names can drift.</strong> The meter, activity-source, and poll-span names are duplicated as string literals across the Aspire package (the filter’s two literals plus the seven AddMeter calls) and the defining assemblies (CqrsMetrics, OutboxMetrics, IdempotencyMetrics, SchedulerMetrics, BrokerMetrics, OutputCacheMetrics, BestEffortMetrics, OutboxProcessor). Every new meter family widens that surface, and each of the three most recent ones landed with the same duplicated-literal note in its own doc comment. A rename on one side silently stops the matching export or subscription until the literal is updated. The decoupled package graph is worth it; the sync discipline is real.</li><li><strong>Sampling trades trace completeness for cost.</strong> A sampled-out trace is gone, so deep debugging of one specific request can miss it. Metrics and logs are unaffected (sampling is trace-only), so RED rates and error counts stay whole even at a low ratio. Size the ratio to your debugging horizon, not to zero.</li><li><strong>Poll-span filtering hides steady-state outbox activity by design.</strong> “Is the poller alive and looping” is not a question traces answer. That signal lives in metrics on purpose, and the metrics that answer it exist: outbox.processed.count, the dispatch-lag histogram, the pending-depth gauge, and the dead-letter counter. If you rely on poll spans for a liveness check, chart those instead.</li><li><strong>Exporters are opt-in per host.</strong> A host that sets neither OTEL_EXPORTER_OTLP_ENDPOINT nor APPLICATIONINSIGHTS_CONNECTION_STRING emits to nothing. And the cost knobs fail toward keeping data (higher cost), not toward silence, so a misconfigured ratio is a possible cost surprise, never a silent data gap. That is the intended bias, but it is a bias worth naming.</li></ul><h3>Apply this even without MMCA</h3><p>The pattern ports to any OpenTelemetry stack, with or without Aspire:</p><ol><li><strong>Put the telemetry baseline in one shared bootstrap</strong> every host calls, not in each app. One place to change the meter list, tighten a timeout, or add a processor means every service moves in lockstep.</li><li><strong>Instrument only where auto-instrumentation is blind.</strong> Let ASP.NET Core, HttpClient, and the runtime ride the free instrumentation. Add your own meters and activity sources for the paths that carry your real work (a use-case pipeline, a background drain), and emit RED from a layer you already have (a logging decorator) rather than sprinkling it through every handler.</li><li><strong>Make expensive fidelity a knob, not a rewrite.</strong> Gate the highest-volume metric families and head-based trace sampling behind configuration, and make every knob fail toward keeping data: drop a family only on an explicit boolean, ignore an out-of-range sample ratio, and treat a typo as sample-all.</li><li><strong>Filter high-volume low-value spans before export.</strong> A recurring poll, a health-check ping, an idle heartbeat: drop them with a processor that clears the Recorded flag, registered before your exporters, and match on both operation name and source so you never suppress an unrelated span by name alone.</li><li><strong>Choose the exporter from the environment.</strong> Ship to a local dashboard when the OTLP endpoint variable is set and to your cloud backend when its connection-string variable is set, both at once if you like, so the same binary works from laptop to production with no code change.</li></ol><p>The takeaway: <strong>observability is a hosting-layer default, not a per-app afterthought. Wire the useful signal once for every host, instrument the paths auto-instrumentation cannot see, and make the expensive fidelity a knob that fails toward data, because the two ways this goes wrong in production are a telemetry bill you did not expect and a trace that cannot answer the question you actually have.</strong></p><p><strong>What we covered:</strong> why auto-instrumentation is structurally blind to the CQRS pipeline and the outbox, how one ConfigureOpenTelemetry call in the shared Aspire defaults wires logs, metrics, and traces plus seven framework meters (MMCA.Common.Cqrs RED histograms plus its cache and short-circuit counters, the MMCA.Common.Outbox counters and gauge, the MMCA.Common.Idempotency counters, the MMCA.Common.Scheduler run, duration and lag instruments, and the MMCA.Common.Broker, MMCA.Common.OutputCache and MMCA.Common.BestEffort failure counters) on every host, how three fail-safe cost knobs (Telemetry:DisableHttpClientMetrics, Telemetry:DisableRuntimeMetrics, Telemetry:TracesSampleRatio) trim spend without going dark, how OutboxPollFilterProcessor drops idle poll spans before export while real outbox work survives, how the exporter (OTLP or Azure Monitor, or both) is chosen from environment variables with no code change, and how the SLO alerts that actually page a human are declared as data in each app&#39;s deployment template, as Log Analytics query rules rather than metric alerts, with the superseded metric alerts disabled in place instead of deleted.</p><p><strong>Next in the series:</strong> Article 49, “Undo Is a Feature: Saga Compensation and the Reconciliation Backstop,” the deep-dive on undoing a cross-boundary workflow when there is no two-phase commit to roll it back for you.</p><p><em>MMCA.Common is open source. Star the repo, read the 2-minute ADR-041 behind this pattern, or </em><em>dotnet add package MMCA.Common.Aspire and call </em><em>AddServiceDefaults().</em></p><p><strong>About the author</strong></p><p>Ivan Ball-llovera is a senior software architect working in enterprise .NET. This series is built on <strong>MMCA.Common</strong>, the open-source framework behind it: fifteen NuGet packages for a modular monolith you can extract services out of later, scored in public against a 34-category architecture rubric, gaps included.</p><ul><li>The framework: <a href="https://github.com/ivanball/MMCA.Common">https://github.com/ivanball/MMCA.Common</a></li><li>Start a new app: dotnet new install MMCA.Templates then dotnet new mmca-app -n Your.App</li><li>Add it to an existing solution: dotnet add package MMCA.Common.API</li><li>The full series index and the architecture docs: <a href="https://ivanball.github.io/writing.html">https://ivanball.github.io/writing.html</a></li></ul><p>Follow along here for one pattern a week.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=673c1886e9e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Security Headers and CSP for Blazor: One Middleware, Every Host]]></title>
            <link>https://medium.com/@ivanball76/security-headers-and-csp-for-blazor-one-middleware-every-host-af82df95236e?source=rss-b79b63d05524------2</link>
            <guid isPermaLink="false">https://medium.com/p/af82df95236e</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[blazor]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[content-security-policy]]></category>
            <category><![CDATA[web-security]]></category>
            <dc:creator><![CDATA[Ivan Ball-llovera]]></dc:creator>
            <pubDate>Mon, 17 Aug 2026 11:44:16 GMT</pubDate>
            <atom:updated>2026-08-22T01:49:10.141Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Every client-facing host must stamp the same hardened response headers, but a Blazor host needs a Content-Security-Policy no static string can express. Here is one middleware that centralizes the headers and resolves the CSP through a pluggable provider, applied at both edges of both apps, formalized in ADR-023.</em></p><p><em>Part of the MMCA.Common series · Article 47 of 50. One pattern at a time.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XVPZzHEl4w9tg_3B_3otjg.png" /></figure><p>You add X-Frame-Options: DENY, HSTS, and a strict Content-Security-Policy to your Blazor app. You deploy. The page loads white. The browser console is a wall of red: Refused to evaluate a string as JavaScript because &#39;unsafe-eval&#39; is not an allowed source of script. Blazor WebAssembly cannot boot, MudBlazor cannot style a single component, and your &quot;hardening&quot; just took the whole front-end offline.</p><p>So you loosen the CSP until the app works again. Then you copy that policy into the second host, and the gateway, and the next app. Six months later the Gateway sends frame-ancestors &#39;none&#39; and the UI host sends nothing, because someone edited one copy and forgot the others. A new edge host ships with no headers at all, because adding them was a manual step nobody remembered. The headers that were supposed to be a baseline became per-host folklore that drifts.</p><p>The two problems are linked. The header set wants to be defined once and inherited everywhere. But the CSP, the one header that actually breaks the app when it is wrong, cannot be a single constant: an API or gateway serving JSON and WebSockets wants a strict fixed policy, while a Blazor host needs script-src &#39;wasm-unsafe-eval&#39;, style-src &#39;unsafe-inline&#39;, and a connect-src pinned to an API origin it only learns at runtime. One string cannot serve both, and a wrong string is an outage.</p><h3>Why it matters</h3><p>Security response headers are cheap defence-in-depth: X-Content-Type-Options: nosniff stops MIME sniffing, X-Frame-Options and frame-ancestors stop clickjacking, HSTS forces HTTPS, and a Content-Security-Policy shrinks the blast radius of an XSS bug by refusing to load script and connect to origins you did not allow. None of them cost a request. All of them are worthless if a host forgets to send them.</p><p>The failure mode is silence. A host that stamps no X-Frame-Options does not throw, does not log, and passes every functional test. You find out it was frameable when someone clickjacks it. A CSP that drifted permissive between two copies protects the strict copy and quietly stops protecting the other. Security headers are exactly the kind of cross-cutting concern that rots when it lives as copied boilerplate in each host&#39;s Program.cs, because the cost of getting one wrong is invisible until it is an incident.</p><p>And the CSP raises the stakes further, because it is the one header where the safe direction and the working direction point opposite ways. Tighten it and you protect the page; tighten it wrong and you blank the page. That tension is why the framework cannot just ship a hardened constant and be done.</p><h3>The MMCA answer: one middleware, a pluggable CSP</h3><p>MMCA.Common ships a single SecurityHeadersMiddleware in the MMCA.Common.Aspire.Security layer, registered with AddCommonSecurityHeaders(configuration?, configure?) and mounted early with UseCommonSecurityHeaders(). Every response gets the same hardened set, and the CSP is resolved through an extension point rather than baked in as a constant.</p><p>The static part is the easy part. InvokeAsync stamps X-Content-Type-Options: nosniff, X-Frame-Options (default DENY), Referrer-Policy (default strict-origin-when-cross-origin), Permissions-Policy (default geolocation=(), microphone=(), camera=(), payment=()), and HSTS (max-age=31536000; includeSubDomains). Every value lives on SecurityHeadersSettings with those hardened defaults, overridable via the &quot;SecurityHeaders&quot; configuration section or the configure delegate. HSTS is emitted only when EnableHsts is set and the environment is not Development: the middleware computes _enableHsts = options.Value.EnableHsts &amp;&amp; !environment.IsDevelopment() once in its constructor, so localhost never gets pinned to HTTPS for a year.</p><p>The interesting part is the CSP. Instead of stamping a string, the middleware asks an ICspPolicyProvider for a CspPolicy(string Value, bool Enforce). When Enforce is true it writes Content-Security-Policy; when false it writes Content-Security-Policy-Report-Only; a null return emits no CSP at all. The enforce-versus-report split is the whole point: Report-Only lets a browser report violations without blocking the page, which is how you trial a tightened policy or degrade safely from a broken one.</p><pre>// SecurityHeadersMiddleware.InvokeAsync, condensed from SecurityHeaders.cs:117-145<br>var headers = context.Response.Headers;<br>headers.XContentTypeOptions = &quot;nosniff&quot;;<br>headers.XFrameOptions = _settings.FrameOptions;                       // &quot;DENY&quot;<br>headers[&quot;Referrer-Policy&quot;] = _settings.ReferrerPolicy;               // &quot;strict-origin-when-cross-origin&quot;<br>headers[&quot;Permissions-Policy&quot;] = _settings.PermissionsPolicy;<br><br>if (_enableHsts)                                                       // EnableHsts &amp;&amp; !IsDevelopment()<br>{<br>    headers.StrictTransportSecurity = _settings.HstsValue;           // &quot;max-age=31536000; includeSubDomains&quot;<br>}<br><br>CspPolicy? csp = _cspPolicyProvider.GetPolicy(context);              // the extension point<br>if (csp is not null)<br>{<br>    if (csp.Enforce) headers.ContentSecurityPolicy = csp.Value;<br>    else             headers.ContentSecurityPolicyReportOnly = csp.Value;<br>}<br><br>await _next(context).ConfigureAwait(false);</pre><p>The default provider is StaticCspPolicyProvider, registered with TryAddSingleton so a host can override it. It returns the baseline from SecurityHeadersSettings.ContentSecurityPolicy: default-src &#39;self&#39;; object-src &#39;none&#39;; base-uri &#39;self&#39;; form-action &#39;self&#39;; frame-ancestors &#39;none&#39;. Note what is missing: no script-src, no style-src. That omission is deliberate and documented on the setting itself. It is the right complete policy for the JSON, WebSocket, and static-page responses an API or gateway serves, and a safe-but-partial policy for an HTML host that forgot to register something fuller. The framework will never be the thing that blanks out a Blazor app, because its default CSP does not restrict the scripts and styles Blazor needs.</p><h3>The Blazor policy, built at runtime</h3><p>An HTML host opts into the strong policy by registering its own provider before calling AddCommonSecurityHeaders. Both apps register one shared BlazorCspPolicyProvider via AddCommonBlazorCsp(), which is a one-line AddSingleton&lt;ICspPolicyProvider, BlazorCspPolicyProvider&gt;. Because the static default is registered with TryAdd, the first-registered provider wins, so the call order is load-bearing: AddCommonBlazorCsp() must run before AddCommonSecurityHeaders(...).</p><p>The provider builds the full policy once, at construction, and returns the cached result for every request. BuildPolicy assembles what a Blazor + MudBlazor page actually needs: default-src &#39;self&#39;, script-src &#39;self&#39; &#39;wasm-unsafe-eval&#39; (the WASM runtime), style-src &#39;self&#39; &#39;unsafe-inline&#39; (MudBlazor), img-src &#39;self&#39; data: https: (profile pictures and CDN images are low XSS-risk, so images stay open while the directives that matter for exfiltration stay locked), font-src &#39;self&#39;, plus base-uri, form-action, and frame-ancestors &#39;none&#39;.</p><p>The hard directive is connect-src, because it is per-deployment. BuildCsp reads the API origin from ApiSettings (WasmApiEndpoint ?? ApiEndpoint), and if it resolves to a real http(s) URL it pins connect-src to &#39;self&#39; plus that origin and its WebSocket form (wss://... for the SignalR notification hub). In Development only, it also allows http://localhost:* and ws://localhost:* so Visual Studio Browser Link and Hot Reload keep working, without ever loosening the production policy.</p><p>The detail worth stealing is the failure path. If the origin cannot be parsed, or on Linux parses as a file:// URI instead of http(s), the provider does not guess and it does not enforce a policy it could not build correctly. It returns a permissive connect-src &#39;self&#39; https: wss: policy with Enforce: false, so the middleware emits it as Content-Security-Policy-Report-Only. A misconfigured origin surfaces as violations in the browser console, not as a white page in production. Fail-safe over fail-secure, by construction.</p><p>font-src &#39;self&#39; reads like the boring entry in that list, and it is the one that carries a real web font. The shared MudBlazor theme names Inter first in its font stack, and the reflex way to supply it is a Google Fonts link tag, with the reflex follow-on of widening font-src to that CDN&#39;s origin plus a style-src allowance for its stylesheet: a third-party origin welded into the policy of every host, permanently, because of a typography change. Instead the font ships from the framework. MMCA.Common.UI vendors the Inter woff2 files (weights 400, 500, 600, 700, 800, latin subset, SIL OFL 1.1 notice alongside them) under its own wwwroot/fonts/, and its app.css declares the five faces with font-display: swap. Because a Razor class library&#39;s static assets are served from _content/MMCA.Common.UI/, the fonts are same-origin, the existing font-src &#39;self&#39; already permits them, and not one character of the CSP changed to land the refresh.</p><p>That is the part worth generalizing. A CSP directive is only a real constraint if it is allowed to shape decisions, because the moment a design choice arrives the path of least resistance is to widen the policy to fit it. Here the policy shaped the implementation instead. The honest costs: the vendored subset is latin only, so non-latin text still falls back to the platform font; the woff2 bytes ride inside the NuGet package, so updating the font means a framework release and a lockstep consumer bump rather than swapping a CDN version; and self-hosting forfeits any shared cross-site CDN cache, so each origin downloads its own copy. font-display: swap trades a visible flash of the fallback face for not blocking first paint. All of that was cheaper than an extra origin in the policy.</p><h3>Adopted at both edges of both apps</h3><p>This is not a library that exists and waits to be used. Store and ADC each wire it at both client-facing edges. The Gateway hosts call AddCommonSecurityHeaders(builder.Configuration) and UseCommonSecurityHeaders() with the strict static baseline, exactly right for a YARP proxy serving JSON, WebSockets, and a static privacy page. The Blazor UI hosts register AddCommonBlazorCsp() first, then AddCommonSecurityHeaders(builder.Configuration, options =&gt; options.EnableHsts = false) (HSTS is emitted at the gateway edge, not repeated here), then UseCommonSecurityHeaders(). The middleware carries a unit test, SecurityHeadersMiddlewareTests in MMCA.Common.Aspire.Tests, and each app&#39;s Gateway has its own SecurityHeadersTests asserting the headers are present.</p><h3>Trade-offs, honestly</h3><ul><li><strong>The baseline CSP is intentionally incomplete.</strong> It omits script-src and style-src so it can never break an unconfigured HTML host, which means an API or gateway that never registers a fuller provider gets default-src-style protection but no script/style discipline. The omission is documented on SecurityHeadersSettings.ContentSecurityPolicy, but it is a weaker default in exchange for a safer one.</li><li><strong>Registration order is a foot-gun.</strong> Because the provider uses TryAddSingleton, a host that calls AddCommonSecurityHeaders before registering its custom ICspPolicyProvider silently keeps the static default. The order is correct in both apps, but nothing forces it.</li><li><strong>A degraded policy protects nothing.</strong> The Report-Only fallback means a broken connect-src origin is non-blocking, which is the point, but it is also non-enforcing until someone notices the Report-Only header in the console. Fail-safe buys availability at the cost of a silent gap.</li><li><strong>One shared Blazor provider constrains divergence.</strong> BlazorCspPolicyProvider lives once in MMCA.Common.UI.Web over the shared ApiSettings, so a host that needs genuinely different CSP logic cannot tweak an app-local copy. It has to supply its own ICspPolicyProvider instead, registered before AddCommonSecurityHeaders.</li></ul><p>None of these argue against centralizing the headers. They argue for keeping the extension point visible and for treating the CSP as the one header you test in every host that renders HTML.</p><h3>Apply this even without MMCA</h3><p>The shape ports to any ASP.NET Core stack, and the idea ports to any web framework:</p><ol><li>Put the hardened header set in <strong>one middleware</strong> with strongly-typed, overridable settings, and mount it early so every response gets it. A new edge host inherits the baseline instead of remembering to copy it.</li><li>Do not stamp the CSP as a constant. Resolve it through a <strong>provider abstraction</strong> that returns the policy string plus an enforce-or-report flag. Static hosts get a fixed strict policy; HTML hosts inject a dynamic one.</li><li>For a Blazor or SPA host, build connect-src from the <strong>API origin at runtime</strong>, and allow only the script-src/style-src sources the framework actually requires (&#39;wasm-unsafe-eval&#39; for Blazor WASM).</li><li>Make the failure path <strong>Report-Only, not enforced</strong>. If you cannot construct the policy correctly, emit it as a report so a misconfiguration is a console warning, never an outage.</li></ol><p>The takeaway: <strong>security headers want to be defined once and inherited everywhere, but the CSP is the one header that breaks the app when it is wrong. Centralize the headers in a middleware, resolve the CSP through a provider, and let a broken policy degrade to Report-Only instead of taking the front-end down.</strong></p><p><strong>What we covered:</strong> why per-host security headers drift and why a static CSP cannot serve both an API and a Blazor host, how MMCA.Common’s SecurityHeadersMiddleware stamps one hardened header set while resolving the CSP through a pluggable ICspPolicyProvider, how the default static provider stays deliberately incomplete so it can never blank a Blazor app, how BlazorCspPolicyProvider pins connect-src to the runtime API origin and degrades to Report-Only on a misconfigured origin, and how both apps adopt it at their Gateway and UI edges (ADR-023).</p><p><strong>Next in the series:</strong> Article 48, “Observability by Default: OpenTelemetry and Azure Monitor in MMCA,” on the tracing, metrics, and logging pipeline every host gets for free.</p><p><em>MMCA.Common is Apache-2.0 licensed and open source. Star the repo, read the 2-minute ADR-023 behind this pattern, or </em><em>dotnet add package MMCA.Common.Aspire and try the middleware.</em></p><p><strong>About the author</strong></p><p>Ivan Ball-llovera is a senior software architect working in enterprise .NET. This series is built on <strong>MMCA.Common</strong>, the open-source framework behind it: fifteen NuGet packages for a modular monolith you can extract services out of later, scored in public against a 34-category architecture rubric, gaps included.</p><ul><li>The framework: <a href="https://github.com/ivanball/MMCA.Common">https://github.com/ivanball/MMCA.Common</a></li><li>Start a new app: dotnet new install MMCA.Templates then dotnet new mmca-app -n Your.App</li><li>Add it to an existing solution: dotnet add package MMCA.Common.API</li><li>The full series index and the architecture docs: <a href="https://ivanball.github.io/writing.html">https://ivanball.github.io/writing.html</a></li></ul><p>Follow along here for one pattern a week.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af82df95236e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Field-Level Encryption in EF Core: AES-GCM for PII Columns]]></title>
            <link>https://medium.com/@ivanball76/field-level-encryption-in-ef-core-aes-gcm-for-pii-columns-06ece340ea25?source=rss-b79b63d05524------2</link>
            <guid isPermaLink="false">https://medium.com/p/06ece340ea25</guid>
            <category><![CDATA[data-security]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <dc:creator><![CDATA[Ivan Ball-llovera]]></dc:creator>
            <pubDate>Sat, 15 Aug 2026 13:18:07 GMT</pubDate>
            <atom:updated>2026-08-22T01:48:29.751Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Transparent database encryption protects the file, then decrypts for anyone who can query it. When a column holds data sensitive enough that a database reader should still see ciphertext, you need a second layer: an AES-256-GCM EF Core value converter that encrypts a PII column per property, formalized in ADR-037.</em></p><p><em>Part of the MMCA.Common series · Article 46 of 50. One pattern at a time.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dpuZ3NcwyIjtRLQpCrajsg.png" /></figure><p>You turned on Transparent Data Encryption (TDE) and closed the “data at rest” line item. The database files are encrypted, the backups are encrypted, the audit checkbox is green. Then a backup gets restored onto a host it should never have touched, or an over-privileged reporting connection runs a SELECT, and every email address, every phone number, every national ID comes back in plaintext.</p><p>That is not a TDE bug. That is TDE working exactly as designed. TDE encrypts the pages on disk and decrypts them transparently for any principal that can open the database. Its threat model is a stolen disk, not a stolen query. The moment a reader is inside the database boundary, the whole point of the control has already been served, and the data is clear.</p><p>Some columns are sensitive enough to deserve a second, tighter boundary: the value should be ciphertext the instant it leaves the application, so that only a holder of the application key, not merely a database reader, can turn it back into text. In MMCA.Common that boundary is one EF Core value converter.</p><h3>Why it matters</h3><p>The gap between “the database is encrypted” and “this column is protected” is where compliance findings live. A PII inventory (what is collected, where it is stored, who can access it) will list columns whose readership you cannot actually constrain to your application. A DBA, a replicated read model, a support tool with a broad connection, a restored backup on a laptop: each is a legitimate database reader, and under TDE alone each sees plaintext.</p><p>The attacker’s side makes the same demand: data-at-rest protection and PII handling as a correctness property, not a deployment afterthought. The two meet on one column. One defends against whoever should not have the data; the other answers to the regulator who asks where the data is and who can read it. Field-level encryption is a single control that speaks to both, because it moves the trust boundary from “can reach the database” to “holds the application key.”</p><p>This is a distinct control from the two sensitive-data mechanisms the framework already records. Password hashing (ADR-032) is deliberately one-way: a credential is stored so it can be verified, never recovered. Erasure (ADR-005) removes or anonymizes personal data on a data-subject request. Neither covers the case of a field that must stay retrievable in plaintext to the application yet be unreadable in the database itself. That is the case ADR-037 answers: an at-rest, reversible, column-level confidentiality control.</p><h3>The MMCA answer: one value converter, applied per property</h3><p>The mechanism is EncryptedStringConverter, a sealed ValueConverter&lt;string, string&gt; in the MMCA.Common.Infrastructure.Persistence.Encryption namespace. You attach it to a single property in an EF entity configuration, and from that point on the property encrypts on write and decrypts on read. Application code, domain code, DTOs, handlers: all of them keep working with an ordinary string and never see ciphertext.</p><pre>// Wire the converter onto the sensitive column in the entity configuration.<br>// (Illustrative: the first HasConversion call is the converter&#39;s own documented usage,<br>//  the second paraphrases the key-ring constructor, and the layout comment<br>//  describes what Encrypt actually writes.)<br>builder.Property(e =&gt; e.SocialSecurityNumber)<br>    .HasConversion(new EncryptedStringConverter(encryptionKey)); // encryptionKey: 32 bytes<br><br>// The same converter over a ring of versioned keys, writing under version 2.<br>builder.Property(e =&gt; e.SocialSecurityNumber)<br>    .HasConversion(new EncryptedStringConverter(<br>        new Dictionary&lt;byte, byte[]&gt; { [1] = retiringKey, [2] = currentKey },<br>        currentKeyVersion: 2));<br><br>// On write, the stored value is Base64 of:<br>//   [key version (1)] [nonce (12)] [ciphertext (N)] [tag (16)]<br>// On read, the version byte picks the key, and the tag (which covers that byte) is verified.</pre><p>Four properties of that converter are worth naming precisely, because they are the whole design.</p><p><strong>It is authenticated, not merely confidential.</strong> Both directions use AesGcm, AES-256 in Galois/Counter Mode, which binds a 128-bit authentication tag to the ciphertext. Encryption gives you confidentiality; the tag gives you integrity for free. A value that has been tampered with, truncated, or corrupted fails the tag check inside AesGcm.Decrypt and throws rather than silently returning garbage plaintext. The converter also rejects, up front, any stored value too short to even hold a key version, a nonce and a tag, throwing a CryptographicException before it ever calls into the primitive.</p><p><strong>Every key is exactly 256 bits, and the converter refuses anything else.</strong> There are two constructors. The single-key one takes a raw byte[], null-checks it with ArgumentNullException.ThrowIfNull, and throws ArgumentException unless the key is exactly 32 bytes (256 bits); it is now sugar for a one-entry key ring registered at version 1. The other takes an IReadOnlyDictionary&lt;byte, byte[]&gt; key ring plus the version to write with, and validates the whole thing once at construction: the ring must be non-null and non-empty, no entry may be null, every key must be exactly 32 bytes, and the nominated current version must actually be present. The validated ring is then copied into a FrozenDictionary, so mutating the dictionary you passed in cannot change which keys the converter uses afterwards. There is a GenerateKey() helper that produces a cryptographically random 32-byte key via RandomNumberGenerator.GetBytes(32) for initial setup. The envelope sizes are fixed constants: a 1-byte key version, a 12-byte nonce (96 bits, the size NIST recommends for GCM) and a 16-byte tag (128 bits).</p><p><strong>The storage envelope is versioned and self-describing, and the ciphertext is non-deterministic.</strong> On write, Encrypt resolves the current key from the ring, takes the UTF-8 bytes of the plaintext, draws a fresh random 12-byte nonce, runs AesGcm.Encrypt, then lays out [key version] [nonce] [ciphertext] [tag] in one buffer and Base64-encodes it into the string column. On read, Decrypt Base64-decodes, reads the version byte at position 0 to select the key, slices the three remaining regions back out by their fixed offsets using spans, and calls AesGcm.Decrypt, which validates the tag while decrypting. Because the nonce is fresh on every write, the same plaintext encrypts to different ciphertext every single time. That is the correct confidentiality default: a deterministic scheme would leak equality and frequency over the column, and this one does not.</p><p><strong>The version byte is authenticated, and that makes rotation a supported operation.</strong> The version is not merely stored next to the ciphertext, it is passed to AES-GCM as associated data on both encrypt and decrypt, so the authentication tag covers it. Rewriting the version byte of a stored value therefore fails the tag check instead of quietly redirecting decryption to a different key, and it fails even when the substituted version happens to map to the same key: a test registers one key under two versions, flips the byte, and still gets a CryptographicException. Because writes always stamp the current version while reads take their key from the data, rotation is a four-step operation with no maintenance window: add the new key to the ring and make it current while keeping the old version registered, deploy (new writes carry the new version, existing rows keep decrypting under theirs), re-encrypt the old rows in the background at whatever pace the table allows, then drop the retired version from the ring. A value whose version is no longer registered throws a CryptographicException naming only the version number, never key material, which is the loud failure rather than the silent one.</p><p>There is one deliberate passthrough: both directions short-circuit on a null-or-empty string, so a NULL or empty column stays as-is rather than becoming a block of ciphertext for the empty string.</p><p>Where do the keys come from? Not from the framework. The converter takes raw key material as a constructor argument, one byte[] or a whole ring, and stops there: no DI registration, no options type, no key-provider abstraction in Infrastructure, and no automatic refresh, since the ring is frozen at construction and adding a version means constructing a new converter. The adopting entity configuration supplies the keys, and the converter&#39;s own XML documentation is explicit that they belong in Azure Key Vault, user-secrets, or an environment variable, and never hardcoded. That keeps secrets out of source and plain config, and keeps the crypto primitive free of any opinion about your secret store.</p><p>It is also stateless and context-free on purpose. Version resolution is data-driven from the stored envelope and never consults the DbContext, because a value converter is a pair of compiled expressions running inside the provider&#39;s materialization path: it cannot reach the context, the current user, or any ambient request scope. Per-tenant and per-request key selection are therefore deliberately out of scope here; that shape wants a SaveChanges interceptor or application-layer encryption above EF Core, where the request context is still reachable.</p><h3>The honest part: shipped, tested, latent</h3><p>Here is what separates this from a “look what we built” post. This converter is not in production. Zero columns across the four repositories are encrypted with it today. The plumbing is complete and the encrypt/decrypt round-trip, the tag-validated integrity path, the 32-byte key guard on both construction paths, the four ring-validation guards, the defensive copy of the caller’s dictionary, the version byte each write stamps, a full rotation round-trip, an unregistered version, a rewritten version byte, the empty-string passthrough, and the too-short-ciphertext rejection are all exercised by EncryptedStringConverterTests (21 cases as of this writing, up from 11), but no *Configuration.cs in any repo calls .HasConversion(new EncryptedStringConverter(...)). ADR-037 records that posture in the open: the capability is proven by tests, not by any deployed column.</p><p>That is deliberate. The framework’s job is to decide the algorithm, the key size, the nonce size, and the storage envelope once, in a single shared type, so that the first team to adopt it inherits a reviewed primitive instead of hand-rolling AES-GCM in a module. ADR-005 already names this converter as the mechanism for erasure fields “that must remain retrievable,” so the pairing is designed and available. It is not yet wired. Telling you that is the point: a security control you claim but have not adopted is worse than one you have honestly labeled latent.</p><p>The zero-adoption posture is also what paid for the versioned envelope. A layout of nonce, ciphertext and tag with no key identifier leaves the obvious question unanswered: what happens when the key has to change. That answer belongs in the storage format rather than in a paragraph explaining the gap, which is why the envelope leads with a key-version byte and the converter reads its key from the data. There is no legacy-decode path and there will not be one: a value in an un-versioned form does not read back under this converter, because its first byte is a nonce byte rather than a version. That break is free precisely because no column stores one. The window in which a storage format is free to change closes at the first adopted column, which is exactly why the format is settled now rather than after adoption.</p><h3>Column-level crypto vs TDE: the trade you are actually making</h3><p>TDE and field-level encryption are not competitors; they are different threat models, and the honest framing is when each earns its cost.</p><p>TDE is cheap, global, and transparent to queries. It encrypts everything at rest with no application changes and no queryability loss, and it protects against exactly one thing: someone walking off with the storage. If your risk is a stolen disk or an unencrypted backup, TDE is the whole answer.</p><p>Field-level encryption is targeted, and you pay for the targeting. It moves the trust boundary inside the database, so a database reader without the application key sees ciphertext, but that same non-determinism that makes it strong also makes the column unqueryable. You cannot equality-filter, index-seek, sort, or join on an encrypted column, because the same plaintext never produces the same bytes twice. A field that must be both encrypted and looked up needs a separate deterministic scheme or a blind index, and this converter provides neither. It is the right control for a genuinely sensitive column the application reads by primary key, not by the encrypted value itself. That is why the converter’s own shipped usage example targets a stored-only field rather than a login lookup: the XML documentation spells out that a Where against an encrypted column compares to a ciphertext that will never match and returns no rows silently, so encrypting an address the authentication flow queries by value would have broken sign-in quietly instead of loudly.</p><h3>Trade-offs, honestly</h3><ul><li><strong>Encrypted columns are not queryable.</strong> The random nonce makes ciphertext non-deterministic, so there is no equality filter, index seek, sort, or join on an encrypted column. Encrypt the columns you read by key, not the ones you search by value.</li><li><strong>Key management is still entirely yours; the ring is a mechanism, not a service.</strong> The converter holds whatever key material you hand it, frozen at construction. There is no key-provider abstraction, no Key Vault integration, no automatic refresh, and no envelope encryption over a key-encryption key. Losing a key still makes every row written under that version permanently unrecoverable; the ring makes that failure mode more granular, not less likely.</li><li><strong>Rotation is enabled, not automated.</strong> The versioned envelope makes a zero-downtime rotation possible, but the re-encryption pass is yours to write and to run, and nothing in the framework reports how many rows still carry an old version. Retire a version early and every unconverted row throws on read: loud, but still an outage for that column. The version prefix is one byte, so a ring caps at 256 live versions, which is ample for annual or quarterly rotation and a real ceiling for anything faster.</li><li><strong>Per-property wiring, not a global switch.</strong> Encryption is one HasConversion call at a time in each entity configuration. A column that should be encrypted but is never wired stays silently plaintext, so the control is only as good as the audit of your PII inventory.</li><li><strong>Storage and CPU overhead.</strong> Every value grows by 29 bytes (a 1-byte key version, a 12-byte nonce, and a 16-byte tag) before Base64 inflation, and every read and write performs an AES-GCM operation.</li><li><strong>Latent until adopted.</strong> Proven by EncryptedStringConverterTests, not by production. The round-trip works; the decision to encrypt a specific column is still yours to make and to audit.</li></ul><p>None of these are reasons to skip encrypting genuinely sensitive columns. They are the reasons to encrypt deliberately: the columns you read by key, with a key lifecycle you have designed, tracked against a PII inventory you actually keep.</p><h3>Apply this even without MMCA</h3><p>The pattern ports to any EF Core codebase, and to most ORMs with a value-conversion or type-handler hook:</p><ol><li>Use an <strong>EF Core </strong><strong>ValueConverter&lt;string, string&gt;</strong> (or your ORM&#39;s equivalent) so encryption lives on the property mapping and the rest of the code keeps a plain string.</li><li>Choose an <strong>authenticated cipher (AES-GCM)</strong>, not a bare block mode, so integrity comes with confidentiality and tampering fails loudly instead of decrypting to garbage.</li><li><strong>Store the nonce with the ciphertext</strong> in a self-describing envelope ([key version][nonce][ciphertext][tag], Base64 into a string column) and draw a <strong>fresh random nonce per write</strong> so the same plaintext never repeats its ciphertext.</li><li><strong>Put a key version in the envelope on day one, and authenticate it.</strong> Pass the version as associated data so the tag covers it: a self-describing envelope whose description can be rewritten is an invitation to rewrite it. One byte buys you both a rotation path and tamper detection on the version itself.</li><li><strong>Keep the keys out of the code.</strong> Take them from a vault, managed identity, user-secrets, or an environment variable, and design the rotation drill (add the new version as current, deploy, re-encrypt in the background, retire the old version) before you encrypt the first column, because the format stops being free to change the moment a row uses it.</li><li><strong>Encrypt by threat model.</strong> Column-level crypto is a second boundary above TDE for the few columns a database reader should never see in the clear, and you trade away queryability to get it.</li></ol><p>The takeaway: <strong>TDE protects the file from whoever steals the disk; field-level encryption protects the column from whoever can run a query. Pick the columns you read by key, encrypt them with an authenticated cipher, a fresh nonce per write, and an authenticated key version in the envelope, keep the keys in a vault, and know going in that you are trading queryability for a trust boundary the database itself cannot cross.</strong></p><p><strong>What we covered:</strong> why TDE leaves a plaintext gap for any principal who can query the database, how EncryptedStringConverter closes it per column with AES-256-GCM authenticated encryption, its self-describing [key version][nonce][ciphertext][tag] envelope and non-deterministic ciphertext, the key ring that makes a zero-downtime rotation possible and the authenticated version byte that keeps it honest, the 32-byte key guard and vault-only key handling, the honest &quot;shipped, tested, not yet adopted&quot; posture from ADR-037, and the trade of queryability for a trust boundary the database cannot cross.</p><p><strong>Next in the series:</strong> Article 47, “Security Headers and CSP for Blazor: One Middleware, Every Host,” where the data-protection story moves from the column to the response.</p><p><em>MMCA.Common is Apache-2.0 licensed and open source. Star the repo, read the persistence chapter of the onboarding guide, or </em><em>dotnet add package MMCA.Common.Infrastructure and try it.</em></p><p><strong>About the author</strong></p><p>Ivan Ball-llovera is a senior software architect working in enterprise .NET. This series is built on <strong>MMCA.Common</strong>, the open-source framework behind it: fifteen NuGet packages for a modular monolith you can extract services out of later, scored in public against a 34-category architecture rubric, gaps included.</p><ul><li>The framework: <a href="https://github.com/ivanball/MMCA.Common">https://github.com/ivanball/MMCA.Common</a></li><li>Start a new app: dotnet new install MMCA.Templates then dotnet new mmca-app -n Your.App</li><li>Add it to an existing solution: dotnet add package MMCA.Common.API</li><li>The full series index and the architecture docs: <a href="https://ivanball.github.io/writing.html">https://ivanball.github.io/writing.html</a></li></ul><p>Follow along here for one pattern a week.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06ece340ea25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Feature Flags in the CQRS Pipeline: Gate Commands, Not Code]]></title>
            <link>https://medium.com/@ivanball76/feature-flags-in-the-cqrs-pipeline-gate-commands-not-code-e58b9ea8d098?source=rss-b79b63d05524------2</link>
            <guid isPermaLink="false">https://medium.com/p/e58b9ea8d098</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[feature-flags]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[cqrs]]></category>
            <dc:creator><![CDATA[Ivan Ball-llovera]]></dc:creator>
            <pubDate>Fri, 14 Aug 2026 12:11:19 GMT</pubDate>
            <atom:updated>2026-08-22T01:47:30.155Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Decoupling release from deploy means shipping code dark and flipping a switch. Here is how MMCA.Common gates commands and queries with feature flags at the outermost decorator, so a handler never checks a flag itself, and a disabled feature is rejected before any work runs.</em></p><p><em>Part of the MMCA.Common series · Article 45 of 50. One pattern at a time.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*et6EuHiq69yFoX9HSDmh2A.png" /></figure><p>Product wants to ship a feature dark: merge it now, turn it on later, and be able to kill it in seconds if it misbehaves in production. The mechanism is a feature flag, and the first instinct is almost always the wrong one.</p><p>The wrong one looks like this. You inject an IFeatureManager into the handler that does the work, and at the top of the method you write if (!await featureManager.IsEnabledAsync(&quot;X&quot;)) return .... It works. Then the same feature turns out to be reachable from a second endpoint, so you copy the check there too. Then a third handler needs a different flag, and now every use case in the module opens with a few lines of flag plumbing that has nothing to do with the business logic underneath it. The flag check has become a cross-cutting concern that you are pasting by hand into every place it applies.</p><p>That is exactly the kind of concern MMCA.Common refuses to let leak into handlers. Logging, caching, validation, and transactions already live in the decorator pipeline, written once and applied to every handler. Feature gating is the same shape of problem, so it gets the same treatment: a decorator at the outermost slot, and a one-property marker interface that a use case implements to opt in.</p><h3>Why it matters</h3><p>A feature flag is a branch in production behavior, and branches that are copy-pasted drift. If the gate lives inside the handler, then whether a feature is on is decided in as many places as the feature is reachable from, and nothing forces those places to agree. Miss one and you have a half-protected feature: disabled on the button the UI shows, still live on the endpoint a script can call.</p><p>There is also a cost argument. If the flag check is the first line of the handler, then everything the request touches on the way to that handler (a log scope opened, a cache looked at, a validator resolved, a database transaction begun) has already happened by the time you discover the feature is off. A kill switch you flip during an incident should reject the request with as little machinery spun up as possible, not do most of the work and then decline at the last moment.</p><p>And the deepest reason: a handler that checks its own flag knows about feature management. That is one more ambient dependency in code whose entire job is supposed to be a single use case. The pipeline exists so that the handler can stay ignorant of logging, caching, transactions, and flags alike, and be the same code whether it runs in a monolith or an extracted service.</p><h3>The MMCA answer: an outermost decorator plus a marker interface</h3><p>The whole mechanism is two small types plus a registration.</p><p>The opt-in signal is IFeatureGated, an interface with exactly one member, string FeatureName { get; }. A command or query implements it to declare &quot;I am gated behind this flag.&quot; The name has to match a key in the &quot;FeatureManagement&quot; configuration section.</p><p>The enforcement is a pair of decorators, one per handler side. FeatureGateCommandDecorator&lt;TCommand, TResult&gt; wraps ICommandHandler, and its query twin FeatureGateQueryDecorator&lt;TQuery, TResult&gt; wraps IQueryHandler. Both do the identical three-step thing in HandleAsync:</p><ol><li>If the command or query is not IFeatureGated, call the inner handler and return. A use case that does not opt in pays nothing.</li><li>If it is gated, check featureManager.IsEnabledAsync(featureGated.FeatureName). Enabled means delegate to the inner handler as normal.</li><li>If the flag is off, short-circuit: build and return a failure result carrying Error.NotFoundError(&quot;Feature.Disabled&quot;, ...), without ever invoking the handler.</li></ol><p>Manufacturing that typed failure is the one subtle piece. TResult is unconstrained (it is Result for some handlers and Result&lt;T&gt; for others), so the decorator cannot just new up a failure. It holds a cached delegate, CreateFailure, built once per closed generic type via ResultFailureFactory.Build, which turns an error list into the right TResult failure with no per-call reflection.</p><p>The last, load-bearing detail is where the decorator sits. In AddApplicationDecorators the feature gate is registered last on both sides. Because the pipeline applies decorators in reverse registration order (ADR-014), last-registered is outermost, so the feature gate is the first decorator every request meets. A command runs feature gate, authorization, logging, caching, validation, timeout, transaction, handler; a query runs feature gate, authorization, logging, caching, timeout, handler. A disabled feature is rejected with zero downstream work: no permission check, no log scope, no cache touch, no validator, no timeout budget, no BEGIN TRANSACTION.</p><p>Here is the shape, drawn from the real decorator and two real gated use cases:</p><pre>// The opt-in marker (IFeatureGated.cs)<br>public interface IFeatureGated<br>{<br>    string FeatureName { get; }  // must match a &quot;FeatureManagement&quot; config key<br>}<br><br>// A real gated command (VerifyPaymentCommand.cs, Store Sales)<br>public sealed record VerifyPaymentCommand(OrderIdentifierType OrderId)<br>    : ICacheInvalidating, IFeatureGated<br>{<br>    public string CachePrefix =&gt; $&quot;{typeof(Order).FullName}:&quot;;<br>    public string FeatureName =&gt; SalesFeatures.PaymentVerification;  // &quot;Sales.PaymentVerification&quot;<br>}<br><br>// The outermost decorator, the whole enforcement (FeatureGateCommandDecorator.cs)<br>public async Task&lt;TResult&gt; HandleAsync(TCommand command, CancellationToken cancellationToken = default)<br>{<br>    if (command is not IFeatureGated featureGated)<br>        return await inner.HandleAsync(command, cancellationToken).ConfigureAwait(false);<br>    <br>    if (await featureManager.IsEnabledAsync(featureGated.FeatureName).ConfigureAwait(false))<br>        return await inner.HandleAsync(command, cancellationToken).ConfigureAwait(false);<br>    <br>    var createFailure = CreateFailure();<br>    return createFailure([Error.NotFoundError(<br>        &quot;Feature.Disabled&quot;,<br>        $&quot;Feature &#39;{featureGated.FeatureName}&#39; is not currently available.&quot;)]);<br>}</pre><p>Two things make this more than a toy. First, the provider is real: AddAPI registers services.AddFeatureManagement().WithTargeting&lt;CurrentUserTargetingContextAccessor&gt;() plus the disabled-response handler, which brings the built-in Percentage, TimeWindow, and Targeting filters with a per-user audience already supplied, so &quot;roll this out to 10 percent&quot; is a config change, not a code change. Second, flag names are module constants, not magic strings scattered through handlers: SalesFeatures.PaymentVerification = &quot;Sales.PaymentVerification&quot;, ConferenceFeatures.SessionizeIntegration = &quot;Conference.SessionizeIntegration&quot;, NotificationFeatures.PushNotifications = &quot;Notification.PushNotifications&quot;. ADC&#39;s RefreshFromSessionizeCommand gates the Sessionize sync this way; Store&#39;s VerifyPaymentCommand gates the direct Stripe verification path.</p><h3>The second surface, and why disabled means 404</h3><p>A feature can be reachable from the CQRS pipeline, but it can also be reachable straight from an MVC action that never dispatches a command. So the same flag name is enforced at a second, independent surface at the HTTP edge (ADR-031). There you put [FeatureGate(&quot;X&quot;)] (from Microsoft.FeatureManagement.Mvc) on the controller or action; the framework&#39;s own push-device controller carries [FeatureGate(NotificationFeatures.PushNotifications)] on the class, not app-specific code in ADC. When the flag is off, DisabledFeatureHandler writes an RFC 9457 ProblemDetails response with status 404 Not Found and the title &quot;Feature not available&quot;.</p><p>Both surfaces agree on one convention that is worth stating plainly: a disabled feature returns not-found, never 403 Forbidden. The pipeline decorator short-circuits with ErrorType.NotFound; the edge handler returns 404. A disabled feature is therefore indistinguishable from a nonexistent one. That is deliberate: 404 hides the feature&#39;s existence rather than advertising a capability the caller is not allowed to use. Turning a flag off makes the feature vanish, not merely refuse.</p><h3>Trade-offs, honestly</h3><ul><li><strong>The two surfaces must be kept in agreement by hand.</strong> Gating the controller but not the command (or the reverse) leaves a half-protected feature reachable through the entry you missed. ADR-031 is explicit that no fitness rule asserts both are wired, so coherence is a convention and an audit concern, not something the build enforces.</li><li><strong>A missing config key resolves to disabled.</strong> IsEnabledAsync returns false for a name that is not in the &quot;FeatureManagement&quot; section. That is the right default for a kill switch (fail safe), but it also means forgetting to add the key in a given service silently hides a feature you meant to ship. Per service, the flag has to be present.</li><li><strong>Flag debt is real and unmanaged.</strong> Every flag is a branch that has to be removed once the feature is permanent. The framework provides no expiry or staleness check. A flag left in is dead weight and a latent second code path.</li><li><strong>Rollout bucketing is per user, but only as stable as the claim behind it.</strong> Percentage and Targeting filters evaluate locally, so consistent assignment needs a targeting context, and the framework supplies one: CurrentUserTargetingContextAccessor implements ITargetingContextAccessor and is wired by AddFeatureManagement().WithTargeting&lt;CurrentUserTargetingContextAccessor&gt;(), so every host that goes through AddAPI buckets a given user the same way on every replica (ADR-031). The residual caveat is that the stickiness is only as stable as the user_id claim, which falls back to Identity.Name, and a filter configured with no targeting audience gains no stickiness from the accessor at all.</li><li><strong>It is opt-in and adopted narrowly today.</strong> The mechanism is wired, unit-tested, and used by a handful of real gated use cases (the Sessionize sync, the Stripe verification path, the push-notification surface). It is a capability the pipeline offers uniformly, not something every handler uses.</li></ul><p>None of these are reasons to check flags inside handlers instead. They are the reasons to keep flag names in one constant per module and to treat every flag as something you will later delete.</p><h3>Apply this even without MMCA</h3><p>The pattern ports to any pipeline that already wraps its handlers (MediatR behaviors, an interceptor, your own decorator chain):</p><ol><li>Make feature gating <strong>a marker interface with one property</strong>, not a base-class method or an attribute the handler reads. The use case declares the flag name; it does not perform the check.</li><li>Put the gate <strong>at the outermost position</strong> so a disabled feature is rejected before logging, caching, validation, or a transaction. The cheapest request is the one you decline first.</li><li><strong>Manufacture a typed failure</strong>, do not throw, when the flag is off. In a Result-based codebase that is a not-found value flowing back through the pipeline; the caller translates it to a 404.</li><li><strong>Return not-found, never forbidden</strong>, for a disabled feature, so turning a flag off hides the feature rather than announcing a capability behind a locked door.</li><li><strong>Name flags as constants next to the module</strong> they belong to, matched to config keys, so a flag flips at config-and-restart and there are no magic strings in handlers.</li></ol><p>The takeaway: <strong>a feature flag is a cross-cutting concern, so put it where the other cross-cutting concerns live. Gate the pipeline at its outermost edge with a one-property marker interface, and your handlers stay flag-free, your kill switch rejects with zero wasted work, and a disabled feature simply is not there.</strong></p><p><strong>What we covered:</strong> why a flag check inside a handler is a copy-paste cross-cutting concern, how IFeatureGated plus the outermost FeatureGateCommandDecorator / FeatureGateQueryDecorator gate commands and queries with zero handler involvement, how the same flag name is enforced at the HTTP edge by [FeatureGate] and DisabledFeatureHandler, and why a disabled feature returns 404 rather than 403.</p><p><strong>Next in the series:</strong> Article 46, “Field-Level Encryption in EF Core: AES-GCM for PII Columns,” encrypting sensitive values at the property boundary so they are ciphertext at rest and plaintext only in the domain.</p><p><em>MMCA.Common is Apache-2.0 licensed and open source. Star the repo, read the 2-minute ADR behind this pattern (ADR-031), or </em><em>dotnet add package MMCA.Common.Application and gate your first command.</em></p><p><strong>About the author</strong></p><p>Ivan Ball-llovera is a senior software architect working in enterprise .NET. This series is built on <strong>MMCA.Common</strong>, the open-source framework behind it: fifteen NuGet packages for a modular monolith you can extract services out of later, scored in public against a 34-category architecture rubric, gaps included.</p><ul><li>The framework: <a href="https://github.com/ivanball/MMCA.Common">https://github.com/ivanball/MMCA.Common</a></li><li>Start a new app: dotnet new install MMCA.Templates then dotnet new mmca-app -n Your.App</li><li>Add it to an existing solution: dotnet add package MMCA.Common.API</li><li>The full series index and the architecture docs: <a href="https://ivanball.github.io/writing.html">https://ivanball.github.io/writing.html</a></li></ul><p>Follow along here for one pattern a week.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e58b9ea8d098" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HTTP API versioning, proven not just claimed]]></title>
            <link>https://medium.com/@ivanball76/http-api-versioning-proven-not-just-claimed-2b0381e4b533?source=rss-b79b63d05524------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b0381e4b533</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Ivan Ball-llovera]]></dc:creator>
            <pubDate>Thu, 13 Aug 2026 11:53:04 GMT</pubDate>
            <atom:updated>2026-08-22T01:46:50.854Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Most APIs “support versioning” by shipping v1.0 and never a second version. Here is a header-based setup that introduces versioning without breaking a single caller, and a fitness contract that proves two live versions coexist instead of asserting they could.</em></p><p><em>Part of the MMCA.Common series · Article 44 of 50. One pattern at a time.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O1r0laoVNJwO1m4z7La_gg.png" /></figure><p>Here is a claim that sounds responsible and is almost always untestable:</p><blockquote><em>“Our API supports versioning.”</em></blockquote><p>Open the code and you find Asp.Versioning wired up, a default of 1.0, and exactly one version ever shipped. The machinery is configured. Whether it actually works past a single version has never been exercised, because there is no second version to exercise it against. The first time someone needs to evolve a response shape, they discover the reader was set to a URL segment nobody&#39;s client builder expected, or that the default-version behavior quietly breaks every caller that never sent a version, or that deprecation was never reported anywhere a client could see it.</p><p>A versioning story you cannot demonstrate is a versioning story that erodes silently. It reads as done in a design doc and fails in the first real evolution.</p><p>There is a second trap next to the first. If you reach for versioning by forking the route (/v1/... and /v2/...), every URL, every gateway route map, every client URL builder, and every OpenAPI path now has a version baked into it. The version is not a property of the request. It is a property of the string, copied everywhere, and it forks the whole surface the moment you add a second one.</p><h3>Why it matters</h3><p>HTTP APIs need a versioning axis of their own: one the caller selects per request, that the service can advertise, and that it can deprecate over time. In a framework whose thesis is “monolith now, services later, no rewrite,” that axis carries extra weight. A module served in-process today becomes a service behind a YARP gateway tomorrow, and as it evolves a response shape has to be able to change without breaking a client still coded against the old shape.</p><p>This is a different concern from how asynchronous integration events evolve on the wire. That axis is resolved by consumers from a SchemaVersion carried inside the serialized event, and it is never chosen by a caller. The HTTP axis is the opposite: request-time, client-selected, and reported back in response headers. Conflating the two is how teams end up with one mechanism doing neither job well.</p><p>And without a shared decision, every host wires it differently: URL segment here, query string there, a different default-version behavior in each service, inconsistent deprecation reporting. The reader, the default, and the reporting choices drift apart between services that are supposed to look like one API behind a gateway.</p><h3>The MMCA answer: one registration, one exemplar, one fitness contract</h3><p>MMCA.Common standardizes a single header-based setup in MMCA.Common.API, adopts it in every service host through one call, and keeps it exercised by a shared contract test that proves two live versions coexist.</p><p><strong>One registration wires the whole policy.</strong> AddCommonApiVersioning is the entire decision, in one place: the reader, the default behavior, the reporting, and the one guard that keeps document generation from tripping over any of it.</p><pre>public IServiceCollection AddCommonApiVersioning()<br>{<br>    // DefaultApiVersion is deliberately not set: 1.0 is already the library default, and the<br>    // API explorer inherits it (restating either it or the assume-default flag trips AV0011/AV0024).<br>    services.AddApiVersioning(options =&gt;<br>    {<br>        options.AssumeDefaultVersionWhenUnspecified = true;      // no header -&gt; 1.0<br>        options.ReportApiVersions = true;                        // advertise supported/deprecated<br>        options.ApiVersionReader = new HeaderApiVersionReader(&quot;api-version&quot;);<br>    }).AddMvc()<br>    .AddApiExplorer(options =&gt;<br>    {<br>        options.GroupNameFormat = &quot;&#39;v&#39;VVV&quot;;                      // feeds the versioned OpenAPI group<br>        options.SubstituteApiVersionInUrl = true;<br>    });<br>    <br>    services.AddApiParameterDescriptorBackfill();                // guards OpenAPI generation<br>    <br>    return services;<br>}</pre><p>Three of those lines carry the design. The reader is a HeaderApiVersionReader(&quot;api-version&quot;), so routes and query strings stay version-free: a caller opts into a newer shape by adding one header, not by rewriting the URL. AssumeDefaultVersionWhenUnspecified means a client that never sends the header keeps getting 1.0, so introducing versioning was not a breaking change for any existing caller. And ReportApiVersions means every response carries the supported and deprecated version lists in its headers, so a client can see which versions a service still honors and which are on the way out without reading a changelog.</p><p>Two more details in that block carry less design and more hard-won experience, and the first of them is a line that is not there. 1.0 is the default because the Asp.Versioning library already defaults to it, so the registration says nothing at all: setting DefaultApiVersion explicitly, in either the versioning options or the explorer options that inherit them, trips the library&#39;s own analyzers (AV0011/AV0024), and the comment standing in its place exists so the next reader does not &quot;fix&quot; the omission. And AddApiParameterDescriptorBackfill installs a parameter-descriptor guard, added in v1.146.0 after a real failure: MVC leaves ApiParameterDescription.ParameterDescriptor null for a route token with no matching action parameter, and Asp.Versioning.OpenApi dereferences it without a null check, so a host that routes api/v{version:apiVersion}/... returned a 500 from GET /openapi/{documentName}.json. The guard fills a placeholder only where one is missing and never replaces a descriptor MVC supplied. Because this framework&#39;s reader is the header, no current host was hit either way, which is exactly why that failure could ship unnoticed.</p><p><strong>A shipped exemplar proves two versions coexist.</strong> This is the part most “we support versioning” stories skip. ServiceInfoControllerBase serves the same /ServiceInfo route under two versions selected by the header. GetV1 is mapped to 1.0 ([MapToApiVersion(&quot;1.0&quot;)]) and returns the minimal ServiceInfoResponse shape. GetV2 is mapped to 2.0 ([MapToApiVersion(&quot;2.0&quot;)]) and returns the evolved ServiceInfoV2Response, a superset that also advertises the supported and deprecated version lists in its body. Same route, two shapes, chosen by one header. The base is read-only: both actions are [HttpGet] and it declares no write verb. Anonymity is not carried by the base: each sealed subclass grants it with [AllowAnonymous].</p><p><strong>The class-level version attributes live on the per-service subclass.</strong> Class-level routing and versioning attributes are not reliably inherited, so each host supplies a sealed subclass that carries them. ADC’s ServiceInfoController declares [ApiVersion(&quot;1.0&quot;, Deprecated = true)] and [ApiVersion(&quot;2.0&quot;)] and sets the service name to &quot;Conference&quot;; Store&#39;s mirror sets &quot;Catalog&quot;. The shared behavior lives in the base; the attributes do not, so each host repeats them on a one-line subclass. That 1.0 is declared deprecated on purpose, so the deprecation-reporting path is live rather than theoretical.</p><p><strong>A shared fitness contract keeps the machinery exercised.</strong> ServiceInfoVersioningContractTestsBase&lt;TFixture&gt; sends api-version: 1.0 and then 2.0 over the real host. It asserts the v1.0 response returns the minimal shape and carries an api-deprecated-versions header, and that the v2.0 response returns the evolved shape and carries an api-supported-versions header. Because the controller ships in MMCA.Common.API, the whole test body is identical across repos: each consumer&#39;s subclass supplies only its fixture. It is one of the runtime conformance bases the shared testing package ships for a host to subclass, and today it is subclassed on one host per repo: ADC&#39;s Conference service and Store&#39;s Catalog service. This is the rubric §9 fitness check, and the same invariant-over-discipline posture the framework prefers: without a second working version, everything above would be asserted rather than proven.</p><p><strong>Every REST host adopts it the same way.</strong> The extracted services call AddCommonApiVersioning in their startup: ADC&#39;s Conference, Identity, Engagement, and Notification hosts, Store&#39;s Catalog, Sales, and Identity hosts, and the monolith reference host. One call per host, and the reader, default, and reporting choices cannot drift apart between services. The discovery exemplar is narrower than the registration: only ADC&#39;s Conference and Store&#39;s Catalog hosts ship a ServiceInfoController subclass today.</p><h3>Trade-offs, honestly</h3><p>The decision record is refreshingly candid about what is real today versus what the shape leaves room for. Four things are worth naming, and none of them is a bug.</p><ul><li><strong>The class-level version attributes are not inherited.</strong> Each per-service subclass must repeat the [ApiVersion(...)] and routing attributes. It is one line of duplication per host, and it is the same inheritance caveat other controller-convention attributes already carry. The shared behavior lives in the base; the attributes are the deliberate exception.</li><li><strong>Adoption is per host.</strong> A new REST host that forgets AddCommonApiVersioning gets no versioning and no reported versions, and the shared fitness contract only guards a host once its subclass is added. This is the same audit-the-inventory caveat that every opt-in framework registration carries.</li><li><strong>Only the discovery endpoint has evolved to 2.0.</strong> This is the honest one. Application controllers beyond ServiceInfo declare only [ApiVersion(&quot;1.0&quot;)] today. The second version exists on the /ServiceInfo discovery endpoint to keep the versioning path honest, not because any business resource has yet needed to evolve its shape. The point of the exemplar is that when a real resource does need a 2.0, the machinery it plugs into has been proven to work, not merely configured.</li><li><strong>Header versioning is less discoverable than a URL segment, and the OpenAPI documents are dev/CI only.</strong> A version chosen by header does not show up in a copied URL or a browser address bar, so the version in play is only visible to a caller that reads request and response headers. The generated contract does follow the versioning axis: the mapping applies a document-per-version convention, so the route resolves one document per discovered API version, named by the explorer’s GroupNameFormat (v1.0 is the v1 document). But the whole endpoint is a no-op in Production, and the only document any host&#39;s contract test pins is /openapi/v1.json, so the machine-readable surface is a development and CI artifact, not something a client can browse in production and not a place the 2.0 shape is currently asserted.</li></ul><p>The trade the framework makes is clear: stable, version-free URLs and a non-breaking rollout, paid for with a version that lives in headers rather than the path, and a proof-of-life second version on the discovery endpoint rather than a business resource that has not needed one yet.</p><h3>Apply this even without MMCA</h3><p>The pattern ports to any HTTP stack that will have to evolve a response shape without a flag day:</p><ol><li><strong>Pick one version reader and put it behind one registration.</strong> Header, query, or URL segment: pick one, wire it once, and adopt it from a single call so every host is versioned identically. A header reader keeps routes and URL builders version-free.</li><li><strong>Assume the default when the caller sends nothing.</strong> AssumeDefaultVersionWhenUnspecified (or its equivalent) is what makes introducing versioning a non-event for existing callers. Without it, the day you turn versioning on is the day every un-versioned client breaks.</li><li><strong>Report supported and deprecated versions on every response.</strong> Deprecation a client cannot see from headers is deprecation nobody acts on. Turn on version reporting and deprecate a real version so the reporting path is live, not theoretical.</li><li><strong>Ship a real second version and put it under a test.</strong> A single-version API cannot demonstrate that its versioning works. A tiny discovery endpoint served under both a deprecated 1.0 and a 2.0, with an integration test that sends each header and asserts the shape and the reported-version headers, is the difference between &quot;we support versioning&quot; and versioning you can prove.</li><li><strong>Keep the HTTP axis separate from your event-schema axis.</strong> Request-time and client-selected is a different problem from consumer-resolved event evolution. One mechanism per axis.</li></ol><p><strong>What we covered:</strong> why “we support versioning” is untestable when only 1.0 ever ships, how AddCommonApiVersioning wires a header-based policy (default 1.0 inherited from the library, assume-default-when-unspecified, report-versions, api-version reader, plus the parameter-descriptor backfill that keeps OpenAPI generation from failing) in one call, how ServiceInfoControllerBase ships a real deprecated 1.0 alongside a 2.0 so ServiceInfoVersioningContractTestsBase can prove two versions coexist rather than assert it, and the honest current-reality caveats (only the discovery endpoint has a 2.0, adoption is per host, the attributes are repeated per subclass, and the OpenAPI documents are dev/CI only).</p><p><strong>Next in the series:</strong> Article 45, “Feature Flags in the CQRS Pipeline: Gate Commands, Not Code,” on gating a command in the pipeline instead of branching the code that runs it.</p><p><em>MMCA.Common is open source. Star the repo, read the 2-minute ADR-046 behind this pattern, or </em><em>dotnet add package MMCA.Common.API and try the header.</em></p><ul><li>This pattern’s decision record: <a href="https://ivanball.github.io/docs/adr/046-http-api-versioning.html">https://ivanball.github.io/docs/adr/046-http-api-versioning.html</a></li><li>The full 34-category scorecard, §9 included, lives in <a href="https://ivanball.github.io/docs/governance/common-ArchitectureScorecard.html">https://ivanball.github.io/docs/governance/common-ArchitectureScorecard.html</a>.</li></ul><p><strong>About the author</strong></p><p>Ivan Ball-llovera is a senior software architect working in enterprise .NET. This series is built on <strong>MMCA.Common</strong>, the open-source framework behind it: fifteen NuGet packages for a modular monolith you can extract services out of later, scored in public against a 34-category architecture rubric, gaps included.</p><ul><li>The framework: <a href="https://github.com/ivanball/MMCA.Common">https://github.com/ivanball/MMCA.Common</a></li><li>Start a new app: dotnet new install MMCA.Templates then dotnet new mmca-app -n Your.App</li><li>Add it to an existing solution: dotnet add package MMCA.Common.API</li><li>The full series index and the architecture docs: <a href="https://ivanball.github.io/writing.html">https://ivanball.github.io/writing.html</a></li></ul><p>Follow along here for one pattern a week.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b0381e4b533" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managed file storage: uploads you don’t have to trust]]></title>
            <link>https://medium.com/@ivanball76/managed-file-storage-uploads-you-dont-have-to-trust-8dfe8bf016bc?source=rss-b79b63d05524------2</link>
            <guid isPermaLink="false">https://medium.com/p/8dfe8bf016bc</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[cloud-security]]></category>
            <category><![CDATA[information-security]]></category>
            <dc:creator><![CDATA[Ivan Ball-llovera]]></dc:creator>
            <pubDate>Wed, 12 Aug 2026 14:02:48 GMT</pubDate>
            <atom:updated>2026-08-22T01:46:00.473Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A user uploads a profile photo. It is attacker-controlled bytes with GPS coordinates baked into the metadata and, if you are unlucky, a payload hiding behind a valid image header. Here is how MMCA.Common turns that upload into something you never have to trust.</em></p><p><em>Part of the MMCA.Common series · Article 43 of 50. One pattern at a time.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nBX6eQ02l0ed-wg0iZG0TA.png" /></figure><p>An avatar upload looks like the most harmless feature in the app. A user picks a photo, you store it, you render it back in an &lt;img&gt; tag. What could go wrong?</p><p>Three things, and all of them are quiet.</p><p>The file is attacker-controlled bytes. The client says it is a JPEG; the client says a lot of things. The EXIF block on a phone photo carries the exact GPS coordinates where it was taken, which is PII you did not ask for and are now storing and re-serving to anyone who loads the profile. And a “valid” image can be a polyglot: bytes that a browser renders as a picture and something else on your box treats as a script or an archive. You did not write a photo-sharing site. You wrote a place for a 256-pixel avatar, and you inherited an untrusted-file-handling problem you never signed up for.</p><p>The reflex is to reach for the Azure SDK, write the blob straight from the controller, and move on. That solves storage and nothing else: the metadata still ships, the bytes are still trusted, and the next consumer who needs blob storage copies your controller code and inherits the same holes.</p><h3>Why it matters</h3><p>An avatar is user-generated content on an anonymous-visible surface. That combination is exactly where file-upload bugs turn into incidents. The two that bite hardest are not exotic:</p><ul><li><strong>Metadata leakage.</strong> EXIF GPS coordinates are personal data. If you store the original file, you are storing where your users live and work, and re-serving it on every profile view. Under GDPR that is data you are now the controller of, silently.</li><li><strong>Content-type confusion.</strong> A Content-Type: image/jpeg header is a claim, not a fact. Accepting files by their declared type (or worse, their file extension) is how a &quot;JPEG&quot; that is really an HTML or SVG payload ends up served from your domain.</li></ul><p>The threat model for an uploaded image is the same shape as the threat model for a password hash: <strong>assume the input is hostile, and make the stored form incapable of hurting you.</strong> You are not trying to keep the file secret. You are trying to guarantee that what you persist is only pixels.</p><h3>The MMCA answer: a storage boundary, and a re-encode that keeps only pixels</h3><p>The framework had no blob abstraction before this. Anything file-shaped would have been written directly against the Azure SDK inside a module, unusable by the next consumer and untestable. ADR-045 adds two Application-layer ports, split the Clean-Architecture way, plus a dependency-free validator.</p><p>IFileStorageService is the storage boundary: UploadAsync takes a blob name, a stream, and a content type and returns the public Uri as a Result&lt;Uri&gt;; DeleteAsync is idempotent, and unknown blob names succeed rather than throw. Callers pass only a blob name scoped within a container; the implementation owns the container, and the container itself is provisioned by infrastructure, never created by the app.</p><p>The default implementation is deliberately inert. NullFileStorageService reports IsConfigured =&gt; false, fails every upload with a clear FileStorage.NotConfigured error, and lets deletes succeed (there is nothing to delete). A host that never wires storage does not crash mysteriously; its upload endpoints degrade with an honest message. A host that wants real storage calls AddAzureBlobFileStorage(configuration), which swaps in AzureBlobFileStorageService when the FileStorage section is complete.</p><p>That registration is defensive on purpose. An incomplete section is a no-op that leaves the Null default in place, so hosts register it unconditionally. Production sets ServiceUri and authenticates with DefaultAzureCredential; local development can use a ConnectionString against Azurite instead. One detail earns its comment in the source: an empty-string ServiceUri binds to a <em>relative</em> Uri, so the guard only accepts an absolute one.</p><p>But storage is the boring half. The security boundary is the image processor.</p><h3>The re-encode is the boundary</h3><p>IImageProcessor has one method, NormalizeToSquareJpegAsync, and its implementation ImageSharpImageProcessor does something that looks like image resizing and is actually a security control. It decodes the upload, bakes EXIF orientation into the pixels, center-crops to an exact square, strips every metadata profile, and re-encodes as a fresh JPEG:</p><pre>// ImageSharpImageProcessor.NormalizeToSquareJpegAsync (illustrative of shape)<br>using var image = await Image.LoadAsync(content, cancellationToken);<br><br>// AutoOrient BEFORE stripping metadata, or portrait phone photos come out rotated.<br>image.Mutate(ctx =&gt; ctx<br>    .AutoOrient()<br>    .Resize(new ResizeOptions { Size = new Size(size, size), Mode = ResizeMode.Crop }));<br><br>image.Metadata.ExifProfile = null;   // EXIF GPS coordinates are PII<br>image.Metadata.XmpProfile  = null;<br>image.Metadata.IptcProfile = null;<br><br>await image.SaveAsync(output, new JpegEncoder { Quality = 85 }, cancellationToken);</pre><p>The point is what does <em>not</em> survive. A full decode-then-re-encode means only the pixel grid crosses the boundary. EXIF GPS is gone because the metadata profiles are nulled. The polyglot payload is gone because the bytes that carried it were never re-emitted: the output is a new JPEG the encoder wrote from a decoded bitmap. One operation kills both classes of problem, and it does so by construction rather than by a blocklist you have to keep updating.</p><p>Undecodable content is a validation failure, not an exception. The processor catches UnknownImageFormatException and InvalidImageContentException and returns Error.Validation(&quot;Image.Undecodable&quot;, ...), so a garbage upload is a clean 400, not a 500. And because the processor has no external configuration, it is <em>always</em> registered as the real implementation, unlike storage: there is no Null image processor, because there is no safe way to skip the re-encode.</p><p>Ahead of the processor sits ImageContentSniffer, a static, dependency-free magic-byte check. IsAllowedImage accepts a payload only when its leading bytes match a JPEG, PNG, or WebP signature: the JPEG SOI prefix FF D8 FF, the 8-byte PNG signature, or a RIFF container declaring the WEBP form type. The accepted formats are decided by the actual bytes, never the client-declared content type or the file extension. It narrows the input; the re-encode neutralizes what gets through. Defense in depth, cheaply.</p><h3>The avatar contract</h3><p>Storage and re-encode are framework legs. The avatar itself is a contract (BR-116a) each consumer applies: one avatar per user; accept jpeg/png/webp up to 2 MB; the server re-encodes to a 256x256 JPEG via IImageProcessor, treating client-declared content types as advisory only. The blob name is {userId}-{random8}.jpg in the public-read avatars container, so the URL path reads avatars/{userId}-{random8}.jpg. Uploading a new avatar deletes the previous blob. The URL lives on the user entity as [Pii]: nulled on anonymize with the blob deleted, and included in the GDPR data export. That last part is why this article carries a §30 (data privacy) tie alongside the §8 (data access) and §11 (security) ones: the avatar is treated as personal data from the moment it lands to the moment it is erased.</p><h3>One capability, two client affordances</h3><p>On the client, the pick-a-photo gesture differs by host, and ADR-045 reuses the capability pattern from ADR-042. IMediaPickerService exposes native photo pick and camera capture with the permission flow encapsulated; a cancelled or denied picker returns null rather than throwing. Web heads keep the Null default (IsSupported =&gt; false) and render a plain InputFile instead. The comment in the port says it plainly: this is an affordance switch, not a degraded path. The same upload endpoint serves a phone&#39;s native picker and a browser&#39;s file input; only the gesture in front of it changes.</p><h3>Trade-offs, honestly</h3><p>ADR-045 owns its rough edges in its Consequences section, and they are real design choices rather than oversights.</p><ul><li><strong>The avatars container is public-read by design.</strong> Avatar URLs render in &lt;img&gt; tags on anonymous-visible surfaces without SAS-token plumbing on every request. The cost is that anyone with the URL can fetch the image. The random 8-character blob suffix prevents enumeration (you cannot walk from one avatar to the next), and the trade-off is accepted and documented in the consumer&#39;s privacy policy. This is a deliberate acceptance, not a gap.</li><li><strong>CDN and browser caches can serve a stale avatar briefly.</strong> A replaced or deleted avatar deletes its blob, but a cache may hold the old URL for a moment. Because the random suffix means a new upload never reuses the old URL, staleness is bounded by cache TTLs and self-heals; there is no cache-busting dance to get right.</li><li><strong>DefaultAzureCredential needs a data-plane role, not a secret.</strong> In production the storage account requires a Storage Blob Data Contributor grant for the app identity. That is a bicep-level infrastructure grant, which is the correct place for it, but it does mean the app will not authenticate until the role assignment exists. It is not a connection string you can paste in.</li><li><strong>ImageSharp joins the dependency set under the Six Labors Split License.</strong> It ships under Apache-2.0 terms for open-source and small-revenue use, which covers this project, and it is vuln-audited like every other dependency. The ADR is explicit that the license note must be revisited if the project’s revenue posture changes.</li></ul><p>Be precise about status: the framework legs are implemented and shipped in MMCA.Common, and MMCA.ADC’s Identity service has already wired them end to end. It calls AddAzureBlobFileStorage(builder.Configuration) at startup, its SetUserAvatarHandler, RemoveUserAvatarHandler, and DeleteUserHandler drive IFileStorageService, and its Profile page uploads through IMediaPickerService. Each consumer still provisions its own storage account and wires its own upload endpoints against these ports, so this is a capability the framework provides rather than one that is live in every downstream app by default: MMCA.Store has not adopted it yet.</p><h3>Apply this even without MMCA</h3><p>The pattern ports to any stack and any blob store. The rules are short:</p><ol><li><strong>Never trust the declared content type or the file extension.</strong> Sniff the leading magic bytes and accept only the formats you actually support.</li><li><strong>Re-encode every uploaded image; do not store the original.</strong> A full decode-then-re-encode is the single move that strips EXIF GPS (PII) and defeats polyglot payloads, because only pixels survive. Resize to the size you will actually serve while you are at it.</li><li><strong>Auto-orient before you strip metadata</strong>, or portrait phone photos come out sideways once the EXIF orientation flag is gone.</li><li><strong>Put storage behind a port with an inert default.</strong> An unconfigured implementation that fails uploads with a clear message beats a host that half-works or crashes at first use.</li><li><strong>Treat the stored URL as PII.</strong> If it points at a user’s face, it belongs in your erasure path and your data export, not just your database.</li><li><strong>Prefer managed identity over secrets</strong> for the store, and let infrastructure provision the container and its access level. The app should never create the bucket it writes to.</li></ol><p>The takeaway: <strong>an upload is hostile bytes until you have re-encoded it into something that can only be a picture.</strong> Storage is the easy half; the re-encode is the boundary that matters.</p><p><strong>What we covered:</strong> why an avatar upload is an untrusted-file problem in disguise (EXIF GPS as PII, content-type confusion, polyglot payloads); how IFileStorageService gives an upload-by-blob-name boundary with an inert NullFileStorageService default that fails clearly and an AddAzureBlobFileStorage swap to the real Azure implementation; how the real security boundary is the full re-encode in ImageSharpImageProcessor (decode, auto-orient, center-crop, strip all metadata, re-encode JPEG) fronted by ImageContentSniffer&#39;s magic-byte check; the avatar contract (256x256 JPEG, 2 MB, random-suffixed public-read blob, URL as [Pii]); and the honest trade-offs (public-read container, cache staleness, a data-plane role grant, the Six Labors Split License).</p><p><strong>Next in the series:</strong> HTTP API versioning, proven not just claimed, one header-based policy adopted by every service and kept honest by a shared fitness contract that runs two live versions.</p><p><em>MMCA.Common is open source. Star the repo, read the 2-minute ADR behind this pattern, or </em><em>dotnet add package MMCA.Common.Infrastructure and try it.</em></p><ul><li>📄 The decision record is <a href="https://ivanball.github.io/docs/adr/045-managed-file-storage-and-avatars.html">https://ivanball.github.io/docs/adr/045-managed-file-storage-and-avatars.html</a>.</li></ul><p><strong>About the author</strong></p><p>Ivan Ball-llovera is a senior software architect working in enterprise .NET. This series is built on <strong>MMCA.Common</strong>, the open-source framework behind it: fifteen NuGet packages for a modular monolith you can extract services out of later, scored in public against a 34-category architecture rubric, gaps included.</p><ul><li>The framework: <a href="https://github.com/ivanball/MMCA.Common">https://github.com/ivanball/MMCA.Common</a></li><li>Start a new app: dotnet new install MMCA.Templates then dotnet new mmca-app -n Your.App</li><li>Add it to an existing solution: dotnet add package MMCA.Common.API</li><li>The full series index and the architecture docs: <a href="https://ivanball.github.io/writing.html">https://ivanball.github.io/writing.html</a></li></ul><p>Follow along here for one pattern a week.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8dfe8bf016bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One Blazor UI, two hosts: a device-capability layer that stays resolvable everywhere]]></title>
            <link>https://medium.com/@ivanball76/one-blazor-ui-two-hosts-a-device-capability-layer-that-stays-resolvable-everywhere-b85444693161?source=rss-b79b63d05524------2</link>
            <guid isPermaLink="false">https://medium.com/p/b85444693161</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[blazor]]></category>
            <category><![CDATA[net-maui]]></category>
            <dc:creator><![CDATA[Ivan Ball-llovera]]></dc:creator>
            <pubDate>Tue, 11 Aug 2026 11:54:26 GMT</pubDate>
            <atom:updated>2026-08-22T01:45:15.484Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The same Blazor component set runs in a browser and inside a MAUI Blazor Hybrid app. But a share sheet, a fingerprint prompt, and a haptic tap only exist on the phone. Here is how one UI talks to native hardware through small per-capability contracts, and never has to ask “am I on mobile?”</em></p><p><em>Part of the MMCA.Common series · Article 42 of 50. One pattern at a time.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U5sC7Xgo_Wp0_u5QSLN_zg.png" /></figure><p>Ship the same Blazor components through a browser and through a .NET MAUI Blazor Hybrid app and you hit a wall the first time a component wants to do something physical. Open the native share sheet. Copy to the clipboard. Buzz on a bookmark. Prompt for Face ID. Read a GPS fix. Speak a screen-reader announcement. None of those APIs exist in a browser, and half of them have a partial browser equivalent (navigator.share, navigator.clipboard, navigator.onLine) that behaves nothing like the native one.</p><p>The naive fix is a platform check. A component asks “am I running on MAUI?” and branches. That question metastasizes: it shows up in the share button, the offline banner, the avatar picker, the login page, and every one of them now has two code paths, one of which never runs in the environment you are testing in. The component library stops being portable the moment it knows what a phone is.</p><p>MMCA.Common.UI is a single-target net10.0 Razor class library that has to compile into a Blazor WebAssembly bundle, so it <em>cannot</em> reference a MAUI type without breaking the web heads at compile time. That hard constraint is the whole reason the design is clean: the shared UI is structurally forbidden from knowing about the phone, so it has to talk to native hardware through an abstraction, and the implementation gets chosen somewhere the shared library never sees. This is ADR-042, the Device Capability Abstraction, and it is a whole shipped functional group (G26 in the onboarding guide, roughly a hundred types once you count contracts, native adapters, browser adapters, and fallbacks).</p><h3>The MMCA answer: one small contract per capability, chosen per host</h3><p>There is no god IDeviceCapabilities interface. That was a deliberate rejection: an aggregate device service forces every head to implement everything, and every new capability becomes a breaking change to a type everyone depends on. Instead the framework defines one small interface per capability, all living under Source/Presentation/MMCA.Common.UI/Services/Capabilities/, 18 capability interfaces in all.</p><p>Each contract is a few methods, shaped so failure is a value, not an exception:</p><ul><li>IShareService: ShareLinkAsync / ShareFileAsync, both returning Task&lt;bool&gt; so a caller learns &quot;no share UI was presented&quot; and falls back to copy-link rather than catching.</li><li>IHapticFeedbackService: Click, LongPress, Vibrate, plus an IsSupported flag; the doc comment is blunt that &quot;haptics are decoration, never behavior,&quot; so failures are swallowed.</li><li>IBiometricAuthenticator: IsAvailableAsync and AuthenticateAsync(reason), where cancellation, lockout, and error all return false so the caller falls back to the normal credential login, never to a weaker path.</li><li>IGeolocationService: GetCurrentOrLastKnownAsync returns a nullable GeoPoint, and denial or timeout yields null so a proximity hint is simply omitted.</li><li>ISpeechToTextService, IConnectivityStatusService, IExternalLinkService, IMediaPickerService, IPushRegistrationService, and the rest follow the same rule: a boolean or a nullable that means &quot;unavailable,&quot; never a throw a component has to guard.</li></ul><p>That last point is the load-bearing design choice. Because unavailability is a return value, a component written against the contract already handles the browser case for free. It calls ShareLinkAsync, gets false, and shows the copy-link path. It never asks what platform it is on.</p><h3>Three flavors of “unavailable,” all registered by default</h3><p>Small contracts only help if every one of them always resolves. A component that injects IShareService must get <em>something</em> on every head, or the browser build throws at runtime the first time someone taps share. So AddUIShared (the shared UI registration every host already calls) TryAdd-registers a safe default for every contract, in AddDeviceCapabilityDefaults. The TryAdd matters: it seeds a default only if nothing else claimed the slot, which keeps repeated host calls idempotent and lets a later registration win.</p><p>There are three flavors of default, and picking the right one per capability is the subtle part:</p><ol><li><strong>Null object.</strong> NullShareService returns Task.FromResult(false) from both methods. NullHapticFeedbackService and NullSpeechToTextService do the same and report IsSupported =&gt; false so components hide the affordance entirely. Each null default signals unavailability the way its own contract does: IBiometricAuthenticator has no IsSupported flag at all, so NullBiometricAuthenticator returns false from IsAvailableAsync instead.</li><li><strong>Constant stub.</strong> AlwaysOnlineConnectivityStatusService hard-codes IsOnline =&gt; true and never raises its event. That is not laziness: it is <em>correct</em> for Blazor Server, where a lost connection tears down the circuit itself, so the reconnect overlay already covers the offline case and a connectivity service would be redundant.</li><li><strong>Neutral local state.</strong> InMemoryDevicePreferences is registered scoped, not singleton, so the Blazor Server fallback holds per-circuit (per-user) state and never leaks one user&#39;s preferences into another&#39;s.</li></ol><p>The payoff: a head that knows nothing about capabilities keeps working. It gets share-returns-false, haptics-do-nothing, always-online, and every component degrades gracefully with zero host changes. That is the same inert-by-default posture the framework’s notification layer takes.</p><h3>Heads override after the defaults, last registration wins</h3><p>A default that is always inert would be useless on the platforms that <em>can</em> do the real thing. So heads override, and the mechanism is deliberately boring: plain Add registrations, called <em>after</em> AddUIShared, exploiting the rule that the last registration wins for single-service resolution.</p><p>The browser heads (Blazor Server and WebAssembly) call AddBrowserDeviceCapabilities, which swaps in eight browser adapters over one shared JS module, CapabilitiesJsModule. BrowserShareService calls navigator.share and returns whether a share UI actually appeared; on desktop Firefox or an insecure context it reports false, and the copy-link fallback kicks in exactly as on the null default. Every browser adapter is prerender-safe: a JS-unavailable call degrades to the null behavior instead of throwing during the static SSR pass.</p><p>The MAUI head calls UseMauiDeviceCapabilities, which wires the native Plugin.LocalNotification lifecycle, registers the notification-tap bridge, and calls AddMauiDeviceCapabilities to replace the defaults with MauiShareService, MauiClipboardService, MauiHapticFeedbackService, MauiGeolocationService, and the rest. Permission flows live <em>inside</em> each MAUI adapter (check, show rationale, request, degrade, never throw); components never see permission state.</p><p>Here is the whole composition, illustrative of the documented shape:</p><pre>// Every host, browser or native, calls the shared UI registration first.<br>// It TryAdd-seeds a safe default for every capability contract.<br>builder.Services.AddUIShared(builder.Configuration);   // -&gt; AddDeviceCapabilityDefaults() inside<br><br>// Blazor Server / WebAssembly host: override with browser adapters AFTER AddUIShared.<br>builder.Services.AddBrowserDeviceCapabilities();       // navigator.share, clipboard, aria-live, onLine<br><br>// MAUI Blazor Hybrid host (in MauiProgram): override with native adapters AFTER AddUIShared.<br>builder.UseMauiDeviceCapabilities();                   // native share sheet, haptics, geolocation, biometrics</pre><p>Three hosts, one shared component set, and the only difference is which one line ran after AddUIShared. A component that injects IShareService gets NullShareService on a forgetful host, BrowserShareService on the web, and MauiShareService on the phone, and it wrote none of that branching.</p><h3>The fifteenth package, and why it lives outside the solution</h3><p>The native adapters cannot ship in MMCA.Common.UI, because that package must stay WebAssembly-compatible. They ship in MMCA.Common.UI.Maui, the framework&#39;s fifteenth NuGet package and its one MAUI-target exception. It multi-targets net10.0-android/ios/maccatalyst/windows, references MMCA.Common.UI plus Microsoft.Maui.Controls and Plugin.LocalNotification, and stays <em>out</em> of MMCA.Common.slnx.</p><p>That exclusion is not cosmetic. MMCA.Common’s CI and release pipelines run on ubuntu, which cannot build MAUI target frameworks at all, and the fifteen packages release in lockstep. So the MAUI package is built and packed by dedicated windows CI jobs (build-maui, a required gate, and publish-maui, under the same tag and SBOM discipline), the same mechanism that keeps the UI gallery and E2E projects out of the fast ubuntu unit run. Its layer rule is &quot;UI plus Shared only,&quot; enforced at compile time; it is deliberately absent from the ubuntu runtime architecture map because its assemblies cannot even load there.</p><h3>Deep links: one funnel, no translation table</h3><p>The most elegant part is navigation. A notification tap, a home-screen app action, an app link, a scanned QR code: all four are native events that need to land on a Blazor route. They funnel through one singleton, IDeepLinkDispatcher, whose default DeepLinkDispatcher either raises RouteRequested live when a listener is attached, or buffers the most recent route (capacity one, guarded by a Lock) so a cold-start tap survives until the router renders. The DeepLinkListener.razor component in the shared layout drains that buffer after first render and navigates.</p><p>Why capacity one, and why a buffer at all? Because a tap can <em>launch</em> the app: native code publishes the route into the singleton before Blazor has rendered anything, so there is no listener yet. The single-entry buffer holds that route until first render, then the listener consumes it. Live taps, once the app is running, skip the buffer entirely.</p><p>The payoff of Blazor Hybrid is that web URLs and app routes are <em>identical</em>. All heads share one Blazor route table, so an incoming deep link is reduced to its path and query and published as-is. No translation table exists anywhere. This is also where ADR-043 (mobile deep links and app association) plugs in: incoming app-link and OAuth-callback URIs reuse this exact dispatcher, and each app’s UI.Web host serves the platform association files (assetlinks.json, apple-app-site-association) that tell the OS to open shared https URLs in the installed app. The OAuth-callback angle is its own story; here the point is only that ADR-043 adds native entry points and reuses this one funnel rather than building a second.</p><p>One more component earns its place: ExternalLink.razor. A raw target=&quot;_blank&quot; anchor silently dead-ends inside a BlazorWebView (WKWebView drops it), so shared components route external links through IExternalLinkService. It renders a real new-tab anchor on web heads, and where InterceptsLinks is true it intercepts the click into the system browser. OfflineBanner.razor renders only when IConnectivityStatusService reports offline. The components adapt; they never branch on platform.</p><h3>Trade-offs, honestly</h3><ul><li><strong>Null-object defaults can mask a missing registration.</strong> A MAUI head that forgets UseMauiDeviceCapabilities does not fail fast: it silently resolves the null defaults and loses haptics, share, and biometrics with no error. That is accepted for decoration-grade capabilities, but a feature that genuinely depends on a capability has to assert availability in its own UI and surface the gap (IsSupported where the contract exposes one, IsAvailableAsync for biometrics, the returned false for share), rather than trusting the registration happened.</li><li><strong>The pattern relies on registration order.</strong> The whole “last registration wins” mechanism only works if AddUIShared (and its TryAdd defaults) runs <em>before</em> the head&#39;s plain Add overrides. Both extension methods document the ordering, and the DI comment in AddMauiDeviceCapabilities restates it, but it is an ordering contract a host can still get wrong.</li><li><strong>A fifteenth package raises release surface.</strong> Two CI runners, ubuntu and windows, must both succeed for a whole release, because the MAUI package cannot build on ubuntu and the packages ship in lockstep. Accepted, and gated by the same tag and SBOM checks as the rest.</li><li><strong>Some contracts ship ahead of their native depth.</strong> The external-auth broker registers MauiExternalAuthBroker scoped but inert (IsAvailable == false) until the head configures its OAuth redirect scheme and platform callback; until then the shared login page stays on its anchor flow. Native push likewise stays wired-but-tokenless until real FCM/APNs credentials exist. Registered is not the same as fully live, and the article does not claim otherwise.</li></ul><p>None of these argue for a platform check back in the components. They argue for asserting IsSupported where a feature truly needs the hardware, and for keeping the registration order honest.</p><h3>Apply this even without MMCA</h3><p>The pattern ports to any UI that runs on more than one host:</p><ol><li>Define <strong>one small interface per capability</strong>, not an aggregate device service. Each new capability is then additive, not a breaking change to a type everyone depends on.</li><li>Shape each contract so <strong>unavailability is a return value</strong> (a bool or a nullable), never an exception. A component written against it handles the missing-hardware case without a single guard.</li><li><strong>Register a safe default for every contract</strong> at the composition root, with a conditional-add so it only seeds when nothing else claimed the slot. Then a host that knows nothing about capabilities still resolves everything and degrades gracefully.</li><li>Let <strong>hosts override after the defaults</strong>, relying on last-registration-wins, so the per-host adapter is one line and the shared code never sees it.</li><li>Keep the <strong>platform-specific package physically separate</strong> if its target frameworks cannot build where the rest of your CI runs, and gate it on its own runner under the same release tag.</li></ol><p>The takeaway: <strong>a portable UI is one that is structurally forbidden from knowing where it runs. Put each device capability behind a small contract, give every contract an inert default so it always resolves, and choose the real implementation per host at the composition root. The component asks for a capability; it never asks for a platform.</strong></p><p><strong>What we covered:</strong> why a platform check inside a shared component set is a portability leak, how ADR-042 replaces it with one small contract per capability under MMCA.Common.UI/Services/Capabilities/, how AddDeviceCapabilityDefaults TryAdd-seeds a null-object, constant-stub, or neutral-state default for every contract so it always resolves, how browser and MAUI heads override those defaults after AddUIShared with last-registration-wins, why the native adapters live in the fifteenth package MMCA.Common.UI.Maui built by a windows CI job, and how IDeepLinkDispatcher funnels every native navigation source onto the one shared Blazor route table.</p><p><strong>Next in the series:</strong> managed file storage, uploads you don’t have to trust, with untrusted-image re-encoding and a storage abstraction that swaps an Azure Blob backend for a safe Null fallback.</p><p><em>MMCA.Common is Apache-2.0 licensed and open source. Star the repo, read the device-capability chapter of the onboarding guide, or </em><em>dotnet add package MMCA.Common.UI.Maui and try it.</em></p><p><strong>About the author</strong></p><p>Ivan Ball-llovera is a senior software architect working in enterprise .NET. This series is built on <strong>MMCA.Common</strong>, the open-source framework behind it: fifteen NuGet packages for a modular monolith you can extract services out of later, scored in public against a 34-category architecture rubric, gaps included.</p><ul><li>The framework: <a href="https://github.com/ivanball/MMCA.Common">https://github.com/ivanball/MMCA.Common</a></li><li>Start a new app: dotnet new install MMCA.Templates then dotnet new mmca-app -n Your.App</li><li>Add it to an existing solution: dotnet add package MMCA.Common.API</li><li>The full series index and the architecture docs: <a href="https://ivanball.github.io/writing.html">https://ivanball.github.io/writing.html</a></li></ul><p>Follow along here for one pattern a week.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b85444693161" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Two real apps on one framework: a conference platform and a store]]></title>
            <link>https://medium.com/@ivanball76/two-real-apps-on-one-framework-a-conference-platform-and-a-store-12f694d2a361?source=rss-b79b63d05524------2</link>
            <guid isPermaLink="false">https://medium.com/p/12f694d2a361</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Ivan Ball-llovera]]></dc:creator>
            <pubDate>Mon, 10 Aug 2026 11:12:03 GMT</pubDate>
            <atom:updated>2026-08-22T01:44:35.064Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A framework’s README can claim anything. The real test is whether two unrelated applications, with different domains and different deployments, can both run on it without forking it. Here are the two that do.</em></p><p><em>Part of the MMCA.Common series · Article 41 of 50. One pattern at a time.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EHH0m3tWzfYaMewThSxMKw.png" /></figure><p>Every architecture framework looks clean in its own repository. The author controls the examples, the tests pass, the diagrams are tidy. The question a senior engineer actually asks is harder: <strong>does this survive contact with a real domain, real users, and a real deployment, or is it a toy that only its author can run?</strong></p><p>MMCA.Common answers that question with two applications built on it. They are not demos in a samples/ folder. They are separate repositories with their own business domains, their own databases, their own CI/CD, and their own production deployments to Azure. They consume the same fifteen NuGet packages, bumped in lockstep, and they prove different things the framework cannot prove about itself.</p><p>This article is the case study. It is also the honest part: the framework’s own scorecard flags that a few categories are demonstrated mainly in these consumer apps, not in the framework, and that is exactly why the apps matter.</p><h3>The two apps</h3><p><strong>MMCA.ADC</strong> is the Atlanta Developers Conference application. Its domain is events: conferences, sessions, speakers, rooms, categories, and the questions attendees ask. It carries four modules:</p><ul><li><strong>Identity</strong> (the User aggregate, JWT auth, plus social login via Google and GitHub),</li><li><strong>Conference</strong> (events, sessions, speakers, rooms, categories, questions and answers, fourteen REST controllers),</li><li><strong>Engagement</strong> (session bookmarks, event and session feedback, and the conference-day live layer: the LivePolls and SessionQuestions aggregates behind Happening Now, the session Live view, and the presenter UI),</li><li><strong>Notification</strong> (a thin SignalR module hosting the real-time notification hub).</li></ul><p>It is deployed to Azure Container Apps, one container image per deployable (the four services, the Gateway, and the web UI), and a merge to main is the deploy: the pipeline builds, tests, and rolls the release out. That is a harder claim than &quot;it builds&quot;: the framework is carrying a six-image production topology, not a sample project.</p><p><strong>MMCA.Store</strong> is an e-commerce application. Its domain is selling things: a product catalog, orders and carts, and the payment plumbing around them. It carries three modules:</p><ul><li><strong>Catalog</strong> (Category, Product, ProductVariant, hierarchical categories, variant pricing and SKUs),</li><li><strong>Sales</strong> (Order with OrderLine, ShoppingCart with ShoppingCartItem, InventoryItem, plus Stripe payment integration and a webhook),</li><li><strong>Identity</strong> (the User aggregate, Customer entity, JWT auth with refresh tokens).</li></ul><p>These are genuinely different bounded contexts. A Speaker linked to a User by email and a ProductVariant that fans out into a zero-stock InventoryItem are not the same shape of problem. That difference is the point. A framework that only fits one domain is a template; a framework that fits two unrelated domains is infrastructure.</p><h3>What they actually share</h3><p>Both apps sit at the <strong>same architecture stage</strong>, and that is deliberate. Each one has its modules extracted into separate service hosts (one process per module) behind a YARP reverse-proxy Gateway pinned to <a href="https://localhost:6001/">https://localhost:6001</a>. Services talk to each other synchronously over gRPC (typed clients defined in *.Contracts projects) and asynchronously over a broker using the outbox pattern. Tokens are signed with RS256 and validated through JWKS discovery, with no shared secret. The former single WebAPI host has been deleted in both.</p><p>None of that topology is hand-rolled per app. It comes from the framework:</p><ul><li><strong>The same fifteen packages.</strong> Both Directory.Packages.props files list MMCA.Common.Shared, .Domain, .Application, .Infrastructure, .API, .Grpc, .UI, .UI.Maui, .UI.Web, .Aspire, .Aspire.Hosting, .Testing, .Testing.E2E, .Testing.UI, and .Testing.Architecture, all pinned to one version.</li><li><strong>The same patterns.</strong> Result&lt;T&gt; for error flow, the CQRS command/query split with the same decorator order (commands run FeatureGate then Authorization then Logging then Caching then Validating then Timeout then Transactional then the handler; queries run FeatureGate then Authorization then Logging then Caching then Timeout then the handler), the AuditableAggregateRootEntity base with AddDomainEvent(), the transactional outbox captured in SaveChangesAsync(), and database-per-service routing by logical data source name. Both apps run one SQL database per service (ADC_Identity, ADC_Conference, and so on for ADC; Store_Catalog, Store_Sales, Store_Identity for Store), each with its own OutboxMessages table so no service races another for outbox rows.</li><li><strong>The same fitness rules, applied to their own code.</strong> This is the part most “reference architecture” repos skip. The architecture tests are not copy-pasted into each app. The rule bodies live once in the MMCA.Common.Testing.Architecture package as a rule library plus abstract test bases parameterized by an IArchitectureMap. Each app supplies <strong>its own map</strong> (one anchor type per package) and subclasses the same bases, so the layer, purity, and extraction rules are literally identical across MMCA.Common, MMCA.ADC, and MMCA.Store. The transport-leakage rule that forbids Domain and Application from touching MassTransit applies to all three the same way.</li></ul><p>The shared abstractions are exactly the swap points the framework promises. The same IMessageBus-backed event that fires in-process in a monolith fires over a broker once the module is its own service, and the consuming app does not change its handler code to make that switch.</p><h3>How a framework change ships</h3><p>The interesting operational property is not that the apps share code. It is <strong>how a change to the shared code reaches them.</strong> There is no phased rollout, no opt-in flag, no per-consumer compatibility shim.</p><p>The release is a lockstep sweep:</p><ol><li>Tag a new MMCA.Common version (the version comes from the git tag via MinVer). All fifteen packages publish at that same version.</li><li>In each consumer, bump every MMCA.Common.* entry in Directory.Packages.props to the new version in one pass. ADC and Store both keep all fifteen entries on the same number.</li><li>Build, run the fitness tests and the rest of the suite, deploy.</li></ol><p>The framework’s versioning policy doc (common-VERSIONING.md, canonical in the published docs library rather than in the framework repo) states the policy plainly: the fifteen packages are versioned and released together, versions come from MinVer git tags, and consumers are swept in one pass with no phased rollout. That is a real constraint, and it is the trade the framework makes on purpose: every consumer stays on one coherent version of the contract, so there is never a matrix of &quot;ADC is on 1.74 but Store is on 1.71 of three of the packages.&quot; The cost is that a breaking change has to be absorbed everywhere at once, which is why breaking changes go through a new event type plus an upcaster rather than a silent reshape (the event-schema-versioning ADR), and why the MassTransit v8 pin is guarded by a test in the framework rather than a comment.</p><h3>What each app proves that the framework cannot</h3><p>A framework can demonstrate a pattern. It cannot, by itself, demonstrate that the pattern survives a real domain and a real deployment. That is the division of labor between MMCA.Common and its consumers.</p><p><strong>ADC proves real bounded contexts and real eventing.</strong> Identity publishing UserRegistered so Conference can auto-link a speaker by email match is a genuine cross-context workflow, not a contrived one. Conference calling Engagement&#39;s bookmark-count service over gRPC, with a disabled-module stub standing in when Engagement is not co-hosted, is the extraction boundary working in a running system rather than in a unit test. And the deployment is the operability proof: four services plus a gateway and a web UI, each service owning its own database and its own OutboxMessages table, rolled to Azure Container Apps.</p><p><strong>Store proves a second, independent shape.</strong> Catalog publishing ProductVariantChanged so Sales auto-creates a zero-stock inventory record is a different integration than ADC&#39;s, with a different consistency story (publish-after-commit so the database-generated variant ID is known). Store also exercises surfaces ADC does not: Stripe payments with a webhook, and compensating saga handlers that restore inventory on order cancellation. Ownership authorization is not one of them: both apps configure the framework&#39;s OwnerOrAdminFilter, Store over customer-owned rows and ADC over its bookmark list endpoints, which is a nice illustration of the same extension point landing in two different vocabularies. Notably, Store and ADC <strong>deliberately diverge</strong> on one point: when a user registers, Store raises an in-process <em>domain</em> event (its Customer lives in the same Identity service) while ADC raises a cross-service <em>integration</em> event. Same idea, different mechanism, each correct for its topology. A framework that forced them to be identical would be wrong; the framework lets each app make the right local call.</p><h3>The honest note</h3><p>Here is the caveat the framework writes about itself. It is not a preamble or a methodology section: it is written into the category rows. Because the framework is a library and not a runnable app, a few categories can only be judged on the substrate it provides, not on realized behavior. The §4 Domain-Driven Design row holds its implementation score at 8 because strategic DDD is “still realized downstream (only Notifications lives here)”, and the §5 Vertical Slice Architecture row holds at 8 because “the enforced in-repo slicing surface is still the Notifications family”: the framework ships a second sliced family (the Users use cases), but its handlers are abstract bases that sit outside the concrete-class slice gate, so it deepens the pattern without widening the enforced surface. <strong>For both, the real surface lives in MMCA.Store and MMCA.ADC.</strong> For performance and cost, the framework ships an in-repo BenchmarkDotNet hot-path harness (§12) and a released COST.md (§31); only full load/stress data lives in the consumer apps.</p><p>That is not a weakness to hide; it is the reason the two apps exist. The framework supplies the base classes, the enforced layering, and the extraction points. The apps supply the proof that those things hold up against two different real domains and two different production deployments. The framework’s two-axis evaluation scores it at roughly 97% maturity and 85% implementation (96.9% and 84.8% exactly), with implementation the weaker axis precisely because some of the most important “does this actually model a domain well” evidence lives downstream, in the consumers, where it should.</p><h3>What we covered / Next</h3><p><strong>What we covered:</strong> two unrelated applications, a conference platform and an e-commerce store, both running on the same fifteen MMCA.Common packages at the same architecture stage; what they share (the packages, the same fitness rules via their own architecture maps, the same Result/CQRS/outbox/ database-per-service patterns); how a framework change ships as a lockstep sweep with no phased rollout; what each app proves that the framework cannot (real bounded contexts, real eventing, real production deployments); and the framework’s own honest note, written into the §4 and §5 scorecard rows, that a few categories are best evidenced in these consumers.</p><p><strong>Next in the series:</strong> a device-capability layer that lets one Blazor UI run in a browser and inside a native MAUI phone app, talking to native hardware through small per-capability contracts chosen at DI composition per host.</p><p><em>MMCA.Common is Apache-2.0 licensed and open source. The fastest way to judge whether it is a toy is to look at what runs on it. Star the repo, skim the scorecard’s §4 and §5 rows (the downstream-evidence note is the honest part), or </em><em>dotnet add package MMCA.Common.API and build your own third app on it.</em></p><ul><li>The 34-category scorecard (<a href="https://ivanball.github.io/docs/governance/common-ArchitectureScorecard.html">https://ivanball.github.io/docs/governance/common-ArchitectureScorecard.html</a>), including those downstream-evidence rows, is published in the docs site.</li></ul><p><strong>About the author</strong></p><p>Ivan Ball-llovera is a senior software architect working in enterprise .NET. This series is built on <strong>MMCA.Common</strong>, the open-source framework behind it: fifteen NuGet packages for a modular monolith you can extract services out of later, scored in public against a 34-category architecture rubric, gaps included.</p><ul><li>The framework: <a href="https://github.com/ivanball/MMCA.Common">https://github.com/ivanball/MMCA.Common</a></li><li>Start a new app: dotnet new install MMCA.Templates then dotnet new mmca-app -n Your.App</li><li>Add it to an existing solution: dotnet add package MMCA.Common.API</li><li>The full series index and the architecture docs: <a href="https://ivanball.github.io/writing.html">https://ivanball.github.io/writing.html</a></li></ul><p>Follow along here for one pattern a week.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12f694d2a361" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>