Onboarding guide
Aspire Orchestration and Containers
This chapter teaches how the MMCA.ADC system goes from a single dotnet run on your workstation to a
running stack of six .NET processes plus four containers: databases, a broker, a cache, a mail
interceptor, and a dashboard.
You will learn which resources the AppHost provisions and why, how service discovery and health-based
startup ordering wire everything together, which probe each resource carries and why the choice of
probe is load-bearing, what service defaults each service host gets from the framework's
MMCA.Common.Aspire package (there is no ADC-local ServiceDefaults project), how the two
MMCA.Common.Aspire* framework packages embed that machinery at the framework level, and how each
deployable is packaged into its Docker image. By the end you should be able to follow a WithReference
edge from first principles and explain local-to-cloud parity without looking at any other document.
Cross-references: primer §1, the big picture, primer §2, architectural styles, and the per-type reference in group 16, Aspire orchestration and service defaults.
The one-command local run
dotnet run --project Source/Hosting/MMCA.ADC.AppHost
That command brings up everything the application needs locally: four SQL Server databases, Redis,
RabbitMQ with management UI, a MailDev SMTP interceptor, four extracted microservice processes, a YARP
gateway pinned to https://localhost:6001, and the Blazor UI pinned to https://localhost:6002. The
Aspire dashboard, opened automatically, shows live logs, metrics, and distributed traces from every
process via an OTLP endpoint it injects into each one. No Docker Compose file is needed; no environment
variables need to be set by hand; the AppHost is the single source of truth for the local topology.
One environment variable changes the shape of that stack. Setting ADC_BROKER=servicebus before the
run swaps RabbitMQ for the official Azure Service Bus emulator container, so the whole stack speaks the
same transport production speaks (MMCA.ADC/Source/Hosting/MMCA.ADC.AppHost/Program.cs:98).
Unset is the default, and the rationale block above the switch is explicit about why
(Program.cs:69-92): the emulator costs a second container plus a warm-up, which is not a price the
everyday inner loop should pay, but a developer chasing a transport-specific bug (entity-name limits,
topic and subscription provisioning through the admin plane, scheduled redelivery pacing) otherwise
could not reproduce it locally at all.
One operational caveat that no source file states: run that command in an interactive terminal only.
Launched from a background or non-interactive shell the AppHost stalls at control-plane init (no
dashboard, no :6001), so a headless "verification run" hangs rather than failing (MMCA.ADC/CLAUDE.md,
Build/Test/Run section).
[Rubric §33, Developer Experience] assesses how quickly a new engineer becomes productive. A
single-command local run that matches production topology (same services, same broker option, same auth
flow) means the feedback loop is: edit, restart, observe real cross-service behavior, rather than
mocking everything and discovering integration bugs in CI. The ADC_BROKER opt-in is the same category
of decision applied to the one place where local and production genuinely diverge: parity is available
on demand rather than either always paid for or permanently missing.
MMCA.ADC.AppHost, the orchestration project
Source file:
MMCA.ADC/Source/Hosting/MMCA.ADC.AppHost/Program.csFramework helpers:MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/(Extensions.cs,BrokerSelection.cs,ServiceInfrastructureExtensions.cs,GatewayUiExtensions.cs,IdentityLinkExtensions.cs,ServiceTokenExtensions.cs,MmcaReplicas.cs,H2cHealthCheckExtensions.cs) Project file:MMCA.ADC/Source/Hosting/MMCA.ADC.AppHost/MMCA.ADC.AppHost.csproj
The AppHost carries no helper code of its own: the directory holds the project file and Program.cs,
and every wiring chain the AppHosts share is one call into MMCA.Common.Aspire.Hosting. What stays in
Program.cs is what only this application knows: its resource names, its databases, its gRPC edges and
its local-only switches. Its inline comments are the canonical explanation of the cross-service topology.
Project identity
The .csproj is a plain Microsoft.NET.Sdk executable with IsAspireHost set (AppHost.csproj:1-7).
Aspire 17 retired the Aspire.AppHost.Sdk project SDK, and the comment records what replaces it
(AppHost.csproj:9-16): Aspire.Hosting.AppHost brings the AppHost build targets and the orchestrator
wiring, and Aspire.Hosting.Dotnet brings AddDotnetProject. Three more hosting integrations are
referenced directly (Aspire.Hosting.Redis, .SqlServer, .RabbitMQ, AppHost.csproj:18-22), plus
MMCA.Common.Aspire.Hosting for the framework helpers (AppHost.csproj:26).
There are no ProjectReferences, and so no generated Projects.* types. Each service, the Gateway
and the UI is declared by its .csproj path through AddDotnetProject, for example
builder.AddDotnetProject("notification", "../../Services/MMCA.ADC.Notification.Service/MMCA.ADC.Notification.Service.csproj", options => options.LaunchProfileName = "https")
(Program.cs:126-129). .Build().RunAsync() (Program.cs:490) launches the dashboard and every declared
resource.
Building the project needs the matching Aspire CLI bundle (ASPIRE013): the build finds the CLI on PATH
or fetches the paired aspire.cli package through dnx (AppHost.csproj:13-15). CI installs the CLI first
through MMCA.Common's aspire-cli composite action (MMCA.ADC/.github/workflows/e2e.yml:222, and the
same action at deploy.yml:1021).
Infrastructure containers
SQL Server is declared as a persistent container named "sql" (Program.cs:15-16). The
ContainerLifetime.Persistent option keeps the container alive across AppHost restarts, preserving
data and avoiding re-seeding during inner-loop development (Program.cs:12-14 comment). Four databases
are carved from it (Program.cs:37-40):
adc-identity -> ADC_Identity (Identity service)
adc-conference -> ADC_Conference (Conference service)
adc-engagement -> ADC_Engagement (Engagement service)
adc-notification -> ADC_Notification (Notification service)
One database per service is the direct implementation of ADR-006 (database-per-service). No service
touches another service's database; no service races for another service's outbox rows
(Program.cs:18-27). The long comment above the declarations (Program.cs:29-36) is the honest part: the
legacy single AtlDevCon database is deliberately not provisioned here, and it is gone in Azure too.
It was exported to a bacpac blob and dropped on 2026-09-02, so the template no longer declares it,
and the bacpac itself was deleted on 2026-10-03, so there is no restore path; the template points at
infra/DISASTER-RECOVERY.md for the outcome (MMCA.ADC/infra/main.bicep:1408-1414). These four databases are the entire application
data estate (main.bicep:1421-1433). Database-per-service is the topology everywhere, not a
local-development shortcut.
Redis is also persistent (Program.cs:44-45), used by service hosts for distributed output caching
and ICacheService. All four service hosts receive a reference to it and a wait on it through
WithMmcaServiceInfrastructure (below).
The broker is chosen, not hardcoded. One line picks it (Program.cs:98):
var withBroker = builder.AddSelectedBroker("ADC_BROKER", sqlServer);
AddSelectedBroker lives in the framework (MMCA.Common.Aspire.Hosting/BrokerSelection.cs:58-74); the
application passes only the name of its own selector variable. When that variable reads servicebus
(case-insensitive, ServiceBusSelection, BrokerSelection.cs:28, checked at 36-44) it provisions the
emulator with AddServiceBusEmulatorBroker(sqlServer); otherwise a persistent RabbitMQ with
AddMessageBroker(). Either way it returns an attach delegate rather than a resource, because the two
WithBroker overloads take different resource types (RabbitMQServerResource at
Common.Aspire.Hosting/Extensions.cs:312 and ServiceBusEmulatorResource at Extensions.cs:341), so the
choice cannot be expressed as one variable handed to one call. WithSelectedBroker applies the delegate
(BrokerSelection.cs:82-87), and the class comment says what that buys (BrokerSelection.cs:13-19): every
service's wiring chain reads the same single line, which stops a new service from quietly being wired
to the wrong broker. See BrokerSelection for the
per-type entry.
AddMessageBroker() wraps builder.AddRabbitMQ(name).WithManagementPlugin() with the resource name
defaulting to "rabbitmq" (DefaultBrokerResourceName, Common.Aspire.Hosting/Extensions.cs:29, method
at 220); the management plugin exposes the admin UI at http://localhost:15672.
AddServiceBusEmulatorBroker(sqlServer) (Extensions.cs:261-298) provisions the official emulator image
mcr.microsoft.com/azure-messaging/servicebus-emulator:2.0.1 (Extensions.cs:136-150) and points it at
the existing SQL Server resource rather than starting a second engine, because the emulator stores
its state in SQL Server (SQL_SERVER and MSSQL_SA_PASSWORD at Extensions.cs:289 and 292, and a
WaitFor(sqlServer) at 297 because the emulator's first act is to create its schema).
MailDev comes from a framework helper rather than an inline container declaration (Program.cs:106):
var mailDev = builder.AddMailDev();
AddMailDev (Common.Aspire.Hosting/Extensions.cs:201-209) adds the MailDev container with a persistent
lifetime and two fixed host ports: 1080 for the web UI and 1025 for SMTP (MailDevHttpPort /
MailDevSmtpPort, Extensions.cs:163 and 169, both taken from the shared MailDevDefaults). Fixed rather
than Aspire's dynamic ports because a developer opens the web UI by hand, and the SMTP port is what each
consumer's Smtp:Port setting names (Program.cs:100-105). Every service waits for MailDev but none
references it, because the address is a literal in configuration rather than a discovered one.
[Rubric §17, DevOps and Deployment] assesses whether the local environment closely mirrors production. Persistent container lifetime means you are not starting from an empty database on every run; the same SQL, broker and Redis containers back both development and the Aspire-driven E2E CI run, so there is no "works on my machine" topology gap between developer and pipeline.
Health-gated startup, and which resource carries which probe
This is the part of the AppHost that is easiest to skim past and most expensive to get wrong. A
WaitFor edge on its own only proves that the target process started. Adding a health check to the
target turns every existing WaitFor into "the app is up and answering". Every service resource in this
AppHost carries one; only the probe differs, because of the Kestrel profile each target serves, and the
ServiceEndpointProfile argument to WithMmcaServiceInfrastructure is what selects it
(ServiceInfrastructureExtensions.cs:80-84; Program.cs:323-359 is the comment block that records all
of this):
- Notification passes
ServiceEndpointProfile.Mixedand so takes Aspire's stockWithHttpHealthCheck("/alive")(Program.cs:137-138). It runs the ADR-012 mixedHttp1AndHttp2profile on its default endpoint (Notification.Service/appsettings.json:9-19) so the SignalR WebSocket Upgrade works, which means Aspire's default HTTP/1.1HttpClientgets a real answer. The probe names thehttpendpoint explicitly (probeEndpointName: "http"), because Notification declares two named Kestrel endpoints and the other one,grpcon 8081, isHttp2-only (Program.cs:135-136). - Identity, Conference and Engagement pass
ServiceEndpointProfile.Http2Onlyand so takeWithH2cHealthCheck()(Program.cs:221, 196, 159; the enum atServiceEndpointProfile.cs:13, 19). Those three run KestrelHttp2-only on cleartext (h2c prior knowledge) so gRPC clients negotiate HTTP/2 without TLS. A stock HTTP/1.1 probe is answered with GOAWAYHTTP_1_1_REQUIREDrather than the health payload, so it would never turn healthy, and since the gateway and the UIWaitForall four services an always-failing check would deadlock the whole stack at startup.
WithH2cHealthCheck lives in the framework
(MMCA.Common.Aspire.Hosting/H2cHealthCheckExtensions.cs:111-138). It issues the same GET over HTTP/2
with RequestVersionExact, registers the check under a key of the form {resource}-h2c-{endpoint}
(CheckKey, H2cHealthCheckExtensions.cs:76, used at 120), and then associates it with the resource,
because association and registration are two separate halves and a WaitFor gates only when both are
present. A second call for the same resource and endpoint is a no-op rather than a duplicate
registration, which the health-check service rejects at startup. The probe budget is two seconds
(ProbeTimeout, H2cHealthCheckExtensions.cs:67) because Aspire polls the check for as long as a
dependent resource is waiting, and a probe slower than the poll interval turns the wait into a queue.
With no endpoint named it probes DefaultEndpointName, http (H2cHealthCheckExtensions.cs:60).
The class comment also records a rejected alternative so it is not re-proposed (the class comment in
H2cHealthCheckExtensions.cs). A deployed service already runs a dedicated HTTP/1.1 probe listener
driven by the HealthProbe:Port key, so injecting that key locally and pointing a stock probe at it
looks tempting. Doing so flips ConfigureEndpointsWithHealthProbe out of endpoint-defaults mode into
explicit-listener mode, whose Listen calls override the ASPNETCORE_URLS binding Aspire injects: the
service stops listening on its Aspire-allocated port and every co-hosted service collides on one fixed
port. The probe listener is a deployment-only construct.
The second half of the rule is which path the gate probes. Every service startup gate is /alive
(liveness), never /health/ready, and the reason is a cycle (Program.cs:339-346). Service readiness
includes the ADR-025 warm-up gate, whose OIDC metadata task fetches the discovery document through the
gateway; the gateway in turn WaitFors these services. A readiness gate there means each service
hammers the not-yet-started gateway with 30 second Polly timeouts until warm-up fails open at roughly
90 seconds. WithMmcaServiceInfrastructure therefore always probes liveness
(ServiceInfrastructureExtensions.cs:33-37), and the default path in the framework helper is /alive
for the same reason (DefaultProbePath, H2cHealthCheckExtensions.cs:54).
The gateway resource stays on /alive too (Program.cs:352-359; WithMmcaGateway hard-codes that probe,
GatewayUiExtensions.cs:55, rationale at 28-34), because /alive proves Kestrel is serving, which is all
ui.WaitFor(gateway) needs. Its downstream-{name} probes are tagged optional and sit outside
/health/ready (see
Readiness that reflects the edge's job), but a startup gate on
any aggregate that fans out to the downstreams would let one unreachable service stop
ui.WaitFor(gateway) from ever releasing. That is the 2026-08-29 UI WaitFor wedge, from when the
gateway's readiness still included those probes, and how Store's run 33237319737 died before it: the
stack never became ready and a whole E2E run reported zero tests executed. Deployed environments own
their own probes, and the deployed gateway's readiness probe targets /alive as well (the gateway app's
probes in MMCA.ADC/infra/main.bicep). Only the UI, which nothing WaitFors, gates on /health/ready
(WithMmcaUi, GatewayUiExtensions.cs:108).
[Rubric §29, Resilience and Business Continuity] assesses whether the system survives partial failure. The liveness-versus-readiness split here is that rubric applied to startup: readiness is the correct signal for a load balancer and the wrong one for a dependency graph, because readiness aggregates other resources and a startup gate that aggregates its own waiters cannot converge.
The WithSQLServerDataSource extension (and its Cosmos/SQLite siblings)
WithSQLServerDataSource is a framework extension method, not an AppHost-local helper. It lives in
MMCA.Common.Aspire.Hosting's Extensions class (Common.Aspire.Hosting/Extensions.cs:587-598). (It was
named WithDataSource until ADR-018; the rename to WithSQLServerDataSource gives it a consistent
With*DataSource shape with the polyglot siblings below, a breaking API change swept across
consumers in one lockstep release, ADR-016.) WithMmcaServiceInfrastructure calls it
first (ServiceInfrastructureExtensions.cs:74), so no ADC service calls it directly.
It is declared inside a C# extension(...) block rather than as a classic this-parameter static
method, which is why the receiver does not appear in the signature:
extension(IResourceBuilder<DotnetProjectResource> service)
{
public IResourceBuilder<DotnetProjectResource> WithSQLServerDataSource(
IResourceBuilder<SqlServerDatabaseResource> database,
string logicalName)
{
ArgumentNullException.ThrowIfNull(service);
ArgumentNullException.ThrowIfNull(database);
return service
.WithReference(database)
.WaitFor(database)
.WithEnvironment($"DataSources__{logicalName}__SQLServerConnectionString", database.Resource.ConnectionStringExpression);
}
}
It injects the connection string once, and that single entry is the whole configuration
(Extensions.cs:577-582). DataSources__{logicalName}__SQLServerConnectionString feeds the MMCA.Common
multi-database routing: entities whose logical source matches logicalName are routed to this database.
With no top-level connection string present, the one database a host declares this way also seeds its
Default source, so the framework's own tables, the [Required] validation and the readiness health
check all resolve from it, and the logical name collapses onto Default: one SQLServerDbContext
instance, one EF change tracker, one migrations set per service. The Azure side matches exactly: the
Bicep hands Identity only DataSources__Identity__SQLServerConnectionString
(MMCA.ADC/infra/main.bicep:2464) plus its migrations assembly (main.bicep:2465) and
Outbox__DatabaseName (main.bicep:2466), with no top-level ConnectionStrings__SQLServerConnectionString
anywhere. The WaitFor(database) (Extensions.cs:596) ensures the service process does not start until
SQL Server is healthy. Its PostgreSQL peer, WithPostgreSQLDataSource (Extensions.cs:617-628), has the
same shape and injects DataSources__{logicalName}__PostgreSQLConnectionString.
Polyglot siblings (ADR-018). Two more helpers wire the engines that have no server container.
Neither ADC nor Store calls them: they are the AppHost half of the polyglot-persistence extension points
ADR-018 keeps, so a module can place an entity on Cosmos or SQLite without new orchestration code.
MMCA.Common's own sample AppHost exercises both
(MMCA.Common/Tests/Hosting/MMCA.Common.Testing.Aspire.AppHostTests.SampleAppHost/Program.cs), and
Helpdesk's template staging emits a WithSqliteDataSource call (MMCA.Helpdesk/build/templates/stage.ps1:420).
WithCosmosDataSource(database, logicalName)(Extensions.cs:646-658) takes anAzureCosmosDBDatabaseResourceand injects two env vars,DataSources__{logicalName}__CosmosConnectionStringandDataSources__{logicalName}__CosmosDatabaseName(Cosmos'sUseCosmostakes the database name separately). It layers on top ofWithSQLServerDataSource(a service uses Cosmos for one module alongside its SQL Server source, Extensions.cs:640-641).WithSqliteDataSource(logicalName, filePath)(Extensions.cs:671-682) takes a file path (SQLite has no Aspire container resource) and injectsDataSources__{logicalName}__SqliteConnectionString(Data Source=<path>). It adds no reference and no wait, because there is no resource to wait on.
The four service hosts and their wiring
Services are declared in this order: Notification (Program.cs:126-138), Engagement (153-159), Conference
(190-200), Identity (214-230). Declaration order matters because the cross-service references, the
gateway and the UI are added after all four are declared (Program.cs:266 onward). Each service is one
AddDotnetProject plus one framework call:
var engagementService = builder.AddDotnetProject(
"engagement",
"../../Services/MMCA.ADC.Engagement.Service/MMCA.ADC.Engagement.Service.csproj",
options => options.LaunchProfileName = "https")
.WithMmcaServiceInfrastructure(engagementDb, "Engagement", redis, mailDev, withBroker, ServiceEndpointProfile.Http2Only);
LaunchProfileName = "https" selects the HTTPS launch profile from launchSettings.json so Aspire
registers both HTTP and HTTPS endpoints for service discovery (Program.cs:114-116 comment).
WithMmcaServiceInfrastructure (MMCA.Common.Aspire.Hosting/ServiceInfrastructureExtensions.cs:57-85)
is the chain every extracted service shares, applied in a fixed order (ServiceInfrastructureExtensions.cs:73-84):
WithSQLServerDataSource(database, logicalName) (its own database plus a wait on it), WithReference(cache),
WithSelectedBroker(attachBroker), WaitFor(cache), WaitFor(mailServer), then the startup probe the
profile selects. Two things it deliberately does not do (ServiceInfrastructureExtensions.cs:28-43): it
marks no endpoint external, because a backend service is reached through the gateway (a host that needs
one service reachable directly chains WithExternalHttpEndpoints() after the call), and it references
no project resource, so the AppHost's project-to-project edge set is exactly what Program.cs declares
itself. Host-specific additions (seeding switches, cross-service references, E2E keys) chain after it.
WithSelectedBroker resolves to one of the two WithBroker overloads. The RabbitMQ one
chains .WithReference(broker).WaitFor(broker).WithEnvironment("MessageBus__Provider", "RabbitMq")
(Common.Aspire.Hosting/Extensions.cs:318-321). The emulator one sets
MessageBus__Provider=AzureServiceBus plus two more variables:
MessageBus__ConnectionString (which ends in UseDevelopmentEmulator=true, the marker the framework's
own Azure Service Bus transport keys its emulator branch off,
MMCA.Common.Azure/Messaging/AzureServiceBusTransport.cs:142-153) and
MessageBus__EmulatorAdminEndpoint, the management-plane address that transport needs to build its
ServiceBusAdministrationClient (AzureServiceBusEndpoint.cs:65-66) (Extensions.cs:350-352,
connection-string shape at ServiceBusEmulatorResource.cs:66-68, admin address at 81-83). That branch
only exists in a service that registered the transport: each ADC service passes
RegisterBrokerTransports = services => services.AddAzureServiceBusTransport()
(MMCA.ADC.Conference.Service/Program.cs:300; Identity 260, Engagement 140 and Notification 97 carry the same line), and
AddBrokerMessaging throws, naming the package and the call, when the selected provider has no
registered transport (DependencyInjection.Messaging.cs:211-230). Either way each service waits for the
broker to be healthy and gets the environment variable that makes AddBrokerMessaging() select the
transport. When that variable is absent (integration tests running via WebApplicationFactory),
AddBrokerMessaging short-circuits to in-process mode so existing tests continue to work without a real
broker (Program.cs:63-67).
Conference service has one extra line (Program.cs:200):
.WithEnvironment("Seeding__IncludeSampleConferenceData", "true")
This seeds sample speakers and sessions so the public browse grids are non-empty for the Playwright E2E suite. The comment (Program.cs:197-199) explicitly restricts this to local dev and E2E CI; production leaves it unset, and the AppHost never runs in production at all.
Identity service carries two extras. Seeding__IncludeSampleUsers=true (Program.cs:225) seeds the
well-known organizer/attendee accounts the Playwright suite logs in with; the comment
(Program.cs:222-224) restricts it to local dev and E2E CI so production creates no weak-credential
accounts. WithE2eRsaKeys() (Program.cs:230) is a framework extension, not AppHost-local code: when
E2E_JWT_PRIVATE_KEY_PEM and E2E_JWT_PUBLIC_KEY_PEM are present in the AppHost's own environment
(injected by the e2e.yml workflow for the ephemeral CI keypair, generated at 3072 bits because that is
MMCA.Common's Jwt:MinimumRsaKeySizeBits floor outside Development, MMCA.ADC/.github/workflows/e2e.yml:252-258) it maps them onto
Jwt__RsaPrivateKeyPem, Jwt__RsaPublicKeyPem and Jwks__RsaPublicKeyPem on the Identity resource
(Common.Aspire.Hosting/Extensions.cs:414-429). Without either variable the method returns the resource
untouched (Extensions.cs:420-423), so locally and in production user-secrets and Azure Key Vault are
used instead.
The service-to-service token key is the one symmetric secret the AppHost provisions.
AddServiceTokenSigningKey() (ServiceTokenExtensions.cs:46) declares a generated secret parameter, and
WithServiceTokenSigningKey (ServiceTokenExtensions.cs:67) hands it to Identity, Engagement and
Notification (Program.cs:243-246): the HS256 key (Grpc:ServiceToken) for the gRPC calls that carry no
user token to forward. It is generated rather than read from user-secrets because three services must
hold it identically; Aspire keeps the generated value in this AppHost's user secrets, so it is never
committed, and production injects the Key Vault secret Grpc--ServiceToken--SigningKey instead
(Program.cs:232-242).
gRPC cross-service references
Nine directed edges express the gRPC topology (Program.cs:250-307):
// Notification -> Identity
notificationService.WithReference(identityService).WaitFor(identityService);
// Engagement -> Conference
engagementService.WithReference(conferenceService).WaitFor(conferenceService);
// Engagement -> Identity (verified-user lookup for the ticket roster)
engagementService.WithReference(identityService).WaitFor(identityService);
// Conference -> Engagement (reverse edge, deliberately no WaitFor)
conferenceService.WithReference(engagementService);
// Engagement -> Notification (live-channel push, deliberately no WaitFor)
engagementService.WithReference(notificationService);
// Identity -> Engagement, Notification and Conference (data-subject export aggregation, no WaitFor)
identityService.WithReference(engagementService);
identityService.WithReference(notificationService);
identityService.WithReference(conferenceService);
// Notification -> Conference (live-channel join gate, deliberately no WaitFor)
notificationService.WithReference(conferenceService);
WithReference on a project resource injects services__{name}__http__0 (and https__0) environment
variables into the consumer. The AddTypedGrpcClient<T>(serviceName) call in each service's
Program.cs uses serviceName to resolve http://{name} through Aspire's service discovery. The
Engagement-to-Notification edge targets a named endpoint rather than the default one: Notification
keeps Http1AndHttp2 on its default endpoint so the SignalR WebSocket Upgrade works and declares a
separate Http2-only grpc endpoint on 8081 (Notification.Service/appsettings.json:15-18), so the
reference injects services__notification__grpc__0 and the client resolves http://_grpc.notification
(Program.cs:276-283, Notification.Contracts/DependencyInjection.cs:42).
The deliberate asymmetry in the Conference/Engagement pair is explained in the inline comment
(Program.cs:256-263): bidirectional WaitFor would produce a circular wait and deadlock. Instead,
transient "peer not ready" gRPC errors during startup self-heal via the Polly retry and circuit-breaker
pipeline baked into AddTypedGrpcClient. Engagement waits for Conference as a best-effort ordering hint
since Conference is the heavier producer (Program.cs:262-263). Engagement's wait on Identity cannot
deadlock, because Identity is a leaf that waits on no service (Program.cs:269-271). The remaining edges
omit WaitFor for the same cycle reason plus one of their own: Engagement's live-channel publish is
fire-and-forget-with-logging (Program.cs:276-282); Engagement, Notification and Conference already depend
on Identity, so a reciprocal wait for the export aggregation would deadlock startup, and an unreachable
peer degrades only its own section of the export (Program.cs:284-299); and the live-channel join gate
fails the join closed when Conference refuses the lookup, so a wait there would only join the
Conference-Engagement pair in a startup deadlock (Program.cs:300-307). Aspire's hosting package has no
gRPC-specific API here: these are stock WithReference calls, and MMCA.Common.Aspire.Hosting
deliberately adds none.
What consumes those injected variables lives in a third package, MMCA.Common.Grpc. On the server side
AddGrpcServiceDefaults() registers AddGrpc with the GrpcResultExceptionInterceptor (mapping
Result failures to RpcException), turns detailed errors off, and adds server reflection
(MMCA.Common.Grpc/DependencyInjection.cs:31-50); AddMmcaServiceHost calls it for all four ADC services
(MMCA.Common.ServiceHost/ServiceHostBuilderExtensions.cs:167). On the client side
AddTypedGrpcClient<TClient>(serviceName) (DependencyInjection.cs:104-185) sets the address to
http://{serviceName}, which is HTTP/2 cleartext with prior knowledge, adds the
JwtForwardingClientInterceptor so an inbound bearer token rides along to the peer, forces a
SocketsHttpHandler (the global ConfigureHttpClientDefaults wrapper can otherwise defeat HTTP/2
negotiation, DependencyInjection.cs:124-141) and applies a resilience pipeline whose values come from
the Grpc-prefixed members of HttpResilienceDefaults (DependencyInjection.cs:143-181). Those members are the interesting part: their
timeouts are the east-west path's own (8 s per attempt, 20 s total, a 5 s default call deadline), sized from measured gRPC latency, while the retry budget is shared with the
outbound-HTTP path (Core/MMCA.Common.Shared/Resilience/HttpResilienceDefaults.cs:61-90),
and its circuit-breaker shape is stated explicitly (failure ratio 0.5 at line 96, minimum throughput
10 at line 102, break duration 10 seconds at line 108) because an east-west gRPC call addresses a peer
directly and bypasses the gateway's destination health checks, so the breaker is the only thing that notices
a peer going bad. The h2c choice is not a shortcut: Aspire's endpoint discovery does not reliably
produce a services__{name}__https__0 key for project resources, so the resolver falls back to http
regardless of the requested scheme, and the target must therefore serve HTTP/2 on its cleartext endpoint
(DependencyInjection.cs:56-64).
[Rubric §7, Microservices Architecture] assesses how cleanly services are decoupled and how
inter-service calls are managed. Declaring WithReference only for actual call edges (not broadcasting
every service to every other service) keeps the service-discovery injection minimal and makes the
topology readable as code.
[Rubric §29, Resilience and Business Continuity] assesses whether the system can survive partial failures. The no-WaitFor choice on the reverse edges, combined with a resilience pipeline on the typed gRPC clients, means a slow-starting peer never blocks the whole stack from reaching a healthy state.
The Gateway
var gateway = builder.AddDotnetProject("gateway", "../../Hosts/MMCA.ADC.Gateway/MMCA.ADC.Gateway.csproj")
.WithMmcaGateway(6001, notificationService, engagementService, conferenceService, identityService);
Program.cs:362-363. WithMmcaGateway (MMCA.Common.Aspire.Hosting/GatewayUiExtensions.cs:40-57) adds a
WithReference and a WaitFor for each service in the order given, marks the gateway's endpoints
external, gates it on /alive, and pins its https endpoint to the port passed in. The gateway has no
data source, no Redis reference, and no broker attachment. It is stateless: no database, no cache, no
broker traffic (Program.cs:319-321). The four references are purely for Aspire service-discovery
injection: they make the gateway able to resolve http://identity, http://conference, and so on at
runtime through YARP's configured route table. The HTTPS endpoint is pinned to port 6001 because the
MAUI native client runs outside Aspire, cannot participate in its dynamic port allocation, and reaches
the gateway at the well-known URL baked into its appsettings.json (Program.cs:315-317).
The gateway waits for all four backend services before Aspire marks it healthy. This means the UI, which in turn waits for the gateway, only starts after the full backend is ready, a deliberate staging of the startup sequence.
Why the gateway proxies JWKS discovery, and stamps the issuer
Identity runs Http2-only on cleartext (h2c prior knowledge) so gRPC clients can negotiate HTTP/2
without TLS. The downside is that the default JwtBearer backchannel HttpClient sends HTTP/1.1, which
a Kestrel Http2-only endpoint rejects. The local solution (Program.cs:365-374 and
Common.Aspire.Hosting/Extensions.cs:370-398) is WithJwksDiscovery, which sets
Authentication__JwtBearer__Authority to the gateway's HTTPS endpoint rather than Identity's:
notificationService.WithJwksDiscovery(identityService, gateway);
engagementService.WithJwksDiscovery(identityService, gateway);
conferenceService.WithJwksDiscovery(identityService, gateway);
The gateway accepts both HTTP/1.1 and HTTP/2 via ALPN, and its /.well-known/* routes forward the
discovery fetch on to Identity over h2c internally. So the JwtBearer middleware's HTTP/1.1 metadata
fetch works end-to-end without any workaround on the services themselves.
The other half of that contract follows the JWKS wiring (Program.cs:384):
identityService.WithIssuer(gateway);
WithIssuer (IdentityLinkExtensions.cs:100) sets Jwt__Issuer on Identity to the gateway's https
endpoint (Program.cs:383). The issuer Identity stamps into every token it signs has to be the same URL
its peers just discovered, or every cross-service call fails validation on the issuer claim. The
appsettings default hardcodes the pinned dev port for a standalone F5 run, so deriving the value from
the gateway resource means an Aspire run cannot mint wrong-issuer tokens if that port ever moves
(Program.cs:376-382). Production sets the equivalent from the gateway's ACA FQDN as Jwt__Issuer
(MMCA.ADC/infra/main.bicep:2499).
Production does not route the discovery fetch through the gateway, and the split is deliberate. On
Conference, Engagement and Notification the Bicep sets Authentication__JwtBearer__Authority to the
Identity container app's internal address over plain HTTP, http://<identity app>, together with
Authentication__JwtBearer__RequireHttpsMetadata=false (MMCA.ADC/infra/main.bicep:2776, 2780, 2923, 2927, 3097, 3101),
so the metadata fetch goes straight to Identity through Container Apps internal ingress; the framework
honors a configured RequireHttpsMetadata=false outside Development, with one startup warning, because
that internal ingress needs it (MMCA.Common/AGENTS.md, cross-service auth). The gateway hop is the
local answer to a local constraint: under Aspire a default backchannel cannot reach the cleartext
Http2-only endpoint directly. The Store AppHost records the same split beside its own
WithJwksDiscovery calls (MMCA.Store/Source/Hosting/MMCA.Store.AppHost/Program.cs:324-336). The
consequence for testing is that the E2E stack exercises the gateway path, not the direct one that ships.
[Rubric §11, Security] assesses how credentials and tokens flow through the system. No symmetric JWT secret is shared between services for user tokens; each non-Identity service fetches the RSA public key dynamically. Locally, routing that fetch through the gateway keeps the internal topology (cleartext h2c) invisible to callers, and deriving the issuer from the gateway resource keeps discovery and issuance from drifting apart.
The Blazor UI
var ui = builder.AddDotnetProject("ui", "../../Hosts/UI/MMCA.ADC.UI.Web/MMCA.ADC.UI.Web.csproj", options => options.LaunchProfileName = "https")
.WithMmcaUi(gateway, 6002, notificationService, engagementService, conferenceService, identityService);
Program.cs:392-393. WithMmcaUi (MMCA.Common.Aspire.Hosting/GatewayUiExtensions.cs:88-110) marks the
UI's endpoints external, references and waits for the gateway, then waits for each service without
referencing it, gates on /health/ready and pins https to 6002. The services are waited for, not
referenced, because the UI calls every API through the gateway: a services__{service}__* variable in
the UI process would be a discovery name nothing resolves, and an edge production does not have, since
the UI container app is given only the gateway (GatewayUiExtensions.cs:70-75). It is the one resource
gated on /health/ready rather than /alive, and it can be: nothing waits for the UI, so there is no
cycle to close, and the UI head runs the default Http1AndHttp2 profile so the stock probe answers
(GatewayUiExtensions.cs:77-82). Port 6002 is pinned for the same reason as 6001: E2E tests and
out-of-Aspire clients need a stable address (Program.cs:386-391).
Several environment-derived values are then pushed onto other resources, all of them things only the AppHost knows:
Api__ApiEndpointandApi__WasmApiEndpointon the UI, throughui.WithGatewayApiEndpoints(gateway)(Program.cs:468; GatewayUiExtensions.cs:128-138). These are both halves of the splitinfra/main.bicep:3424and3426make in production, derived from the gateway'shttpsendpoint instead of hardcoded. The WASM one is what/client-confighands the browser (and what the Blazor CSP pinsconnect-srcto), so it must be an externally reachable URL: a browser cannot resolve an Aspire service-discovery name. The server-side one is overridden here because exactly one consumer is not anIHttpClientFactoryclient:NotificationHubServicebuilds a SignalRHubConnection, which creates its own message handler and never sees the service-discovery handler (Program.cs:455-467).- The UI origin on Identity, through
identityService.WithUiLinks(ui)(Program.cs:476;IdentityLinkExtensions.cs:74): the OAuth post-login redirect baseOAuth__UIBaseUrl, so the redirect lands on the UI host rather than staying on the API server, and the three emailed links, the password reset (/reset-password), the email confirmation (/confirm-email) and the sign-in link and ticket-holder invitation (/auth/sign-in-link). The UI port is dynamic under Aspire, so the appsettings defaults, which serve a standalone F5 run, would point each emailed link at a host that is not listening (Program.cs:470-475). - Passkeys (ADR-139) and machine clients (ADR-140). Both ship switched off (
Passkeys:EnabledandMachineClients:Enabledare false in the Identity service's appsettings and nothing ininfra/turns them on), and the local stack turns them on:Passkeys__Enabled,Passkeys__Origins__0set to the UI's dynamichttpsendpoint as the one WebAuthn origin, andMachineClients__Enabledon Identity, plusSignIn__OfferPasskeyson the UI so the web head offers them (Program.cs:478-488).
Between the UI declaration and those lines sit the E2E switches (Program.cs:395-429), all absent in
production. Each is a single framework call; the trigger, the target setting and any lifted value live
in MMCA.Common.Aspire.Hosting:
ui.WithE2eForceWebAssembly(); // Program.cs:408
ui.WithE2eForceServer(); // Program.cs:416
identityService.WithE2eRegistrationThrottleLift(); // Program.cs:422
gateway.WithE2eGatewayRateLimitLift(); // Program.cs:429
E2E_FORCE_WASM sets E2E__ForceWebAssembly on the UI to run the suite without a Blazor Server circuit
(Extensions.cs:63, 69); it is a local fast-box option only, since on the two-core hosted runner the
per-context WASM boot never wins the race against the suite's waits, so e2e.yml deliberately does not
set it (Program.cs:396-402). E2E_FORCE_SERVER sets E2E__ForceServer to pin the UI to
InteractiveServer (Extensions.cs:49, 55), and loses to E2E_FORCE_WASM when both are set
(Program.cs:410-415). E2E_LIFT_REGISTRATION_THROTTLE, set by e2e.yml and implied by E2E_FORCE_WASM
for local runs, lifts the registration throttle (Program.cs:403-407) to the framework constant
E2eRegistrationsPerIpPerHour = 1000 (Common.Aspire.Hosting/Extensions.cs:36), from the production
default of 10 (MMCA.Common.Infrastructure/Auth/LoginProtectionSettings.cs:37), because the suite
registers far more than ten accounts from one localhost IP. The same call lifts Identity's per-IP
auth-ip limiter too: with passkeys offered, every login-page visit spends one permit on the passkey
options call before the login spends another (Program.cs:418-421). The gateway lift is covered in the
package section below.
The multi-replica opt-in
ADC_REPLICAS=<n> is the second environment variable that changes the stack's shape
(Program.cs:431-453). Conference mode runs Identity, Conference, Engagement and the Gateway at up to four
replicas and Notification at two, and nothing in the inner loop otherwise exercises more than one: the
shared-store lockout, refresh-rotation reuse grace, outbox claims, the MigrateAsync applock and the
non-sticky SignalR negotiate only misbehave across processes. MmcaReplicas.FromEnvironment("ADC_REPLICAS")
(MMCA.Common.Aspire.Hosting/MmcaReplicas.cs:33) reads the count, and
WithMmcaReplicas(replicas, distributedRateLimiting) (MmcaReplicas.cs:63) runs the four services and the
gateway at that many replicas behind Aspire's proxy, each replica on its own target port. The flag is
true on the services and false on the gateway, mirroring production, which sets
RateLimiting__Distributed on the four services and not on the gateway, whose edge limiters stay per
replica (Program.cs:445-453). The UI stays single-instance. Aspire's proxy balances per TCP connection
rather than per request, so the gateway's pooled HTTP/2 connections tend to pin to one service replica
while browser, WebSocket and SignalR connections spread: the run proves correctness under concurrency,
not capacity (Program.cs:440-443). Unset, or 1, keeps the single-instance stack.
Where service defaults come from, MMCA.Common.Aspire, not a local project
There is no MMCA.ADC.ServiceDefaults project. Source/Hosting/ contains the AppHost and the four
per-service migrations assemblies, nothing else. The conventional Aspire "ServiceDefaults" shared project
that scaffolding generates has been deleted; each service host (and the UI, and the Gateway) instead
calls AddServiceDefaults() from the framework's MMCA.Common.Aspire package, and MapDefaultEndpoints()
to expose the health endpoints. All six ADC deployables do this. The four service hosts reach both through the framework's AddMmcaServiceHost (AddServiceDefaults() at MMCA.Common.ServiceHost/ServiceHostBuilderExtensions.cs:85) and UseMmcaServiceHostAsync (MapDefaultEndpoints() at ServiceHostApplicationExtensions.cs:56), the UI through AddMmcaBlazorWebHost (MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:85 and :198), and the Gateway calls them itself (MMCA.ADC.Gateway/Program.cs:77 and 195).
Each host then runs AddAzureMonitorExporter() from the MMCA.Common.Azure adapter package straight
after AddServiceDefaults(): the services and the UI pass it as the AfterServiceDefaults callback (for example MMCA.ADC.Notification.Service/Program.cs:85, invoked at ServiceHostBuilderExtensions.cs:86), the Gateway on the
line after AddServiceDefaults() (see Dual telemetry export below). This means the OpenTelemetry wiring, health checks, service discovery, and Polly resilience
are identical across both downstream apps (ADC and Store, neither of which has a ServiceDefaults
project any more) and are versioned in lockstep with the rest of the framework, there is no per-app copy
to drift. The full behavior of those methods is documented in the next section.
Framework host extensions that are opt-in per host
Not every framework host extension is bundled into the defaults. Several are opt-in per host, called
from each host's own Program.cs, and most are gated on a configuration key that is absent locally,
so they no-op on a developer machine and in the test tiers while doing real work in Azure. That gating
is what keeps local-to-cloud parity honest: the same call sites run in both places, and only the
configuration differs.
AddCommonSerilog(path)(MMCA.Common.Aspire/Logging/SerilogHostExtensions.cs:59-70) is called beforeAddServiceDefaultsin every ADC service (AddMmcaServiceHostcalls it atMMCA.Common.ServiceHost/ServiceHostBuilderExtensions.cs:84, ahead ofAddServiceDefaultsat 85). The provider registration is the load-bearing part, and the comment says why (SerilogHostExtensions.cs:18-22, echoed at ServiceHostBuilderExtensions.cs:83):UseSerilog()replaces the wholeILoggerFactoryand so silently bypasses every other provider, including the OpenTelemetry to Azure Monitor oneAddAzureMonitorExporter()wires. That bypass is why no application log line from these hosts ever reached Application Insights, while the Gateway (which never calledUseSerilog) did show up.builder.Logging.AddSerilog(Log.Logger, dispose: true)(line 67) adds Serilog as one provider alongside the others. Production then caps what ships to Azure Monitor withLogging__OpenTelemetry__LogLevel__Default=Warning(MMCA.ADC/infra/main.bicep:331-341); Serilog keeps writing Information to stdout, so container logs stay complete while only warnings and above bill against the workspace.ConfigureEndpointsWithHealthProbe(protocols, redeclareCleartextEndpoint, cleartextPort)(MMCA.Common.Aspire/Kestrel/KestrelEndpointExtensions.cs:77-101) appliesprotocolsto every Kestrel endpoint default and, whenHealthProbe:Portis set (HealthProbePortConfigKey, KestrelEndpointExtensions.cs:31), adds a dedicated Http1-only listener for the platform probes. Both deployed profiles are this one call with different arguments, and the second parameter is the reason there are two (KestrelEndpointExtensions.cs:45-59). The three h2c REST services passHttpProtocols.Http2and keepredeclareCleartextEndpointat its default oftrue(the defaults ofMmcaServiceHostOptions, MmcaServiceHostOptions.cs:42 and 49, passed on atServiceHostBuilderExtensions.cs:81), because an explicitListencall overrides the container'sASPNETCORE_HTTP_PORTSdefault binding and the main h2c endpoint has to be re-declared alongside the probe port or it disappears. Notification passesHttpProtocols.Http1AndHttp2, redeclareCleartextEndpoint: false(MMCA.ADC.Notification.Service/Program.cs:79-80) because its two endpoints come from configuration already; there the probe listener is strictly additive and nothing re-binds a port the configuration owns. A non-integer probe port throws at startup rather than silently producing no listener, since the platform would then probe a closed port and the revision would never come up (KestrelEndpointExtensions.cs:72-76). In Azure the key is8081on Identity, Conference and Engagement (main.bicep:2460, 2753, 2906) and8082on Notification (main.bicep:3080), because the ADR-012 mixed profile already owns 8080 for ingress and 8081 for gRPC there (main.bicep:3028, 3032-3041). Locally the key is absent on every host, which is exactly why the AppHost has to use the h2c probe instead.AddAzureKeyVaultConfiguration()(MMCA.Common/Source/Hosting/MMCA.Common.Azure.Startup/AzureKeyVaultConfigurationExtensions.cs:80) layers an Azure Key Vault over the host configuration, so a secret in the vault reads back throughIConfigurationlike any other setting and overrides the sources added before it. It lives in theMMCA.Common.Azure.Startupadapter package (MMCA.Common.Azure.Startup.csproj:3-4), not inMMCA.Common.Aspire, so the core packages reference no Azure SDK. The three start-up extension classes live only in that package, under theMMCA.Common.Azurenamespace (the Gateway'susing MMCA.Common.Azure;atMMCA.ADC.Gateway/Program.cs:61is what reaches them), andMMCA.Common.Azurecarries no forwarding copy of them (it takes a plainProjectReferenceon the package instead,MMCA.Common.Azure.csproj:39). The gate isKeyVault:Uri: absent or whitespace and the method returns without adding a source (AzureKeyVaultConfigurationExtensions.cs:82, 89-92), which is why local dev, CI and the integration tier take no Azure dependency at startup. Only past the gate does it register the marker the core startup tripwire checks (AzureKeyVaultConfigurationExtensions.cs:113-115), so a host withKeyVault:Uriset but no call fails at startup naming the missing call (MMCA.Common.Aspire/Integrations/HostIntegrationTripwire.cs:95-100) instead of running with every vault secret absent; registering nothing on the absent path means a URI that only appears in a source added after the call still trips that check (comment at 84-88). An optionalKeyVault:ReloadIntervalMinutesre-reads the vault on that interval, and a value that is not a positive whole number throws at startup rather than silently falling back to "never reload" (AzureKeyVaultConfigurationExtensions.cs:96-111); left unset, the vault is read once and a rotated secret reaches the host only on its next restart (lines 39-41). Two details worth knowing. It is called early, beforeAddServiceDefaults()and anything else that binds settings, becauseConfigurationManagerbuilds and loads each source as it is added (AddMmcaServiceHostruns the host'sConfigureConfigurationSourcescallback first,MMCA.Common.ServiceHost/ServiceHostBuilderExtensions.cs:79, with the comment at 76-78; Notification passes the call atMMCA.ADC.Notification.Service/Program.cs:70, and its comment at 67-69 says the same); and a secret name cannot contain a colon, so the provider maps--onto the configuration separator, meaningJwt--SigningKeyarrives asJwt:SigningKey(AzureKeyVaultConfigurationExtensions.cs:45-48). Authentication isDefaultAzureCredential(line 117), so a deployed host uses its managed identity. All four ADC services call it, as do the Gateway and the UI (MMCA.ADC.Gateway/Program.cs:75,MMCA.ADC.UI.Web/Program.cs:41).AddAzureDataProtection()(MMCA.Common/Source/Hosting/MMCA.Common.Azure.Startup/AzureDataProtectionExtensions.cs:54) persists the ASP.NET Core DataProtection key ring to a single Azure blob so every replica of a scaled-out host shares one key ring. The default key ring is per-process and in memory, which is correct for one process and wrong for two: a cookie or antiforgery token minted by replica A cannot be decrypted by replica B, and the user sees sign-outs that follow the load balancer rather than any pattern. The gate isDataProtection:BlobStorageUri(AzureDataProtectionExtensions.cs:56-67), and like the vault call it registers the tripwire marker only once past that gate (AzureDataProtectionExtensions.cs:69-71), so the URI set without the call fails startup instead of leaving every replica on its own key ring. A second, deliberately separate gate,DataProtection:KeyVaultKeyUri, encrypts that key ring at rest (AzureDataProtectionExtensions.cs:90-94, rationale at 83-89): the two are not folded together because blob persistence is what fixes cross-replica decryption and has to work on its own, since the Key Vault Crypto User role is granted out of band and can lag a deployment, so coupling them would turn a missing role assignment into a total auth outage. Leaving that key unset is therefore not a failure, but outside Development it registers a hosted service that logs one startup Warning naming the key (AzureDataProtectionExtensions.cs:95-99), so the hardening gap is visible rather than silent. The two ADC hosts that do cookie cryptography call it: Identity (MMCA.ADC.Identity.Service/Program.cs:106) and the UI (MMCA.ADC.UI.Web/Program.cs:49).AddRedisCaching()/AddRedisOutputCaching()(MMCA.Common.Aspire/Caching/RedisCachingExtensions.cs:70-81and112onward) register the Aspire distributed cache plus theIConnectionMultiplexerthatDistributedCacheServiceneeds for SCAN-based prefix eviction, and back the output cache with the same Redis. Both no-op when the connection string is absent (RedisCachingExtensions.cs:72-75, 114-117), where the in-memory fallback is the documented behavior. The load-bearing argument isDisableHealthChecks = trueon both registrations (RedisCachingExtensions.cs:77-78, 121): the raw Aspire integration registers an untagged StackExchange.Redis check, which/health/readytherefore includes, and against Azure Managed Redis it issuesCLUSTER INFO, a command StackExchange.Redis 3.x refuses outside admin mode. Every probe threw against a healthy cache and every revision failed activation. Common contributes its own PING-only check instead (seeAddInfrastructureHealthChecksbelow). The class comment at RedisCachingExtensions.cs:9-25 records the whole incident inline.AddMmcaServiceHostgates one more cache on the same key:AddCommonHybridCacheWhenRedisConfigured(builder.Configuration)registers the two-level cache only when aredisconnection string is present (MMCA.Common.ServiceHost/ServiceHostBuilderExtensions.cs:97), because without Redis the second level is the in-memory distributed cache and an L1 in front of it buys nothing.AddScheduledJobs(builder.Configuration)(MMCA.Common.Infrastructure/DependencyInjection.Jobs.cs:37-52) registers the recurring-job runner: it binds theSchedulersection and addsScheduledJobRunneras a hosted service viaTryAddEnumerable(notAddHostedService, so two callers in one process cannot end up with two runners racing for the same job rows, DependencyInjection.Jobs.cs:44-48). Registering it is not the same as turning it on: the runner'sExecuteAsynclogs once and returns whenScheduler:Enabledis false (MMCA.Common.Infrastructure/Scheduling/ScheduledJobRunner.cs:84-90). The runner owns no jobs of its own; jobs areIScheduledJobimplementations contributed separately. The framework ships one,AuditTrailCleanupJob(MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailCleanupJob.cs:45), registered byAddAuditTrailand running daily at 03:00 UTC (CronExpression => "0 3 * * *", AuditTrailCleanupJob.cs:60) to prune the change trail. Conference, Engagement and Identity all callAddScheduledJobs(Conference.Service/Program.cs:266, comment 264-265; Identity 216, Engagement 118).
[Rubric §11, Security] assesses how secrets and key material reach a running process. Vault-backed configuration keeps connection strings and signing keys out of both the repository and the process environment, and a shared, optionally vault-encrypted DataProtection key ring keeps auth cookies portable across replicas. Both are single calls in the framework, so every consumer opts in the same way rather than inventing its own.
One more AI signal is worth noting because ADC's session scorer is its only producer. Conference
needs no subscription of its own: AddServiceDefaults already subscribes every host to the "MMCA.Common.AI" meter and activity source
(AiTelemetryName, used as a meter at
(MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.Telemetry.cs:73 and as an activity source at :117). It carries the
paid-call cost counters mmca.ai.input_tokens and mmca.ai.output_tokens, emitted by the governed chat
client rather than by ADC code and tagged with model, prompt_name, prompt_version and provider
(MMCA.Common/Source/Core/MMCA.Common.AI/Observability/AiUsageMeter.cs:26-32, tags at :161-164).
They replace the former per-service MMCA.ADC.Conference.Scoring meter and its scoring.tokens.*
counters, and the AI spend alert queries the new names (MMCA.ADC/infra/main.bicep:512-546). Reusing
the one name is the point: it is also the governed client's ActivitySource, so one name turns on both
the token metrics and the per-call spans. The tags that move spend are the model (a swap changes the
per-token price) and the prompt version (a revision changes the token count), which is why these
counters are the aggregate a budget alert queries. A background scoring run that exhausts its retries is
no longer counted on a Conference meter: it runs as an internal command
(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sessions/UseCases/DecisionSupport/ScoreEventSessions/ScoreEventSessionsInternalCommand.cs:36),
so the framework's internal_commands.dead_letter.count, tagged reason attempts_exhausted, reports
it
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Processing/InternalCommandMetrics.cs:53-61).
Like the framework meters, the name is a literal (Extensions.Telemetry.cs:43, comment at :34-42) so
MMCA.Common.Aspire does not have to
reference MMCA.Common.AI.
MMCA.Common.Aspire, the framework service-defaults package
Source:
MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.csTags:.../HealthCheckTags.csTelemetry:.../Telemetry/OutboxPollFilterProcessor.csSecurity:.../Security/SecurityHeaders.csWarmup:.../Warmup/Health:.../Health/RedisPingHealthCheck.csGateway building blocks:.../Gateway/
This package is the canonical, and the only, service-defaults implementation. Each ADC service host calls its methods directly; there is no ADC-local copy that shadows or extends it.
AddServiceDefaults<TBuilder>
MMCA.Common.Aspire/Extensions.cs:35-121. The Extensions class is partial: this file holds the
service defaults and the warm-up registration, while the health half lives in Extensions.Health.cs and
the telemetry half in Extensions.Telemetry.cs. Called early in each service's Program.cs,
AddServiceDefaults chains ConfigureOpenTelemetry() (Extensions.cs:37), AddDefaultHealthChecks(),
which adds a "self" check tagged "live" (Extensions.cs:38; Extensions.Health.cs:25-28),
AddWarmupReadiness() (Extensions.cs:39), and Services.AddServiceDiscovery() (Extensions.cs:40). It
then applies a Polly resilience pipeline to every HttpClient (ConfigureHttpClientDefaults,
Extensions.cs:57-119) with 30 s per-attempt / 60 s circuit-breaker sampling / 90 s total-request timeouts
and one retry per hop (Extensions.cs:59-73). That one retry is switched off for POST and PATCH
(Extensions.cs:82): an attempt that timed out may still be running server-side, and most hops carry no
idempotency key, since a server-to-server call never does and the UI's "APIClient" stamps one only on
EntityServiceBase creates and updates, whose replay the UI service base classes own (Extensions.cs:75-78). GET,
PUT, DELETE and the other idempotent verbs keep their retry, which is why the code names the two verbs
instead of calling DisableForUnsafeHttpMethods, a helper that would also switch the retry off for PUT
and DELETE (Extensions.cs:79-81). The retry also waits out a 429's Retry-After only within budget: a 429
asking for longer than MaxRetryAfterWait is not retried, matching the UI service base classes, so a
refused action stays one request rather than a request held for up to a minute (Extensions.cs:84-92).
Finally it installs a SocketsHttpHandler tuned explicitly for Azure Container Apps Consumption plan
(Extensions.cs:109-116):
PooledConnectionLifetime = 10 min, forces connection recycling so DNS changes during ACA replica rollovers are picked up without an app restart.PooledConnectionIdleTimeout = 5 min, keeps idle connections in the pool long enough for low-traffic inter-service calls to reuse them.KeepAlivePingDelay = 60 swithKeepAlivePingTimeout = 30 sunderKeepAlivePingPolicy = HttpKeepAlivePingPolicy.WithActiveRequests(Extensions.cs:113-115), HTTP/2 PING frames sent only while the connection has a request in flight, so a peer that dies during a long call or stream is detected within the ping timeout. An idle connection is never pinged and sends nothing at all, which is what keeps an idle replica on idle-vCPU billing (roughly 8x cheaper than active);PooledConnectionIdleTimeoutalone decides how long it stays pooled (comment at Extensions.cs:101-106).EnableMultipleHttp2Connections = true, avoids a single multiplexed connection becoming a bottleneck under concurrent requests.
None of those numbers are literals here. They all come from HttpResilienceDefaults in
MMCA.Common.Shared (Core/MMCA.Common.Shared/Resilience/HttpResilienceDefaults.cs:13-43), which
exists so the Aspire HTTP defaults and the MMCA.Common.Grpc typed clients cannot drift apart: the
hand-mirrored copies previously did, leaving the gRPC side on the 10 s / 30 s library defaults
(HttpResilienceDefaults.cs:3-9). MaxRetryAttempts is deliberately 1 (HttpResilienceDefaults.cs:28),
because the UI service base classes own the user-facing retries and stacking a full budget at every hop
turned a backend brownout into an up-to-16x request storm (HttpResilienceDefaults.cs:21-27).
Health-check tags, the vocabulary the endpoints filter on
HealthCheckTags.cs defines the three tag literals every check in the framework is classified with:
Live (line 12), Ready (line 18) and Optional (line 32). Reading the doc comment on Optional
(HealthCheckTags.cs:20-31) is the fastest way to understand the whole health model: a distributed cache
sitting behind an in-memory fallback, or a broker behind a retrying outbox, can fail without the app
losing the ability to serve, and gating readiness on it converts a partial degradation into a total
outage because every replica goes unready simultaneously. Leave a check untagged only when the app
genuinely cannot serve correct responses without it, its own database being the standard example. See
HealthCheckTags.
The endpoint paths are declared once alongside the tags, in HealthEndpointPaths
(.../HealthEndpointPaths.cs:11, 14, 17), with an IsProbePath predicate that also matches anything
below /health/ (HealthEndpointPaths.cs:29-33). That single declaration is what keeps the mapping, the
probe-telemetry filters described below and any host bypass list from drifting apart: a probe route
added to MapDefaultEndpoints is automatically a probe route everywhere else
(HealthEndpointPaths.cs:3-7).
Warmup infrastructure
AddWarmupReadiness<TBuilder> (Common.Aspire/Extensions.cs:132-143) registers:
WarmupReadinessGate(singleton), a boolean gate that opens when all warm-up tasks finish.WarmupHostedService, runs all registeredIWarmupTaskimplementations on startup, then opens the gate in afinallyblock (Warmup/WarmupHostedService.cs:58), so a failing task degrades to a slow start rather than a permanently unready replica. Each task is capped at 120 seconds (TaskTimeoutSeconds, WarmupHostedService.cs:42), a backstop rather than a latency budget: the built-in OIDC task is already bounded at 90 s by the resilience pipeline, so a task reaching this limit is one waiting on something that will never arrive (WarmupHostedService.cs:36-41).WarmupReadinessHealthChecktagged"ready"(Extensions.cs:139-140), reports unhealthy until the gate opens. Because it appears on/health/ready(the readiness probe) but not on/alive, ACA ingress holds back user traffic from a replica that is still warming up.OpenIdConnectMetadataWarmupTask, pre-fetches{authority}/.well-known/openid-configuration, where{authority}is theAuthentication:JwtBearer:AuthoritykeyWithJwksDiscoverysets; with that key unset the task returns immediately (Warmup/OpenIdConnectMetadataWarmupTask.cs:32-36). The problem it solves is documented in the class summary (OpenIdConnectMetadataWarmupTask.cs:6-13): on a CPU-throttled idle ACA replica, a lazy metadata fetch on the first request can stretch past the client timeout, producing the "first request fails, second succeeds" pattern. What it warms is narrower than "the connection", and the remarks say so (OpenIdConnectMetadataWarmupTask.cs:14-22): the authority's own discovery-document cache and the host-level DNS path, plus one connection in the task's ownIHttpClientFactoryclient pool (the fetch is at OpenIdConnectMetadataWarmupTask.cs:49-50). The JwtBearerConfigurationManagercaches discovery state separately and fetches through its own default backchannelHttpClient, because noBackchannelorBackchannelHttpHandleris configured, so the first authenticated request still performs its own fetch over a connection of its own. What the warm-up buys is a warmed authority, not a shared warm connection.
Hosts can contribute their own tasks with services.AddWarmupTask<TTask>() (Extensions.cs:155), and
three ADC services do. Identity (Program.cs:135), Engagement (Program.cs:114) and Conference
(Program.cs:262) each register a subclass of the framework's SelfHttpWarmupTaskBase
(Warmup/SelfHttpWarmupTaskBase.cs:28-33), which replays a short list of hot read paths against the
host's own Kestrel endpoint once the server is listening. The OIDC task warms the authority side
of one outbound call; this warms the full inbound path (Kestrel, output cache, routing, authentication,
controller, EF Core, SQL), which is where an idle CPU-throttled replica's cold-start cost actually sits
(SelfHttpWarmupTaskBase.cs:11-15). Two details are load-bearing. The request version defaults to HTTP/2
with RequestVersionExact (SelfHttpWarmupTaskBase.cs:70, 77), because these hosts serve h2c only and
an OrLower policy would downgrade to HTTP/1.1 and fail the warm-up on every startup
(SelfHttpWarmupTaskBase.cs:64-68); and the whole task is skipped under the Testing environment
(SelfHttpWarmupTaskBase.cs:41-46), where WebApplicationFactory's in-memory TestServer opens no
socket for a self-request to reach. The derived class contributes only the path list, and that list has
to match the URLs real callers issue in their values, not just their shape, or a query-keyed output
cache is warmed with an entry nothing ever reads (SelfHttpWarmupTaskBase.cs:51-59).
[Rubric §12, Performance] assesses whether the system is tuned for its hosting environment. The
SocketsHttpHandler tuning and the OIDC warmup task both target the same class of problem: ACA
Consumption plan cold-starts and idle-replica penalties. Solving them in the framework means every
consumer inherits the fix.
ConfigureOpenTelemetry<TBuilder>
MMCA.Common.Aspire/Extensions.Telemetry.cs:101-182. Configures OTel logging (IncludeFormattedMessage +
IncludeScopes, Extensions.Telemetry.cs:103-107), metrics (ConfigureMetrics, Extensions.Telemetry.cs:271-357:
ASP.NET Core, HttpClient, .NET runtime), and tracing (the application's own source plus
"MMCA.Common.Outbox", "MMCA.Common.Messaging", "MMCA.Common.InternalCommands" and the optional AI
package's "MMCA.Common.AI", Extensions.Telemetry.cs:113-117 and 43, with ASP.NET Core and HttpClient instrumentation). Four
MMCA.Common-specific additions stand out:
MMCA.Common meters, eleven of them, from one list (
FrameworkMeterNames, Extensions.Telemetry.cs:61-74, subscribed in a singleAddMetercall at 331)."MMCA.Common.Outbox"(outbox counters and dispatch lag),"MMCA.Common.Cqrs"(RED histograms for command/query handlers plus query cache hit/miss),"MMCA.Common.Idempotency"(the idempotency filter's replay, conflict and degraded counters),"MMCA.Common.Scheduler"(the recurring runner's run outcomes, duration and schedule lag, inert in a host that never setsScheduler:Enabled),"MMCA.Common.Broker"(consumer faults plus outbox circuit-breaker openings, inert on the in-process bus),"MMCA.Common.OutputCache"(the eviction consumer's failed tag evictions),"MMCA.Common.BestEffort"(swallowed failures of best-effort side effects),"MMCA.Common.InternalCommands"(the internal-command queue's completions, dead letters, latency and backlog),"MMCA.Common.Persistence"(the optimistic-concurrency conflicts the API answers),"MMCA.Common.Auth"(password sign-in outcomes) and"MMCA.Common.AI"(the optional AI package's token spend plus call duration, inert until a host adds that package and enablesAi:Enabled) (Extensions.Telemetry.cs:45-55, 327-330). They are literal names because the Aspire package references none of the defining assemblies, and a meter with no publisher in a host is inert, so subscribing all of them costs nothing where a capability is off. The list is a public property rather than an inline chain so a fitness test can hold it equal to the meters the Common packages actually create: a new meter cannot ship unexported (remarks at Extensions.Telemetry.cs:56-60).Polly's own meter (Extensions.Telemetry.cs:338,
PollyMeterName = "Polly"at 30). The standard resilience handler runs on everyHttpClientand every gRPC typed client, so it is the component that decides whether an inter-service call is retried, timed out or refused by an open circuit; until this meter was subscribed none of that left the process, and a brownout looked from the outside exactly like latency (Extensions.Telemetry.cs:333-337, citing ADR-009).OutboxPollFilterProcessoris added to the tracing pipeline (Extensions.Telemetry.cs:155) before the exporters, so itsOnEndruns first (comment at Extensions.Telemetry.cs:148-154).Six cost knobs ([Rubric §31, Cost and FinOps]): four that change nothing until a host sets them, and two whose saving is the default.
Telemetry:DisableHttpClientMetrics(Extensions.Telemetry.cs:282-304) andTelemetry:DisableRuntimeMetrics(Extensions.Telemetry.cs:310-325) each drop a metric family. Both branches are more than "skip the instrumentation call", and the comments explain why (Extensions.Telemetry.cs:284-294 and 312-314): a deployed host also registers the Azure Monitor distro (AddAzureMonitorExporter()fromMMCA.Common.AzurecallsUseAzureMonitor()), and that distro adds theSystem.Net.HttpandSystem.Runtimemeters itself, so skippingAddHttpClientInstrumentationlefthttp.client.open_connectionsas the single largest AppMetrics stream in both production workspaces despite the toggle being on. AMetricStreamConfiguration.DropView applies to the whole MeterProvider regardless of which component added the meter, which is what makes the toggle authoritative instead of advisory (System.Net.NameResolutionrides along because DNS-lookup metrics carry no signal without the rest of the family). The third knob,Telemetry:TracesSampleRatio, installs aParentBasedSamplerover aTraceIdRatioBasedSamplerfor head-based trace sampling (Extensions.Telemetry.cs:171-172). Traces are the largest observability line item while unsampled; once sampled, metrics can outweigh them (Extensions.Telemetry.cs:165-170, pointing at ADR-041). A value outside the open interval (0,1), or one that fails to parse, falls back to "sample everything" rather than silently blinding the host (TryGetTraceSampleRatio, Extensions.Telemetry.cs:213-226; the same defensive shape inIsInstrumentationDisabled, Extensions.Telemetry.cs:236-237). The fourth,Telemetry:FilterProbeTelemetry, is the first of the two that default on and is covered on its own below (IsProbeTelemetryFilterEnabled, Extensions.Telemetry.cs:261-262). A fifth,Telemetry:DisableAspNetCoreMetrics, drops the ASP.NET Core meter family (http.server.*,kestrel.*,aspnetcore.*,signalr.server.*) with the same whole-providerDropView, matched on theMicrosoft.AspNetCore.meter-name prefix, for the same reason: the distro adds those meters on its own (ConfigureAspNetCoreMetrics,MMCA.Common.Aspire/Extensions.Telemetry.cs:368-384). The sixth,Telemetry:EnablePollyDurationMetrics(Extensions.Telemetry.cs:24), is the second default-on saving: unless a host sets it totrue(while debugging a retry storm, say), aDropView removes Polly's two duration histograms,resilience.polly.strategy.attempt.durationandresilience.polly.pipeline.duration(Extensions.Telemetry.cs:348-356). They are per-bucket streams on a pipeline that runs on every outbound call and re-measure whathttp.client.request.durationand the dependency traces already report, while theresilience.polly.strategy.eventscounter (retries, circuit opens and closes, timeouts) is never dropped, because it is the signal the meter exists for (Extensions.Telemetry.cs:340-347). ADC's production Bicep sets four of the first five explicitly:Telemetry__TracesSampleRatio=0.25(MMCA.ADC/infra/main.bicep:326-329, rationale at 322-325),Telemetry__DisableHttpClientMetrics=true(main.bicep:360-363) andTelemetry__DisableRuntimeMetrics=true(main.bicep:364-367), those two measured at roughly 65% of AppMetrics ingestion, about 290 MB of a 500 MB daily stream (main.bicep:353-359), andTelemetry__DisableAspNetCoreMetrics=true(main.bicep:373-376), whose family was 73% of workspace ingestion over 2026-09-22..28 with no alert reading it, since request latency and failures alert offAppRequests(main.bicep:369-372). Alongside them it sets the distro's ownAzureMonitor__EnableLiveMetrics=false(main.bicep:383-386): Live Metrics is on by default and keeps every replica talking to the Live Metrics service with nobody watching, which held every app just above the Container Apps idle line so that 64% of vCPU-seconds billed at the active rate (main.bicep:378-382). All six container apps carry that entry (for example main.bicep:2454 on Identity and 3270 on the gateway). It also stretches the OTel export cadence with the standardOTEL_METRIC_EXPORT_INTERVAL=300000(main.bicep:394-397): the exporter ships cumulative aggregates, so a 5x longer interval drops roughly 80% of the remaining datapoints while five-minute alert windows keep the same signal (main.bicep:388-393). The Bicep sets noTelemetry__EnablePollyDurationMetrics, so production keeps the Polly histograms dropped. An unset host keeps every other metric family, samples every trace and exports on the SDK's 60 second default.
MapDefaultEndpoints
MMCA.Common.Aspire/Extensions.Health.cs:143-179. Maps three endpoints, each at its HealthEndpointPaths
constant rather than a literal, and each declared anonymous explicitly: a host that adopts the framework's
fallback authorization policy would otherwise 401 its own liveness and readiness probes, and a probe that
cannot answer takes the replica out of rotation (Extensions.Health.cs:145-147).
/health(Extensions.Health.cs:154), all checks must pass; used by humans and dashboards./alive(Extensions.Health.cs:156-161), liveness probe:"live"-tagged checks only, so a transient dependency outage (SQL Server down, say) does not mark the process dead and get it killed./health/ready(Extensions.Health.cs:174-176), readiness: everything except"live"-only and"optional"checks. This includes the warmup check (tagged"ready") and any untagged dependency checks, so a replica still in cold-start or with a failing dependency is removed from ACA ingress without being killed. The"optional"exclusion is deliberate and the comment above it (Extensions.Health.cs:168-173) restates the rule fromHealthCheckTags: a dependency the app degrades gracefully without must not gate readiness, or a partial degradation takes every replica unready at once and becomes a total outage. Those checks still surface on/health, so the degradation is visible without being self-inflicted.
/health and /health/ready are served by MapCachedHealthChecks (Extensions.Health.cs:181-207), not by
plain MapHealthChecks: a GET/HEAD endpoint that asks CachedHealthReportProvider for the report,
answers 503 only when the status is Unhealthy (200 otherwise, so Degraded still passes) and writes the
status as text/plain. The provider is a short-TTL, single-flight report cache that
AddDefaultHealthChecks registers next to the "self" check, with HealthReportCacheOptions bound from
configuration and validated at startup (Extensions.Health.cs:30-38). The reason is SEC-Common-71 /
SEC-ADC-17: both paths sit on a rate-limit bypass (see the gateway pipeline below), and that bypass cannot
bound the amplification of an anonymous flood in which every request runs a full round of dependency
probes. The cache can: one probe round per window instead of one per request
(Extensions.Health.cs:149-153). /alive is deliberately left uncached; it runs only the "self" check,
which answers Healthy without touching a dependency (Extensions.Health.cs:28, 156-161).
The checks that carry that "optional" tag come from AddInfrastructureHealthChecks(bool requireDatabase)
(Extensions.Health.cs:76-127), which a host calls separately from AddServiceDefaults; all four
ADC services get requireDatabase: true from AddMmcaServiceHost (MMCA.Common.ServiceHost/ServiceHostBuilderExtensions.cs:106). It registers:
- Relational checks, one per distinct database (
AddDatabaseHealthChecks, Extensions.Health.cs:223-285). Three engines are read, SQL Server, PostgreSQL and SQLite (Extensions.Health.cs:243-245, registered at 257-284), because a host picks its engine from configuration, and both the top-levelConnectionStringssection and every namedDataSourcesentry are scanned (RelationalSources, Extensions.Health.cs:309-363). Deduplication is by connection string, so the entries that collapse onto one physical database contribute one check rather than one per logical name; the first database of each engine keeps the baresqlserver/postgresql/sqlitecheck name and later ones are named{engine}:{entry}(Extensions.Health.cs:319-325, 348, 352-360). None is tagged optional, so every one gates readiness. - Redis, via the framework's own
RedisPingHealthCheck(Extensions.Health.cs:83-101), tagged"optional". The comment at Extensions.Health.cs:86-91 is the postmortem: theAspNetCore.HealthChecks.Redischeck this replaced issuedCLUSTER INFOagainst any server it detected as clustered, which is how StackExchange.Redis 3.x sees Azure Managed Redis (Enterprise tier), and the server refuses that command outside admin mode, so every probe threw against a healthy cache. The replacement issues PING only and is registered as a singleton so the fallback multiplexer is built once rather than per probe. SeeRedisPingHealthCheck. - RabbitMQ (Extensions.Health.cs:103-124), also tagged
"optional", when arabbitmqormessagingconnection string parses as an absolute URI.
The asymmetry is intentional: Redis and RabbitMQ are optional per host, but a host that cannot resolve
any relational database at all is misconfigured, so requireDatabase: true throws at startup instead of
quietly registering no check and reporting healthy (throw at Extensions.Health.cs:247-253).
Dual telemetry export
Two exporters can run, and they come from two packages. AddServiceDefaults enables only the
vendor-neutral one: AddOpenTelemetryExporters (MMCA.Common.Aspire/Extensions.Telemetry.cs:195-204) turns
on OTLP when OTEL_EXPORTER_OTLP_ENDPOINT is present (Extensions.Telemetry.cs:197-203). The Aspire
dashboard sets this automatically; standalone deployments must supply it.
Azure Monitor is an adapter call each host makes itself: AddAzureMonitorExporter()
(MMCA.Common/Source/Hosting/MMCA.Common.Azure.Startup/AzureMonitorExporterExtensions.cs:42-68) calls
UseAzureMonitor() only when APPLICATIONINSIGHTS_CONNECTION_STRING is present
(AzureMonitorExporterExtensions.cs:56-59, 65), injected by the Bicep deployment so logs, metrics, and traces flow
to the workspace-based Application Insights resource (MMCA.ADC/infra/main.bicep:296-312, env entry at
317-320). Keeping the vendor SDK in an adapter package is what lets the core packages stay cloud-neutral, and
two guards keep the split from failing silently:
- Ordering. The call throws unless
AddServiceDefaults()(orConfigureOpenTelemetry()) has already run (AzureMonitorExporterExtensions.cs:44-52), because the outbox-poll and probe filter processors must sit ahead of the exporter's batch processor or the spans they drop are exported anyway. The check runs whether or not the connection string is set, so a misordered host fails on a developer machine rather than only in Azure. All six ADC hosts call it right afterAddServiceDefaults()(for exampleMMCA.ADC.Notification.Service/Program.cs:82-85, reason in the comment at 82-84, via theAfterServiceDefaultscallback thatServiceHostBuilderExtensions.cs:86runs; the Gateway calls it directly atMMCA.ADC.Gateway/Program.cs:82). - Omission. The call registers a marker only when it exports (AzureMonitorExporterExtensions.cs:61-63);
with no connection string at call time it registers nothing, so a connection string that only appears in a
source added later still trips the check (comment at 54-55). The core startup tripwire fails a host that
has
APPLICATIONINSIGHTS_CONNECTION_STRINGset without that marker, naming the missing call (MMCA.Common.Aspire/Integrations/HostIntegrationTripwire.cs:93-94), instead of letting it start with no telemetry export.
Both can be active simultaneously; each exports an independent copy.
[Rubric §13, Observability and Operability] assesses whether a running system can be understood from the outside. Dual export means local runs use the lightweight Aspire dashboard (no Azure subscription required) while the same binary, with a different environment variable, ships telemetry to Application Insights in production. The switch is purely environment-driven; no code path changes.
OutboxPollFilterProcessor
MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Telemetry/OutboxPollFilterProcessor.cs
This OpenTelemetry BaseProcessor<Activity> (OutboxPollFilterProcessor.cs:17) drops recurring background
poll spans from export. The OutboxProcessor background service polls every relational outbox table on a
recurring cycle (2 s framework default,
Core/MMCA.Common.Infrastructure/Persistence/Outbox/Administration/OutboxSettings.cs:36; deployed environments set 300 s).
Without filtering, those idle polls would dominate Application Insights ingestion, both by span count
and by spawning SqlClient dependency spans when the Azure Monitor distro's auto-instrumentation is
active (OutboxPollFilterProcessor.cs:6-16). The InternalCommandProcessor polls every internal-command
queue table the same way, so its idle polls are dropped by the same processor for the same reason
(OutboxPollFilterProcessor.cs:9-12).
The processor walks the in-process parent chain in OnEnd (OutboxPollFilterProcessor.cs:32-53),
matching spans on source and operation name together: "MMCA.Common.Outbox" with "OutboxPoll", or
"MMCA.Common.InternalCommands" with "InternalCommandPoll" (OutboxPollFilterProcessor.cs:26-29).
Matching on both avoids suppressing an unrelated consumer span that happens to share a poll's name
(OutboxPollFilterProcessor.cs:40-41). When a match is found it clears the ActivityTraceFlags.Recorded
flag (line 49), which tells the batch export processors to skip the span. It is registered before the
exporters (MMCA.Common.Aspire/Extensions.Telemetry.cs:155) so its OnEnd runs before the batch
processors check the flag. A null activity returns early rather than throwing, because a telemetry
callback must never throw (OutboxPollFilterProcessor.cs:34-38).
Real work is unaffected: per-message OutboxProcess and per-command InternalCommandExecute spans
restore explicit parent contexts from the stored trace IDs and are never descendants of a poll span
(OutboxPollFilterProcessor.cs:12-15).
The four name constants (OutboxPollFilterProcessor.cs:26-29) are deliberately duplicated from
MMCA.Common.Infrastructure; the comment explains that the Aspire package's only ProjectReference is
MMCA.Common.Shared (for HttpResilienceDefaults), so AddServiceDefaults stays usable from a host
that does not take the persistence stack (OutboxPollFilterProcessor.cs:19-25).
[Rubric §31, Cost and FinOps] assesses whether observability costs are controlled. Suppressing poll
spans on a 300 s polling interval in production (Outbox__PollingIntervalSeconds=300 on all four ADC
container apps, MMCA.ADC/infra/main.bicep:2472, 2760, 2913, 3089) eliminates the majority of
idle-process telemetry ingestion. The framework makes this the default for every consumer; individual
services do not need to configure it.
Probe telemetry filtering
MMCA.Common.Aspire/Telemetry/ProbeTelemetryFilter.cs and .../ProbeTelemetryFilterProcessor.cs
The outbox poll is not the only span nobody asked for. Container Apps liveness and readiness probes,
the gateway's downstream-{name} aggregate probes, YARP's active health checks and the outside-in
availability web test between them accounted for every AppRequests row in both production
workspaces, and their children (the health check's SQL SELECT 1, the Redis PING, the gateway's
HttpClient call to each backend's /alive) for most of the AppDependencies rows
(ProbeTelemetryFilter.cs:6-11, ProbeTelemetryFilterProcessor.cs:6-12). None of it carries end-user
signal, and none of it is touched by Telemetry:TracesSampleRatio, because proportional sampling keeps
a proportion of exactly the traffic you did not want (MMCA.Common.Aspire/Extensions.Telemetry.cs:119-130).
The knob is Telemetry:FilterProbeTelemetry and it is the one that defaults to on: absent, blank or
unparseable all mean "filter", and only an explicit false turns it off, for a host debugging its own
probes (IsProbeTelemetryFilterEnabled, Extensions.Telemetry.cs:261-262, rationale at 127-128). Enabled, it
installs two halves:
- Instrumentation predicates (Extensions.Telemetry.cs:131-146).
ShouldCollectRequestrefuses an inbound request whose pathHealthEndpointPaths.IsProbePathmatches (ProbeTelemetryFilter.cs:40-55) andShouldCollectOutgoingrefuses an outbound call to a probe path (ProbeTelemetryFilter.cs:62-63). Both configure the DEFAULT-named instrumentation options, which is why they are authoritative without a View, unlike the metric toggles (Extensions.Telemetry.cs:134-136). The outbound half exists because the gateway'sDownstreamServiceHealthCheckcalls and YARP's active checks are driven by background timers and are nobody's descendants, so a processor would never see them (ProbeTelemetryFilter.cs:20-25). ProbeTelemetryFilterProcessor(Extensions.Telemetry.cs:162), registered under the same condition and, like the outbox processor, before the exporters. It walks the in-process parent chain and unrecords any span sitting under a probe request (ProbeTelemetryFilterProcessor.cs:42-64), because the probe's children are sampled independently of the request the predicate just refused.
The load-bearing detail is how the two halves talk to each other. When ShouldCollectRequest refuses a
request, the ASP.NET Core instrumentation returns before writing url.path, so the descendants would
have no way to recognize their own probe ancestor. The predicate therefore stamps a mmca.probe tag on
the server activity on its way out (ProbeTelemetryFilter.cs:33, 49-52), and that tag is the processor's
first match test (ProbeTelemetryFilterProcessor.cs:68-71). It falls back to url.path, http.route and
the route portion of the display name (ProbeTelemetryFilterProcessor.cs:76-79, 89-93) for the case where
an exporter-side enricher has already consumed the tags. The match is server-kind only, so a normal
request never loses its whole subtree because one dependency happened to be a probe
(ProbeTelemetryFilterProcessor.cs:73-76). The pass runs at both OnStart and OnEnd
(ProbeTelemetryFilterProcessor.cs:29, 40): clearing Recorded at end is what keeps the span out of the
exporters, while the start pass additionally stops the instrumentation from enriching data it will never
export, and running only at start would depend on callback ordering this processor does not control
(ProbeTelemetryFilterProcessor.cs:32-39).
Metrics are deliberately untouched. http.server.request.duration, the Kestrel instruments and the
routing instruments keep flowing, so probe traffic stays visible on dashboards and only the per-request
trace rows stop being billed (ProbeTelemetryFilterProcessor.cs:15-17).
[Rubric §13, Observability and Operability] assesses whether the signal a system emits is usable.
Filtering here is not "less telemetry", it is a better ratio: the rows that remain in AppRequests are
now requests a user made. [Rubric §31, Cost and FinOps] gets the other half, and note the default
direction: the three metric-family knobs are opt-in because dropping a metric family is a judgement call, while
this one is opt-out because probe chatter is ingestion no host wants billed.
Security headers
MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Security/SecurityHeaders.cs provides
SecurityHeadersMiddleware (line 147) and SecurityHeadersExtensions (line 258). The middleware sets
X-Content-Type-Options: nosniff (line 191), X-Frame-Options (default DENY, line 191 and settings
line 25), Referrer-Policy (strict-origin-when-cross-origin, line 28), Permissions-Policy (line 31),
HSTS outside Development (lines 34 and 50-51, applied at 175 and 214-216), and a Content-Security-Policy resolved from
ICspPolicyProvider (lines 219-239).
The default static policy is a complete hardened baseline, not a minimal one (SecurityHeaders.cs:53-69):
default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline';
object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'
It ships script-src and style-src at exactly the strength Blazor ('wasm-unsafe-eval') and MudBlazor
('unsafe-inline' styles) require, so an HTML host that never registers a provider still gets a
functional policy instead of one silently missing both directives, while the JSON, WebSocket and static
responses of API and Gateway hosts are unaffected (SecurityHeaders.cs:59-62). A host needing something
stricter configures the SecurityHeaders section or registers its own ICspPolicyProvider; the
supported path off 'unsafe-inline' is the {nonce} placeholder, which the middleware replaces with a
freshly generated 16-byte value per request and also stashes in HttpContext.Items under
CspNonce.ItemKey before the pipeline runs, because the page render is what stamps it onto its tags
(SecurityHeaders.cs:110-117, 134-138, 222-230). Consumers call AddCommonSecurityHeaders() (line 268)
and UseCommonSecurityHeaders() (line 296); the ADC UI gets both through
AddMmcaBlazorWebHost (BlazorWebHostExtensions.cs:157, 185) with EnableHsts at its default, and its Program
(UI.Web/Program.cs:102) deliberately never calls the built-in UseHsts(), which would overwrite the shared one-year value with a 30-day default.
The same package also ships AddCommonGatewayCors
(MMCA.Common.Aspire/GatewayCorsExtensions.cs:24 onward), which the ADC Gateway calls
(Gateway/Program.cs:140). It is deliberately looser than MMCA.Common.API's allow-list version, because a
reverse proxy has to pass arbitrary client headers through: allow-any in Development
(GatewayCorsExtensions.cs:34-40), and in every other environment the origins from Cors:AllowedOrigins
with any header/method plus credentials (GatewayCorsExtensions.cs:44-53).
MMCA.Common.Aspire.Hosting, the AppHost extensions package
Source:
MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/Files:Extensions.cs,BrokerSelection.cs,ServiceInfrastructureExtensions.cs,GatewayUiExtensions.cs,IdentityLinkExtensions.cs,ServiceTokenExtensions.cs,MmcaReplicas.cs,ServiceEndpointProfile.cs,H2cHealthCheckExtensions.cs,H2cEndpointHealthCheck.cs,ServiceBusEmulatorResource.cs
This package lives in a separate assembly from MMCA.Common.Aspire so running services do not pull in
the full Aspire.Hosting package (Common.Aspire.Hosting/Extensions.cs:13-17 class comment). Extensions.cs
and its sibling files export the extension methods the AppHosts that orchestrate extracted microservices are composed from, and
H2cHealthCheckExtensions.cs adds the h2c probe. It exposes no gRPC API at all: gRPC peers are wired
with stock Aspire WithReference, as shown above.
Builder-level resource helpers
AddMailDev(name = "maildev")(Extensions.cs:201-209). The MailDev container with a persistent lifetime and the two fixed host ports, covered above.AddMessageBroker(name = "rabbitmq")(Extensions.cs:220). Wrapsbuilder.AddRabbitMQ(name).WithManagementPlugin(). The management plugin is always enabled for local debug.AddServiceBusEmulatorBroker(sqlServer, name = "servicebus")(Extensions.cs:261-298). The official Azure Service Bus emulator container. Both planes are published because the emulator serves two: AMQP on container port 5672 carries every publish and consume, and the HTTP management plane on 5300 is what the framework's Azure Service Bus transport provisions topology through (ServiceBusEmulatorResource.cs:34-44). The image tag floor is 2.x for that exact reason: the admin plane shipped in 2.0.0, and the transport provisions its whole topology when its receiver starts, so a silent downgrade to a 1.x image would leave the broker unusable rather than merely older (Extensions.cs:136-150, tag2.0.1). Host ports are left dynamic because nothing outside the stack dials these (Extensions.cs:247-248), andACCEPT_EULA=Yis set explicitly because the emulator refuses to start without it (Extensions.cs:284-287). No health check is declared, so aWaitForgates on the container running rather than on warm-up finishing; the consuming service absorbs the remainder because the transport's receiver provisions and connects in the background, retrying, rather than failing host startup (ServiceBusEmulatorResource.cs:25-30). SeeServiceBusEmulatorResource.
WithBroker<TResource>, two overloads
Extensions.cs:312-322 (RabbitMQ) and 341-353 (emulator). Each chains
WithReference(broker).WaitFor(broker) plus the provider environment variable, so a single call is the
complete wiring for a broker-aware service: service discovery, health-based wait, and the variable that
AddBrokerMessaging() reads to select the transport. The emulator overload adds the connection string
and the management-plane address. The UseDevelopmentEmulator=true suffix on that connection string is
the marker the Azure Service Bus transport (AddAzureServiceBusTransport() from MMCA.Common.Azure,
AzureServiceCollectionExtensions.cs:156, which the service must register) keys its emulator branch off,
and a real Azure Service Bus connection string never carries it, so the emulator path cannot be entered
by accident (Extensions.cs:332-336).
WithJwksDiscovery<TResource>
Extensions.cs:370-398. Injects Authentication__JwtBearer__Authority pointing to the gateway's HTTPS
endpoint (when a gateway is passed) or Identity's HTTPS endpoint (fallback, Extensions.cs:393-395). The
routing-through-gateway rationale is in the method comment (Extensions.cs:382-392): Identity runs
Http2-only, so the default HTTP/1.1 backchannel is rejected; the gateway terminates TLS, speaks ALPN,
and routes /.well-known/* to Identity over h2c. The method also calls
WithReference(identity).WaitFor(identity) (Extensions.cs:377-379). That WaitFor is easy to miss and
it shapes the startup graph: all three non-Identity ADC services wait on Identity because they call
WithJwksDiscovery; Conference has no other wait on Identity, while Notification and Engagement also carry an explicit one on their gRPC edge (AppHost Program.cs:266, 272).
WithE2eRsaKeys
Extensions.cs:414-429. Reads E2E_JWT_PRIVATE_KEY_PEM / E2E_JWT_PUBLIC_KEY_PEM from the AppHost's own
process environment and, only when both are non-blank, maps them onto Jwt__RsaPrivateKeyPem,
Jwt__RsaPublicKeyPem and Jwks__RsaPublicKeyPem on the Identity resource. Without the forwarding
every CI login and register fails with "No supported key formats were found" and the readiness gate
times out (Extensions.cs:409-411). Both ADC (AppHost/Program.cs:230) and Store
(MMCA.Store/Source/Hosting/MMCA.Store.AppHost/Program.cs:200) call it, which is why it lives in the
framework rather than in either AppHost.
The two E2E lifts
Both are parameterless and read their triggers from the AppHost's own environment, returning the
resource untouched when no trigger fires. The trigger names, the target settings and the lifted values
all live in the framework, so a consuming AppHost writes one line per lift. The shared trigger is
E2eLiftTriggerVariable = "E2E_LIFT_REGISTRATION_THROTTLE" (Extensions.cs:43), and ADC's comment records
that a forced-WASM run implies it for local runs (AppHost Program.cs:403-407).
WithE2eRegistrationThrottleLift()(Extensions.cs:456) setsLoginProtection__MaxRegistrationsPerIpPerHourtoE2eRegistrationsPerIpPerHour(1000, Extensions.cs:36), lifted from the production default of 10. An E2E suite registers far more than ten accounts from a single localhost IP, so the production default refuses every register test past the tenth and the failures look like broken registration rather than the anti-abuse control doing its job. It also lifts the service's per-IPauth-iplimiter (E2eAuthIpPermitLimit, 100000, Extensions.cs:94), because with passkeys offered each login-page visit spends one permit on the options call before the login spends another (AppHost Program.cs:418-421).WithE2eGatewayRateLimitLift()(Extensions.cs:548-569) lifts three gateway values:GatewayRateLimiting__PermitLimitto 100000 (E2eGatewayPermitLimit, Extensions.cs:75),GatewayRateLimiting__GlobalConcurrencyLimitto 10000 (line 81), and theauth-tightroute policy'sPermitLimitto 100000 (line 87), set by the threeWithEnvironmentcalls at Extensions.cs:560-568. The whole E2E suite arrives from one loopback client IP, so the per-IP window that protects production from a single-source flood reads the suite itself as that flood (2026-08-18 ADC run 32185349945: 12 login failures once the window saturated), and the anti-credential-stuffingauth-tightpolicy has the same problem for the same reason. The keys are built from constants that mirror the settings types rather than referencing them (GatewayRateLimitingSectionat line 112,MmcaGatewaySectionat line 119,AuthTightPolicyNameat line 126), because this AppHost-tier package must not pull in the service-defaults graph to spell one configuration key.
ADC and Store call both the same way, parameterless (MMCA.ADC/Source/Hosting/MMCA.ADC.AppHost/Program.cs:422
and 429; MMCA.Store/Source/Hosting/MMCA.Store.AppHost/Program.cs:348 and 357), leaving the
environment as the only trigger. A silent regression here surfaces as login and register E2E reds,
never as a build failure.
WithH2cHealthCheck
H2cHealthCheckExtensions.cs:111-138, covered in full in the health-gating section above. The point to
carry away is that it is the AppHost-side counterpart of the Http2-only Kestrel profile: without it,
a WaitFor edge into an h2c service silently degrades to "the process started", which is precisely the
condition that lets a dependent resource race a service that has not finished migrating, seeding or
warming up (H2cHealthCheckExtensions.cs:13-21). See
H2cHealthCheckExtensions.
The data-source helpers
WithSQLServerDataSource (Extensions.cs:587-598), its PostgreSQL peer WithPostgreSQLDataSource
(617-628), WithCosmosDataSource (646-658) and WithSqliteDataSource (671-682), covered in the AppHost
section above.
The composition helpers
The rest of the package is the wiring every gateway-fronted AppHost repeats, one call each, all walked
through in the AppHost section above: AddSelectedBroker and WithSelectedBroker
(BrokerSelection.cs:58, 82), WithMmcaServiceInfrastructure (ServiceInfrastructureExtensions.cs:57)
over the ServiceEndpointProfile enum (ServiceEndpointProfile.cs:7), WithMmcaGateway, WithMmcaUi
and WithGatewayApiEndpoints (GatewayUiExtensions.cs:40, 88, 128), WithUiLinks and WithIssuer
(IdentityLinkExtensions.cs:74, 100), AddServiceTokenSigningKey and WithServiceTokenSigningKey
(ServiceTokenExtensions.cs:46, 67), MmcaReplicas.FromEnvironment and WithMmcaReplicas
(MmcaReplicas.cs:33, 63), and the two UI render-mode switches WithE2eForceServer and
WithE2eForceWebAssembly (Extensions.cs:490, 514). The Store AppHost is composed from the same calls
(MMCA.Store/Source/Hosting/MMCA.Store.AppHost/Program.cs:74, 162, 320, 367, 380).
The six Dockerfiles
All six Dockerfiles share the same multi-stage structure (base, build, publish, final) and
the same digest-pinned base images, and each builds either of the two framework lines the repo carries (Store's five images, with no Notification service, build net10.0 only: MMCA.Store/Source/Hosts/MMCA.Store.Gateway/Dockerfile:1-7).
None build the AppHost: it is a local-only orchestration artifact, never deployed.
Common structure
The framework line is a build argument. Each file declares ARG MMCA_NET=net11.0
(Gateway.Dockerfile:5): net11.0 is production and net10.0 the permanent second line, selected with
--build-arg MMCA_NET=net10.0, which deploy.yml passes from its runtime input
(Gateway.Dockerfile:1-4, deploy.yml:1514-1521). That one argument picks the runtime base image and,
through the MmcaNet environment variable in the build stage, the target framework and the lock-file set.
Stage base: one runtime stage per line, base-net11.0 on
mcr.microsoft.com/dotnet/aspnet:11.0-resolute-chiseled-extra and base-net10.0 on
aspnet:10.0-noble-chiseled-extra, each pinned by digest (Gateway.Dockerfile:16, 18), with
FROM base-${MMCA_NET} AS base choosing between them (Gateway.Dockerfile:20), then WORKDIR /app and
EXPOSE 8080, the one port the gateway binds (Gateway.Dockerfile:24). Each image exposes exactly the ports its host binds: the UI image 8080 too (UI.Web.Dockerfile:24), the three h2c services 8080 plus their 8081 probe listener (MMCA.ADC.Identity.Service/Dockerfile:26-27), and Notification 8080, its 8081 gRPC endpoint and its 8082 probe port (MMCA.ADC.Notification.Service/Dockerfile:29-31). BuildKit builds only the stage the final image
descends from, so the other line's base image is never pulled (Gateway.Dockerfile:7-11). The digest is
the point of each FROM: the tag still names the channel, but the digest is what resolves, so a
re-tagged tag cannot silently change the runtime under a rebuild. The images are chiseled: no shell,
package manager or coreutils in the runtime image, and non-root by default; the -extra variant keeps
ICU and tzdata, which the es culture and the event time zones need, and SkiaSharp's
NativeAssets.Linux.NoDependencies removes any fontconfig requirement (Gateway.Dockerfile:12-14). The
human-readable versions (11.0.0 and 10.0.15 for aspnet, 11.0.100 for the SDK) live in the comment
directly above each FROM, because a Dockerfile comment has to sit on its own line, and each is bumped
together with its digest (Gateway.Dockerfile:15, 17, 26).
Stage build: a single mcr.microsoft.com/dotnet/sdk:11.0 image, digest-pinned for the same reason,
because the .NET 11 SDK builds both framework lines (Gateway.Dockerfile:26-28). It re-declares
ARG MMCA_NET (an ARG before the first FROM is visible to FROM lines only) and promotes it to
ENV MmcaNet, which MSBuild reads as the MmcaNet property, so restore and publish need no -p: flag
(Gateway.Dockerfile:30-33). The stage restores the MMCA.Common.* packages from GitHub Packages, and the
token is a BuildKit secret, never a build argument: each restore step is
RUN --mount=type=secret,id=github_token and reads /run/secrets/github_token into GITHUB_TOKEN for
that one command (Gateway.Dockerfile:55-57). The header comment says why: an ARG promoted to ENV
lands in image layers, the build cache, and docker history (Gateway.Dockerfile:34-36). CI therefore
hands it over as a github_token secret (deploy.yml:1536-1537), not a --build-arg.
Restore runs in locked mode wherever a lock file exists. The gateway copies both lock files
alongside its .csproj: packages.lock.json belongs to the net11.0 line, and on net10.0
Directory.Build.props points NuGetLockFilePath at packages.net10.0.lock.json instead
(Gateway.Dockerfile:47-52). Both travel because --locked-mode with the selected lock file absent does
not fail: it restores unlocked and writes a fresh one (Gateway.Dockerfile:50-51). With them in place the
restore passes --locked-mode (Gateway.Dockerfile:57), and the four service images do the same against
their own project (MMCA.ADC.Identity.Service/Dockerfile:59-61). That turns the image build into a
reproducible restore: a transitive version that moved since the lock was written fails the build instead
of quietly shipping. The UI image follows the same rule: each of its eight project files travels with
both of its lock files (UI.Web.Dockerfile:48-55), and its restore of MMCA.ADC.UI.Web passes
--locked-mode (UI.Web.Dockerfile:57-65). That works because Directory.Build.props enables lock files
for every project, the Blazor WASM subtree (MMCA.ADC.UI.Web + MMCA.ADC.UI.Web.Client) included: its
comment records that the NETSDK1124 trimming-evaluation failure which once kept that subtree out no longer
reproduces, and that a locked package-mode publish of UI.Web passes on both framework lines
(MMCA.ADC/Directory.Build.props:73-77). The publish
restore is never locked in any of the six, and the comment is explicit about why: publish is RID-specific
(linux-x64, inferred for ReadyToRun) while the committed lock files are RID-agnostic, so locked mode
fails there with NU1004 (Gateway.Dockerfile:82-86). The restore step above it is the locked gate.
There is deliberately no dotnet build step in any of the six. The comment records the measurement
(CI run 30115729720, 2026-07-24, Gateway.Dockerfile:64-68): a build stage emitted bin/Release/<tfm>/
while the ReadyToRun publish emits bin/Release/<tfm>/linux-x64/, so publish never reused the build
output and every image compiled twice, about 75 s of waste per image. Publish does its own restore and
build.
Stage publish: runs dotnet publish ... -o /app/publish /p:UseAppHost=false against the same
project, with the same secret mount because publish performs its own restore pass
(Gateway.Dockerfile:87-89). The four services and the Gateway add /p:PublishReadyToRun=true so cold
starts on fractional-vCPU containers skip first-request JIT (Gateway.Dockerfile:79-80, 89;
MMCA.ADC.Identity.Service/Dockerfile:82-83, 92); the UI image does not, and its comment notes that
without R2R the publish reuses the same obj/ path a build step would have produced
(UI.Web.Dockerfile:70-72, 81-84). Every publish also passes -p:RunAnalyzers=$RUN_ANALYZERS, an
argument declared in the publish stage only, so its value never invalidates the build stage's restore
layer, and defaulting to true (Gateway.Dockerfile:74-78, 89). deploy.yml passes false on main
and true from any other ref (deploy.yml:1516-1521), because a squash merge onto an up-to-date branch
means the PR jobs already ran the analyzers at error severity on this exact tree; source generators run
either way (Gateway.Dockerfile:69-70, 74-77). The analyzer gate (TreatWarningsAsErrors,
AnalysisMode=All) therefore lives in the PR jobs, and the image build on main does not pay for it a
second time.
Stage final: COPY --from=publish /app/publish . into the base layer
(Gateway.Dockerfile:91-93), sets ASPNETCORE_ENVIRONMENT=Production (line 94), and then drops
privileges with USER $APP_UID (Gateway.Dockerfile:104, UI.Web.Dockerfile:98,
MMCA.ADC.Identity.Service/Dockerfile:106). APP_UID (1654) and its matching non-root app user come
from the aspnet base image. Nothing in these images writes to the container filesystem at runtime: the
Gateway, for one, registers no Serilog file sink at all, because unlike the service hosts it never
calls AddCommonSerilog and logs through the default console and OpenTelemetry providers
(Gateway.Dockerfile:95-100); the UI's Serilog rolling file sink is skipped in Production
(UI.Web.Dockerfile:90-94); and the DataProtection key ring, where configured, lives in blob storage. Read
and execute on the root-owned /app payload is all the runtime needs. Every port the hosts bind is 8080
or higher, outside the privileged range a non-root user cannot bind. The line is kept last in the
final stage on purpose: the build and publish stages still need write access to /src and the NuGet
folder (Gateway.Dockerfile:101-103). The ENTRYPOINT form of the dotnet invocation closes each file.
Gateway Dockerfile
MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/Dockerfile
The build stage copies only the gateway's .csproj and its two lock files before restoring
(Gateway.Dockerfile:52), then copies the full Source/ tree before publishing
(Gateway.Dockerfile:62). The comment at lines 59-61 explains why the full tree is needed:
Directory.Build.props links GlobalUsings.IdentifierType.cs from each module's Shared project, so
the source tree must be present even though the gateway itself references no module projects. The
gateway has minimal NuGet dependencies (MMCA.Common.Aspire, Azure.Startup, Gateway and YARP, per the
comment at Gateway.Dockerfile:46); the partial restore approach is feasible, and the lock files
travelling with the project file are what let that restore run --locked-mode
(Gateway.Dockerfile:47-51, 57).
Entrypoint: dotnet MMCA.ADC.Gateway.dll (Gateway.Dockerfile:105).
UI (Blazor Web) Dockerfile
MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Dockerfile
The build stage copies the solution file (UI.Web.Dockerfile:43) and then eight .csproj files
individually, each with its packages.lock.json and packages.net10.0.lock.json, before restoring in
locked mode (UI.Web.Dockerfile:48-55, 65): three *.Shared projects, three *.UI
projects, and the two web host projects (MMCA.ADC.UI.Web + MMCA.ADC.UI.Web.Client). This is a
layer-caching optimization: a change in a source file does not invalidate the restore cache. After
restoring, the full Source/ tree is copied (UI.Web.Dockerfile:68) and the publish stage builds it.
Entrypoint: dotnet MMCA.ADC.UI.Web.dll (UI.Web.Dockerfile:99).
Four service Dockerfiles
MMCA.ADC/Source/Services/MMCA.ADC.{Identity,Conference,Engagement,Notification}.Service/Dockerfile
All four are identical in structure; the line numbers below are the Identity file's (Notification's sit a few lines lower, because its image exposes three ports). Each opens with a pinned BuildKit
frontend, # syntax=docker/dockerfile:1.29.0@sha256:... (line 1), pinned by tag and digest for the
COPY --parents the restore layer relies on, rather than whatever frontend the daemon happens to bundle;
a parser directive must be the first line, so its version note sits below it (lines 2-4). The restore
layer copies only what restore reads: every project file under Source/ and both lock files beside each
one, with --parents keeping each file at its path (line 56). Services reach most of the tree through
project references (each Migrations project to its own module Infrastructure), so the set is wide, but a
change to source files alone leaves that layer and the restore below it cached; only a project, lock or
build-configuration change busts it (lines 49-55). Each service then restores its own .Service.csproj
in locked mode (lines 59-61), copies the full Source/ tree for publish because Directory.Build.props
links each module's GlobalUsings.IdentifierType.cs (lines 62-65), and publishes with ReadyToRun
(lines 90-92); all four drop to USER $APP_UID on line 106 and carry their entrypoint on line 107:
dotnet MMCA.ADC.Identity.Service.dlldotnet MMCA.ADC.Conference.Service.dlldotnet MMCA.ADC.Engagement.Service.dlldotnet MMCA.ADC.Notification.Service.dll
[Rubric §17, DevOps and Deployment] continues: having one Dockerfile per deployable means each image
is independently versioned and deployed. CI declares all six as a six-way parallel matrix
(.github/workflows/deploy.yml:1461-1482), gated as a whole on the changes job classifying the diff as
code (deploy.yml:1452), and each leg additionally carries a changed column from that job's per-image
dirty map (deploy.yml:1467, 1470, 1473, 1476, 1479, 1482). A leg whose image is clean skips the build and
push (deploy.yml:1509) and re-tags the last :latest to this sha instead
(deploy.yml:1557-1570), a registry-side az acr import manifest copy that pulls and pushes no layer
(deploy.yml:1566-1570), so it still concludes success: the comment above the job
(deploy.yml:1443-1447) records why that matters, since deploy gates on the job-level
needs.build-images.result == 'success' equality (deploy.yml:1692) and a skipped leg would turn the
whole job skipped and silently cancel the deploy. The UseAppHost=false publish flag strips the native
executable wrapper; the Docker entrypoint invokes the DLL directly via the already-present runtime in the
base image.
A dirty leg builds with docker/build-push-action on a Buildx builder, because the default docker
driver cannot import or export a layer cache and every leg starts on a fresh runner with an empty local
cache (deploy.yml:1501-1505). The cache lives in the ACR the job already authenticates to, mode=max,
one ref per image and framework line (deploy.yml:1546-1547). The comment gives the reasons: the GitHub
Actions cache has a hard 10 GB per-repo quota with LRU eviction that six multi-stage SDK images would
thrash; max is required because the expensive restore and publish layers sit in the build stage, which
min does not cache; and the per-line ref keeps a rollback build from reading or overwriting the
production line's layers (deploy.yml:1538-1545). The leg always pushes the sha tag and pushes :latest
only on a net11.0 build, so a net10.0 rollback build never moves the tag a later clean leg copies
from (deploy.yml:1523-1530).
The same clean leg then copies the fresh sha tag back onto :latest (deploy.yml:1579-1583). That
second copy exists because of the registry's own housekeeping: the daily ACR purge task keeps only the
three most recently updated tags per repository and deletes anything older than three days, and minting
a sha tag never touches :latest, so after a few deploys that leave an image clean the very tag the
re-tag reads from would age out, get purged, and fail the next clean leg, which blocks the whole deploy
through the same success equality (deploy.yml:1571-1578). Copying the identical digest moves only the
tag's timestamp; the build-and-push leg already pushes :latest on every net11.0 build, so both legs
keep it alive.
Every leg, built or re-tagged, then pins the image digest this run produced (deploy.yml:1592-1614).
The comment gives the reason: the sha tag is mutable, so anyone holding AcrPush could re-point it
between this job and the rollout, and Container Apps would pull whatever it names (deploy.yml:1585-1591).
A built leg takes the digest build-push-action reports for the manifest it pushed (the build step
carries id: build for this, deploy.yml:1508), a re-tagged leg reads the digest the az acr import
just wrote with az acr repository show (deploy.yml:1602-1606), and anything that is not a
sha256: digest fails the leg rather than fall back to the tag (deploy.yml:1607-1610). Matrix legs
cannot publish per-leg job outputs reliably, so each leg hands its digest on as a one-line
image-digest-{image} artifact kept for one day, with if-no-files-found: error
(deploy.yml:1616-1622). The deploy job downloads all six (deploy.yml:1712-1719) and builds every
image parameter for main.bicep as {acr}/{image}@{digest}, refusing to deploy by tag when a digest is
missing or malformed (deploy.yml:1809-1826, 1841-1846).
Each leg ends with a container-image CVE scan of that exact digest, so the scanned image is the
deployed image (deploy.yml:1589-1590): Trivy
against {acr}/{image}@{digest}, table format, CRITICAL,HIGH, ignore-unfixed: true, exit-code: '1'
(deploy.yml:1643-1650). It exists because the supply-chain job's CycloneDX SBOM and
dotnet list --vulnerable cover the managed NuGet graph only, so nothing else inspects the OS layer
(openssl, zlib, the ICU tail) of any of the six images (deploy.yml:1624-1626). It runs on every leg, the
re-tagged clean images included: their content has not changed but the vulnerability database has, so
re-scanning is what catches a CVE disclosed after the image was built (deploy.yml:1628-1630). It is a
deploy gate (ADR-093): the step carries no continue-on-error, so a fixable CRITICAL/HIGH finding
fails the leg, and because deploy needs build-images, nothing rolls out (deploy.yml:1632-1633). The
gate was switched on only after the baseline was observed clean: all six chiseled images scanned 0 OS
and 0 dotnet-core CRITICAL/HIGH findings on the v1.277.0 deploy (deploy.yml:1633-1634). Because the
bases are digest-pinned (Gateway.Dockerfile:16, 18, 28), a CVE disclosed against a pinned digest reds
every deploy until the digest is bumped, and the comment states that this is the intent, with two
deliberate exits: bump the base-image digest to a patched one (the normal fix), or accept a specific CVE
in a repo-root .trivyignore, one line per id with a written justification and a review date above it
(deploy.yml:1635-1639). A failure of the action itself (an ACR pull, a vulnerability-database download)
also fails the leg, and the instruction is to re-run the failed job rather than bypass the gate;
ignore-unfixed: true stays because a CVE with no fixed package version is not actionable inside a
deploy (deploy.yml:1640-1642).
[Rubric §32, Dependency and Supply-Chain] assesses whether what ships is known, pinned and checked. The
digest-pinned bases, the --locked-mode restores in all six images, the BuildKit-secret token
and the per-image Trivy scan of the digest the deploy then rolls out are four independent halves of that: what the image is built from is
pinned, what it restores is pinned, the credential never lands in a layer, and the assembled image is
inspected before the deploy job points a container app at it.
Local-to-cloud parity
The AppHost topology maps directly to the Azure infrastructure provisioned by infra/main.bicep. The
table below cross-references the local resource with its Azure equivalent:
| Local (AppHost) | Azure (Bicep) |
|---|---|
| SQL Server container (persistent) | Azure SQL Server; the same four databases (ADC_Identity, ADC_Conference, ADC_Engagement, ADC_Notification, main.bicep:1428-1433), each Basic 5 DTU / 2 GB (main.bicep:1445-1451) outside conference mode, with conferenceMode lifting the attendee hot-path pair ADC_Conference and ADC_Engagement to S2 for the day (main.bicep:232-235, 1443-1446), and carrying a service tag equal to the owning container app's, so one tag-grouped cost report splits compute and storage per service (main.bicep:237-241, 1439-1441), with weekly/monthly/yearly long-term retention on top of Basic-tier PITR (main.bicep:1455-1471). The three databases that hold an audit-trail table (ADC_Identity, ADC_Conference, ADC_Engagement; Notification has no audited entities) also get a database-level audit policy recording every UPDATE or DELETE on dbo.AuditTrailEntries outside the database (main.bicep:1502-1506, 1524-1541), because the services connect with the server admin login and could otherwise rewrite the ADR-075 trail without a record (main.bicep:1476-1484). The legacy AtlDevCon database is declared in neither place (main.bicep:1408-1414), and with its bacpac deleted on 2026-10-03 it has no rollback source (main.bicep:1458-1459) |
| Redis container (persistent) | Azure Managed Redis (Microsoft.Cache/redisEnterprise, Balanced B0, no HA, main.bicep:2038-2049), OSS-cluster policy and volatile-LRU eviction (main.bicep:2069, 2072), injected as ConnectionStrings__redis from Key Vault (main.bicep:2487) |
RabbitMQ container (persistent, management plugin), or the Service Bus emulator container under ADC_BROKER=servicebus |
Azure Service Bus (Standard tier, main.bicep:1574-1577; Basic only supports queues, while the transport publishes each event on its own topic and binds each consuming host with a subscription that forwards into that host's queue, main.bicep:1564-1566). The template declares that topology itself: one queue per consuming host, one topic per event, and the forwarding subscriptions (main.bicep:1601-1614, 1668, 1689, 1707), with one per-service SAS rule rather than one credential for the whole fleet (main.bicep:1752, 1763, 1774, 1785) |
| MailDev container (fixed ports 1080/1025) | Not provisioned; a real SMTP relay via Smtp__Host / Smtp__Port / Smtp__From (main.bicep:2554 for Identity, 3126 for Notification) |
MessageBus__Provider=RabbitMq (AppHost default) |
MessageBus__Provider=AzureServiceBus (Bicep env var on all four services, main.bicep:2528, 2793, 2953, 3117) |
| Aspire dashboard (OTLP) | Application Insights workspace-based resource (APPLICATIONINSIGHTS_CONNECTION_STRING, main.bicep:317-320) |
WithSQLServerDataSource injects one connection-string env var |
Bicep injects the same one plus DataSources__{Module}__SQLServerMigrationsAssembly and Outbox__DatabaseName (main.bicep:2464-2466) |
h2c health probe from the AppHost (WithH2cHealthCheck) |
Dedicated HTTP/1.1 probe listener via HealthProbe__Port, 8081 on the three h2c services (main.bicep:2460, 2753, 2906) and 8082 on Notification (main.bicep:3080), because the ACA platform probes speak HTTP/1.1 |
WithJwksDiscovery(identity, gateway): the JwtBearer authority is the gateway's https endpoint, which proxies the discovery fetch to Identity |
Authentication__JwtBearer__Authority=http://<identity app> with Authentication__JwtBearer__RequireHttpsMetadata=false on Conference, Engagement and Notification (main.bicep:2776, 2780, 2923, 2927, 3097, 3101): the fetch goes to Identity through Container Apps internal ingress, not through the gateway, a deliberate split the Store AppHost records beside its own WithJwksDiscovery calls (MMCA.Store/Source/Hosting/MMCA.Store.AppHost/Program.cs:324-336). On Identity, the one app with configured keys, the signing key id comes from the jwksKeyId parameter (main.bicep:70, 2576); during a key rotation the optional rsaPreviousPublicKeyPem (fed by deploy.yml from the JWT_RSA_PREVIOUS_PUBLIC_KEY_PEM secret, deploy.yml:1729-1731, 1872-1879) keeps the outgoing public key published under its old kid as Jwks__AdditionalKeys__0__*, and drops Jwt__MinimumRsaKeySizeBits to 2048 only while that pre-rotation key is configured (main.bicep:2592-2604), so the three validators see both keys through the one JWKS document |
WaitFor gates on /alive; only the UI gates on /health/ready |
The ACA probe block splits the same two paths by job: startup and liveness on /alive, readiness on /health/ready, all three against the probe port (main.bicep:2658-2683). Readiness polls every 30 s rather than 10 s, because the DB-aware check issues a SELECT 1 per probe and neither the probe request nor its dependency row is sampled (main.bicep:2652-2657) |
| Outbox poll interval: framework default 2 s | Outbox__PollingIntervalSeconds=300 on every service (main.bicep:2472, 2760, 2913, 3089); Identity, Conference and Engagement, the three hosts that call AddScheduledJobs, also slow the runner's idle wake to Scheduler__PollingIntervalSeconds=300 (main.bicep:2483, 2768, 2916). Internal commands (ADR-114) deliberately poll faster at InternalCommands__PollingIntervalSeconds=60 on all four (main.bicep:2478, 2761, 2914, 3090), because a row is signalled when it is written or, when enrolled in a transaction, once that transaction commits, so the interval mainly bounds the retry of a row that failed, and 60 s keeps such a retry from waiting five minutes (comment above the Identity entry at main.bicep:2478) |
| Telemetry knobs at their defaults (sample everything, all metric families on, probe traces filtered) | Telemetry__TracesSampleRatio=0.25, Telemetry__DisableHttpClientMetrics=true, Telemetry__DisableRuntimeMetrics=true, Telemetry__DisableAspNetCoreMetrics=true, OTEL_METRIC_EXPORT_INTERVAL=300000, plus the distro switch AzureMonitor__EnableLiveMetrics=false (main.bicep:326-329, 360-367, 373-376, 383-386, 394-397). Telemetry__FilterProbeTelemetry is set nowhere, because its default is already the production behavior |
Gateway: YARP request-routing lines at Information (Gateway/appsettings.json:6) |
Logging__LogLevel__Yarp=Warning on the gateway container and no other (main.bicep:342-351, 3266), because YARP's two lines per proxied request duplicated AppRequests and AppDependencies in the console-log stream; Warning keeps the forwarder's error lines |
The transport switch (RabbitMq to AzureServiceBus) is entirely environment-driven. No code path
changes between local and production: the same AddBrokerMessaging(configuration) call in each
service's Program.cs reads MessageBus:Provider and branches accordingly. This is ADR-003 (outbox +
in-process dispatch + background processor) combined with the infrastructure flexibility of
MessageBusProvider selection.
Be honest about what that buys and what it does not. Environment-driven transport selection means no
#if and no second code path, but the default local run still uses a different broker than
production: RabbitMQ exercises the framework's built-in RabbitMQ transport
(MMCA.Common.Infrastructure/Messaging/Transports/RabbitMq/RabbitMqBrokerTransport.cs:24), not the
Service Bus topic topology, its quotas, or its admin-plane behavior. ADC closes that gap on two fronts
rather than one. The ADC_BROKER=servicebus opt-in (AppHost Program.cs:98, rationale at 69-92) runs the whole inner-loop
stack against the official emulator, so a developer chasing a transport bug can reproduce it locally; and
Tests/Integration/MMCA.ADC.ServiceBusEmulator.IntegrationTests runs MMCA.Common's native Azure Service
Bus transport (AzureServiceBusTransport.cs:37) with ADC's real integration-event contracts and the
production entity names against the same emulator, proving admin-plane topology provisioning and the
AMQP round-trip (ServiceBusRoundTripSmokeTests.cs:9-18). It runs as the servicebus-emulator-smoke
job on the weekday nightly (.github/workflows/cross-service-tests.yml:28-31), and it is
deploy-gating: the cross-service-freshness gate in deploy.yml requires both it and the RabbitMQ
cross-service job to have succeeded in the same qualifying run, so a red here is fixed rather than
waved through (cross-service-tests.yml:122-133). The residual gap is what
the emulator itself does not model (real quotas, real throttling, the real admin plane), which is
narrower than the gap a RabbitMQ-only inner loop leaves.
[Rubric §7, Microservices Architecture] is directly served by the fact that the extraction boundaries (gRPC contracts, broker interfaces, JWKS discovery) are identical in both environments. An engineer can validate a cross-service event flow locally before it reaches the Azure Service Bus in production.
[Rubric §17, DevOps and Deployment] is served by the single-command local run matching the production topology in process count, service-discovery mechanism, and transport semantics. The two remaining gaps, MailDev versus a real SMTP relay and the default RabbitMQ versus Azure Service Bus, are intentional and each is scoped: the first is never exercised in production paths, the second has both the opt-in emulator and the nightly emulator tier above.
The YARP Gateway's role
The gateway (Source/Hosts/MMCA.ADC.Gateway) is a pure YARP reverse proxy. It has no DbContext, no
ModuleLoader, no REST controllers, and no broker connection. Its Program.cs is 243 lines and
contains no route definitions at all: the route table is configuration, not code
(Gateway/Program.cs:9-13). appsettings.json's ReverseProxy section owns every route pattern and every
cluster, so adding or repointing a route is an appsettings edit plus a matching entry in RouteMapTests
(which pins the whole table), never a redeploy of hand-written MapForwarder calls.
The route table
Gateway/appsettings.json declares 45 routes across 5 clusters in its ReverseProxy section
(the section at appsettings.json:64, clusters at appsettings.json:341), every destination an in-cluster
service-discovery name over cleartext, never a public URL. The route families, in file order:
- The identity and administration block (appsettings.json:86-173): the credential routes
/Auth/login,/Auth/registerand/Auth/token, the/Auth/{**catch-all}that carries everything else,/Users,/UserClaims, the administration prefixes/Admin/Users,/Admin/Roles,/Admin/ViewAsGrantsand/Admin/MachineClients, the three per-module audit-history prefixes (/Admin/Identity/AuditHistory,/Admin/Conference/AuditHistory,/Admin/Engagement/AuditHistory), and the two/.well-knowndocuments (jwks.jsonandopenid-configuration). - The Conference block: seventeen aggregate prefixes from
/Eventsto/Activities(appsettings.json:178-258), the two/SessionAssetsroutes (268-278),/Admin/Conference/FeatureFlags(285) and/mcp(293). - The Engagement block:
/Bookmarks,/CheckIns,/LivePolls,/Points,/SessionQuestions,/Ticketsand/Admin/Engagement/FeatureFlags(appsettings.json:298-328). /Notificationsto clusternotification-restand/hubs/*to clusternotification-hub(appsettings.json:333-338). Both point at the samehttp://notificationdestination; they are two clusters because a cluster is what carries the forwarder request config, and these two need different ones (Program.cs:15-31).
The cluster each route names is pinned route by route, in both directions, by RouteMapTests, so an
unpinned route fails the build. /Partners (appsettings.json:253) shows the shape every new aggregate
takes at the edge: one prefix route, "AuthorizationPolicy": "anonymous", the same conference
cluster, no forwarder config of its own, and a matching row in the test that pins the table. Nothing in
the gateway image or its Program.cs changes to carry it.
Two of those entries are worth reading rather than counting.
The auth-tight split is a bug fix, not a tightening. The policy used to sit on the single /Auth
catch-all, which also matched /Auth/refresh, and the UI container calls the gateway server-side at
http://adc-gateway for every SSR session refresh. Those internal calls carry no X-Forwarded-For, so
the ClientIp partition keyed every user's refresh on the UI replica's own container IP: one shared
30-per-minute bucket for the whole site. ADR-019 deliberately leaves RefreshAsync unthrottled at the
service layer for exactly that shared-IP reason, and the gateway policy was silently undoing it
(appsettings.json:74-82). Login and register are split out and keep the tight policy; everything else
under /Auth (refresh, logout, forgot/reset password, the OAuth callbacks) stays on the edge global
limiter alone (appsettings.json:106-107).
Every route states "AuthorizationPolicy": "anonymous". A proxied route carries no authorization
metadata of its own, so without the declaration the anonymous posture of the whole table would be an
absence rather than a statement, with nothing for a reviewer or a fitness test to read (SEC-Common-16,
Gateway/Program.cs:115-123). The declaration makes the posture readable; it does
not make a new route fail closed. The framework's fallback policy is deliberately not registered in
this host, so a route added without a policy still inherits the anonymous default rather than failing
closed at the edge (Program.cs:125-128). builder.Services.AddAuthorization() (Program.cs:129) plus
app.UseAuthorization() (Program.cs:233) evaluate the declared policy, with no UseAuthentication
above them on purpose: the gateway authenticates no one and the bearer travels untouched to the service
that does (Program.cs:230-232). The fallback is not adopted because it ships in MMCA.Common.API, and
referencing that package would pull the whole MVC and controller stack into a pure-YARP host and into
the edge container image; the four services and the UI head, which already reference it, do adopt it
(Program.cs:125-128).
Three forwarder profiles, on two axes
There are three profiles, not two, and they differ on HTTP version and activity timeout (the header comment enumerates them, Gateway/Program.cs:15-31).
The identity, conference and engagement clusters each state
"Version": "2.0" with "VersionPolicy": "RequestVersionExact" in their own HttpRequest block
(appsettings.json:346-349, 355-358, 364-367). Exact is load-bearing: on cleartext there is no ALPN to
negotiate, so RequestVersionOrLower silently downgrades to HTTP/1.1 and the Http2-only backend
rejects it. That pair stays per-cluster rather than moving into the shared defaults, because which
clusters speak h2c is a per-cluster fact, not a default (Program.cs:42-43).
The two Notification clusters state no HttpRequest block at all, so YARP's HTTP/1.1-capable defaults
apply, because SignalR's WebSocket transport begins with an HTTP/1.1 Upgrade handshake and Notification
therefore stays Http1AndHttp2 (Program.cs:23-26).
The timeouts moved out of the clusters entirely. They live in the MmcaGateway section that
MMCA.Common.Gateway binds (GatewaySettings.SectionName,
MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewaySettings.cs:15):
MmcaGateway:ClusterRequestDefaults:ActivityTimeout = "00:01:40"(appsettings.json:43-45) applies to every cluster that states no value of its own. That value is the shared backend total-request budget of 90 s (HttpResilienceDefaults.TotalRequestTimeout,Core/MMCA.Common.Shared/Resilience/HttpResilienceDefaults.cs:19) plus a deliberate 10 second margin. The margin is the whole point: the forwarder must outlive the backend's own total request budget, or a call that exhausts the backend surfaces a gateway abort that hides the backend's real error (Program.cs:35-39).MmcaGateway:ClusterRequestOverrides:notification-hub:ActivityTimeout = "01:00:00"(appsettings.json:46-50) is the one cluster whose budget genuinely differs. A hub connection is long-lived by design (a WebSocket or long-poll stays open for the session), so applying the REST budget to it would tear down healthy hubs.
Precedence is per property and most-specific-wins, which is why the three h2c clusters keep their local
Version/VersionPolicy pair while inheriting the shared timeout (Program.cs:152-155).
What AddMmcaGateway adds on top
builder.Services.AddReverseProxy().LoadFromConfig(...).AddMmcaGateway(configuration).AddServiceDiscoveryDestinationResolver()
(Gateway/Program.cs:171-174). AddServiceDiscoveryDestinationResolver is what turns http://identity
into a real endpoint; without it YARP would treat identity as a DNS host (Program.cs:142-147).
AddMmcaGateway (MMCA.Common.Gateway/GatewayReverseProxyExtensions.cs:47) binds the MmcaGateway
section and adds six things on top of the loaded table, plus a connect retry this host leaves off
(Program.cs:149-170):
- The shared cluster request profiles described above.
- Version forwarding exactly as each cluster states it. The same config filter merges each request
property per cluster, most specific first, and adds no HTTP version of its own: HTTP/2 reaches the
three h2c services only because their clusters declare
Version2.0 withRequestVersionExact, and a new cluster in front of anHttp2-only service must state the pair too, or it answers 502 (Program.cs:45-55, 156-158). - Passive destination health checks on every cluster that declares none: YARP marks a destination
unhealthy from the failures in the responses the gateway is already forwarding, with no extra probe
traffic (Program.cs:159-163, defaults at
GatewaySettings.cs:121-122). Each cluster here has one destination, and YARP's defaultHealthyOrPanicpolicy keeps sending to it while it is marked unhealthy, so the signal steers traffic only where a cluster has a healthy peer to prefer. Active probes stay at the framework default, off: the gateway'sappsettings.jsondeclares noHealthCheckDefaultssection, and the comment in its place gives the reasoning (appsettings.json:51-54). Every cluster fronts exactly one Container Apps internal address, so an active probe could only ever eject the sole destination while the platform already routes only to ready replicas, and each probe is an HTTP request that bills an otherwise idle downstream replica at the Container Apps active rate ([Rubric §31, Cost and FinOps]). X-MMCA-Route/X-MMCA-Clustertrace headers on every proxied request, with any inbound value stripped first so a downstream can trust them (GatewaySettings.cs:181-184), plus the named per-route rate-limiter policies routes reference by name.- Removal of the edge limiter's trusted-caller and synthetic-traffic bypass headers from every proxied request, so a downstream never receives them (Program.cs:167-168).
- A Kestrel header-encoding selector that reads the correlation header as Latin-1, so a non-ASCII value reaches the correlation middleware (which replaces it) instead of an empty 400 (Program.cs:169-170).
The gateway's own pipeline
The middleware order in Gateway/Program.cs:183-236 is itself the documentation, and each position is
argued:
UseCommonForwardedHeaders()(line 183) comes first, because behind Azure Container Apps ingress every connection arrives from the ingress proxy's IP, and without it the per-client-IP rate-limit partition would collapse to one shared window for all real users (Program.cs:178-182).UseGatewayCorrelation()(line 188) stamps the correlation ID on the request headers before anything can short-circuit (a 429 from the edge limiter included), so the proxied request carries it downstream and the service-side middleware adopts the same ID rather than minting a second one (Program.cs:185-187).UseCommonSecurityHeaders()(line 193) is early so the headers apply to forwarded API responses, the SignalR hub, the static pages and the health endpoints alike (Program.cs:190-192).MapDefaultEndpoints()(line 195) thenUseCors()(line 196).UseGatewayRateLimiting()(line 203) sits after CORS so a rejected preflight is still a CORS answer, and before the proxy is mapped so a throttled request never reaches a backend. One middleware serves both limiters: the edge global limiter fromAddGatewayRateLimiting(line 89) and the named per-route policiesAddMmcaGatewayregistered (auth-tighton the/Authcredential routes), and a request must satisfy both (Program.cs:198-202).UseStaticFiles()(line 208) and three extension-less static pages, eachAllowAnonymousand each served beforeMapReverseProxy()so it is answered locally rather than forwarded:/privacy(lines 215-217), the URL the App Store and Google Play listings link to;/terms(lines 222-224); and/delete-account(lines 226-228), the deletion URL the Google Play listing requires, so it must answer without any credential (Program.cs:205-221).UseAuthorization()(line 233) evaluates the per-routeAuthorizationPolicythe table declares, with noUseAuthenticationabove it (Program.cs:230-232), andMapReverseProxy()(line 236) maps the whole route table from configuration.
The pipeline has no request-size branch. Session-material uploads are the one request the gateway
forwards that is bigger than Kestrel's 30 MB default, so the cap is raised on that route alone: the
conference-session-assets-file route (/SessionAssets/file) carries "MaxRequestBodySize": 52494336,
50 MB plus multipart headroom (appsettings.json:268-273, rationale at 260-267), and RouteMapTests.cs:419
pins it. A global raise would hand every other route a 50 MB body budget it has no use for, and the
service that terminates the request enforces its own cap with [RequestSizeLimit].
The edge limiter's own numbers are configuration: 120 requests per 60 second window per client IP, a
replica-wide concurrency ceiling of 200, and /hubs on the bypass list because a SignalR connection is
long-lived and its negotiate/reconnect traffic must not be throttled (defaults in
MMCA.Common.Aspire/Gateway/GatewayRateLimitingSettings.cs:60, 64, 74); health probes and
/.well-known are always exempt (Program.cs:84-88). The auth-tight route policy is 30 requests per
60 seconds partitioned on client IP with no queue, declared in the MmcaGateway section of
appsettings.json.
A trusted-caller path exists for the same shared-IP problem the auth-tight split solves from the
other side: every server-side call the UI container makes to this gateway, the SSR session refresh above
all, leaves from that container's single address. GatewayRateLimiting:TrustedCallerHeaderName names
the header (default X-Internal-Caller-Key, GatewayRateLimitingSettings.cs:128) and only the name;
the secret arrives as GatewayRateLimiting__TrustedCallerSecret from Key Vault, never from checked-in
configuration (GatewayRateLimitingSettings.cs:148, 156). A request that proves the secret is not
exempt by default: TrustedCallerMode.PerVisitor, the default, still counts it against the end visitor,
and TrustedCallerMode.Exempt is the opt-in that exempts every trusted-caller request
(GatewayRateLimitingSettings.cs:159-166; MMCA.ADC/infra/OPERATIONS.md:768-775).
The two health paths are cached rather than exempted-and-uncached. /health and /health/ready are
anonymous and unconditionally exempt from both limiters (which ADR-088 requires so a flood cannot
starve Container Apps' own probe), and without a cache that exemption turns one anonymous request into
four live internal GETs against a 0.25 vCPU gateway. MMCA.Common.Aspire now serves both paths from a
single-flight CachedHealthReportProvider whose window is HealthChecks:CacheSeconds, pinned to 10 here
(appsettings.json:39-41, rationale at Program.cs:107-113). The Container Apps readiness probe does not read
this report (it targets /alive, see below), so its consumers are the availability web test and
operators, and ten seconds keeps a real outage visible almost immediately (appsettings.json:34-38).
Readiness that reflects the edge's job
AddGatewayDownstreamHealthChecks("identity", "conference", "engagement", "notification")
(Gateway/Program.cs:105) registers one downstream-{name} check per service, each GETting /alive
through a service-discovery-resolved client, tagged Optional
(MMCA.Common.Aspire/Gateway/GatewayHealthCheckExtensions.cs:135, 245). The tag is the decision: the
checks show on /health but stay off both /health/ready and /alive
(GatewayHealthCheckExtensions.cs:117-126). A deployment usually runs a single gateway in front of every
route, so a gateway made unready by one downstream outage would stop serving the healthy routes too: one
failed service becomes a whole-site outage, and a downstream that scales to zero or rolls a deployment
looks like one. Restarting the gateway fixes nothing about a downstream being down either, so the checks
gate neither probe, and the gateway's readiness is its own warm-up (Gateway/Program.cs:91-96). Failure
status stays Unhealthy rather than Degraded, because /health answers 503 only for Unhealthy,
so the availability web test polling /health still alerts on a downstream outage and the report names
the service that failed (GatewayHealthCheckExtensions.cs:129-132).
Production points the platform's readiness probe at /alive as well. The gateway container app probes
/alive for startup, liveness and readiness, all on port 8080 (MMCA.ADC/infra/main.bicep:3315-3346),
and the comment on the readiness entry records why (main.bicep:3331-3337): /alive makes no downstream
request, so a 30 second probe never keeps an idle service replica off the Container Apps idle rate, and
because the downstream checks sit outside /health/ready, one failed downstream never marks the
only gateway replica unready and takes the whole site down, healthy routes included. The full
aggregate stays on /health for the availability web test and its alert. No cold-revision
protection is lost, because the gateway registers no JwtBearer scheme, so the OIDC metadata warm-up task
AddServiceDefaults would otherwise wait on has nothing to fetch. This is the gateway's exception to the
service pattern in the parity table, where readiness stays on /health/ready.
One call covers all four because the probe no longer needs to be told which protocol each downstream
speaks. DownstreamProbeVersion.Auto is the default
(GatewayHealthCheckExtensions.cs:60); it negotiates per downstream and latches the answer for the life of
the process, so the three h2c REST services latch HTTP/2 on their first poll and Notification answers
HTTP_1_1_REQUIRED once and latches HTTP/1.1. The fallback is a one-time cost per downstream, not a
per-poll one (Gateway/Program.cs:97-104).
Whatever still probes that aggregate has an observable cost, and the gateway's appsettings.json pays it
down at the logging layer (appsettings.json:2-16): at Information three categories (Polly retry
attempts, the per-request System.Net.Http.HttpClient logs for the gateway-downstream-* clients, and
the YARP health monitor, Yarp.ReverseProxy.Health) write a line per probe for traffic no user made, so
they sit at Warning while YARP's own request-routing lines stay at Information (appsettings.json:6,
13). Production goes one step further and caps YARP too: the Bicep sets Logging__LogLevel__Yarp=Warning
on the gateway container and no other host (main.bicep:342-351, 3266), because at Information YARP writes two lines per
proxied request that Container Apps ships to Log Analytics, measured at about 177k lines and 77 MB a week,
the largest console-log stream in the workspace and all of it already recorded as AppRequests and
AppDependencies. Warning keeps the forwarder's error lines, so a failed proxy hop still logs.
The three architectural purposes
Single entry point. The MAUI client and Blazor UI always talk to
https://localhost:6001(local) or the equivalent Azure Container Apps ingress URL (production). Neither client is hardcoded to individual service addresses. This allows services to be scaled, moved, or split without client changes.TLS termination. The three REST backends (Identity, Conference, Engagement) run HTTP/2 cleartext (h2c) for gRPC; Notification keeps
Http1AndHttp2defaults for the SignalR WebSocket Upgrade and serves gRPC on a separateHttp2-only endpoint. The gateway terminates TLS and forwards to services over cleartext, avoiding TLS overhead on the internal network. Locally the JWKS discovery routing exploits this: JwtBearer's HTTP/1.1 backchannel hits the gateway over HTTPS, the gateway negotiates h2c to Identity, and the JWKS document is returned transparently. In Azure the services' authority is the Identity app's internal address instead, so that fetch does not pass through the gateway (see Why the gateway proxies JWKS discovery).Extraction reversibility. If a service needs to be re-merged into the monolith or split further, only the YARP route table changes, and it is a configuration file. Clients and other services are unaffected. This is ADR-008 (service extraction topology): "transport at the edge keeps extraction reversible."
[Rubric §7, Microservices Architecture] is directly served: clients talk to one address; services talk to each other via gRPC or the broker; the gateway is the only component that knows the current service topology on behalf of clients.
Startup ordering summary
The health-based WaitFor chain imposes this ordering. Two things shape it that are not visible at the
call site: every non-Identity service waits on Identity through WithJwksDiscovery, which adds
WithReference(identity).WaitFor(identity) (Common.Aspire.Hosting/Extensions.cs:377-379), and every one
of those waits gates on a liveness answer over the protocol the target actually serves, not on
readiness. The database, broker, Redis and MailDev waits come from WithMmcaServiceInfrastructure
(ServiceInfrastructureExtensions.cs:73-78).
SQL Server container health
|- Database resources health (adc-identity, adc-conference, adc-engagement, adc-notification)
|- Identity Service (WaitFor: identityDb, broker, redis, mailDev; gate: h2c /alive)
|- Conference Service (WaitFor: conferenceDb, broker, redis, mailDev,
| identity via JWKS; gate: h2c /alive)
| |- Engagement Service (WaitFor: engagementDb, broker, redis, mailDev,
| conferenceService, identityService explicit at Program.cs:272 and
| again via JWKS; gate: h2c /alive)
|- Notification Service (WaitFor: notificationDb, broker, redis, mailDev,
identityService explicit at Program.cs:266 and again via JWKS;
gate: stock HTTP/1.1 /alive)
|- Gateway (WaitFor: all four services; gate: stock /alive, never /health/ready)
|- UI (WaitFor: gateway + all four services; gate: /health/ready)
Six edges deliberately carry a WithReference with no WaitFor: Conference to Engagement (the reverse
half of the bidirectional gRPC pair, Program.cs:275), Engagement to Notification (fire-and-forget live
channel, Program.cs:283), Identity to Engagement, Notification and Conference (the export aggregation,
Program.cs:293-294, 299), and Notification to Conference (the live-channel join gate, Program.cs:307).
Each would close a cycle against a wait that already exists in the other direction, or join the
Conference-Engagement pair in one. All six retry via the gRPC resilience pipeline until the peer is ready.
Where the composition is exercised
Everything above is composition code, and composition code has a specific blind spot: a renamed
resource, a reference that no longer resolves, a WaitFor cycle, or a data source that stopped being
injected is invisible to dotnet build and to every in-process test tier, because those tiers boot hosts
directly through WebApplicationFactory and bypass the orchestration. Two places run the orchestration
for real. The framework owns the test base: MMCA.Common's apphost-testing job boots a sample AppHost
through Aspire.Hosting.Testing and is blocking in Common's CI, though not a required merge check
(MMCA.Common/.github/workflows/ci.yml:1454-1474; the base is
ADR-117). And ADC's
e2e.yml starts this AppHost for every Playwright run (MMCA.ADC/.github/workflows/e2e.yml:277, after the Aspire CLI install through MMCA.Common's aspire-cli composite action at e2e.yml:222; the step sets ASPIRE_SUPPRESS_CLI_RUN_HOOK=true so Aspire 17's run hook does not turn that dotnet run -c Release --no-build into an aspire run that drops -c Release and starts a never-built bin/Debug, e2e.yml:285-289), so a
wiring break surfaces as a failed stack start or a red browser suite: on the deploy path through the
chromium e2e-gate on a UI diff (MMCA.ADC/.github/workflows/deploy.yml:1224-1246), and on the scheduled
firefox and webkit legs. ADC carries no AppHost test project of its own.
[Rubric §14, Testability and Test Strategy] assesses whether the test suite covers the risks the system actually carries. An orchestration file is a genuine failure surface with no compiler covering it, and the answer here is proportionate: the framework proves the shared test base once, and the consumer's composition is proven by the suite that has to boot it anyway.
Rubric category index for this chapter
| Category | Where primarily embodied |
|---|---|
| §7 Microservices Architecture | WithReference declared only for real call edges, so the gRPC topology reads as code (AppHost Program.cs:250-307); the gateway as the only component that knows the service topology on behalf of clients; identical extraction boundaries (gRPC contracts, broker interfaces, JWKS discovery) locally and in Azure |
| §11 Security | The GitHub Packages token as a BuildKit secret in all six Dockerfiles (Gateway.Dockerfile:34-36, 55-57), and the non-root USER $APP_UID final stage (Gateway.Dockerfile:104); JWKS discovery with no shared symmetric secret, routed through the gateway locally and issuer-pinned from the same resource (Program.cs:365-384); AddAzureKeyVaultConfiguration and AddAzureDataProtection as single framework calls gated on configuration keys absent locally; the hardened default CSP baseline (SecurityHeaders.cs:53-55) |
| §12 Performance & Scalability | The ACA-tuned SocketsHttpHandler (MMCA.Common.Aspire/Extensions.cs:78-86) and the OIDC metadata warm-up task, both aimed at Consumption-plan cold starts and idle-replica penalties; ReadyToRun publish on the five non-UI images |
| §13 Observability & Operability | Dual OTLP / Azure Monitor export from one binary (Extensions.Telemetry.cs:195-204); eleven MMCA.Common meters registered by literal name from one FrameworkMeterNames list (Extensions.Telemetry.cs:61-74, 331); probe-trace filtering that raises the signal ratio of AppRequests rather than only cutting volume |
| §14 Testability & Test Strategy | AppHostBicepParityTests (MMCA.ADC/Tests/Hosts/MMCA.ADC.Gateway.Tests/AppHostBicepParityTests.cs:11) subclasses MMCA.Common's AppHostBicepParityTestsBase, which reads the AppHost Program.cs and infra/main.bicep as text, without booting the stack, and fails when a WithReference edge has no matching services__ entry in Bicep or a Bicep entry has no matching edge (MMCA.Common/Source/Hosting/MMCA.Common.Testing/Conformance/ServiceDiscovery/AppHostBicepParityTestsBase.cs:75, AppHostBicepParityTestsBase.cs:99); ADC exempts only the one UI-to-gateway edge (ui->gateway), with a stated reason (AppHostBicepParityTests.cs:26-30), and a blank reason fails the test (AppHostBicepParityTestsBase.cs:89-90), which pins the one failure surface no compiler covers; the booted composition is exercised by e2e.yml, and ADC carries no AppHost test project of its own |
| §17 DevOps & Deployment | Persistent container lifetimes shared by the inner loop and the Aspire-driven E2E CI run; one Dockerfile per deployable behind the six-way build-images matrix with per-image dirty gating (deploy.yml:1461-1482); the parity table's environment-driven local-to-cloud mapping |
| §29 Resilience & Business Continuity | The liveness-versus-readiness split on every startup gate (Program.cs:323-359), including the gateway's /alive gate that avoids the readiness-aggregate wedge; WithReference without WaitFor on the six cycle-closing edges, absorbed by the gRPC resilience pipeline; "optional"-tagged dependency checks that keep a degradation partial |
| §31 Cost / FinOps | The five telemetry knobs, the Live Metrics switch (main.bicep:378-386) and the metric export interval; OutboxPollFilterProcessor and ProbeTelemetryFilterProcessor suppressing the two highest-volume classes of span nobody asked for; the gateway's probe-log trim (Gateway/appsettings.json:2-16) and its production-only YARP log floor (main.bicep:342-351, 3266); the 30 s readiness cadence in the ACA probe block (main.bicep:2652-2657); the gateway's YARP active probe switched off (Gateway/appsettings.json:51-54) and its readiness probe on /alive rather than the downstream fan-out (main.bicep:3331-3346) |
| §32 Dependency & Supply-Chain | Digest-pinned aspnet and sdk base images in all six Dockerfiles (Gateway.Dockerfile:16, 18, 28); --locked-mode restore in all six (Gateway.Dockerfile:57, UI.Web.Dockerfile:65); deploy by digest, pinned per image in build-images and refused when missing (deploy.yml:1585-1622, 1809-1826); the per-image Trivy scan of that same digest, a deploy gate on any fixable CRITICAL/HIGH finding (deploy.yml:1632-1650) |
| §33 Developer Experience | One command brings up six processes and four containers with no Compose file and no hand-set environment variables; the ADC_BROKER=servicebus parity opt-in that is paid for only when needed |
Not determinable from source
- The specific integration events that flow over the broker (
UserRegistered,SpeakerLinkedToUser,SpeakerUnlinkedFromUser) are cited from AppHost inline comments (Program.cs:50-57, 168-177), not from the handler implementations. The comments name the publisher and consumer handler on each side; whether those handlers still match the comment is a question for the messaging chapter, not this one. - The headless-AppHost stall is an operational fact recorded in
MMCA.ADC/CLAUDE.mdand the workspaceCLAUDE.md, not something any source file asserts. There is no code path or config key to cite for it. - The AppHost declares the Service Bus emulator's endpoints and connection string, but how
AddBrokerMessagingconsumesUseDevelopmentEmulator=trueandMessageBus:EmulatorAdminEndpointis inMMCA.Common.Infrastructure, outside the files this chapter walks. The emulator resource's own doc comment (ServiceBusEmulatorResource.cs:18-24) is the only statement of that contract cited here. - Every ingestion figure quoted in the cost sections (roughly 65% of AppMetrics, about 290 MB of a
500 MB daily stream, 100% of
AppRequestsrows from probes, the ASP.NET Core meter family at 73% of ingestion, Live Metrics holding 64% of vCPU-seconds on the active rate, the YARP forwarder's roughly 177k console lines a week) comes from the inline comment that records the measurement, not from a workspace query this chapter ran:MMCA.ADC/infra/main.bicep:342-347,353-359,369-372and378-382, andMMCA.Common.Aspire/Telemetry/ProbeTelemetryFilter.cs:8-11. - That the
AtlDevCondatabase is actually gone from the Azure SQL server is asserted by the template's comment (main.bicep:1408-1414), which is explicit that Incremental-mode Bicep never deleted it and an operator did, after the template stopped declaring it. The template can only prove the declaration is absent, not the server's current state.