How a request gets answered
Three domains, two web apps, one process for everything .NET. Follow a request
from the address bar to the code that answers it, every step read from this
build. The whole path first, then each hop with its code:

A preview. Open the request path in a new page to zoom in. Drawn by docs/images/request-path.mjs.
theyard.stevenstout.biz and theyard-cosmos.stevenstout.biz, at the edge.
Netlify reads edge/_redirects first. A page (the bare path, with its query)
goes to the rendering service as that site; the bare domain and www move to
theyard with a 301:
https://stevenstout.biz/* https://theyard.stevenstout.biz/:splat 301!
https://www.stevenstout.biz/* https://theyard.stevenstout.biz/:splat 301!
http://stevenstout.biz/* https://theyard.stevenstout.biz/:splat 301!
http://www.stevenstout.biz/* https://theyard.stevenstout.biz/:splat 301!
# The second site, whose default store is Azure Cosmos DB, under its own name
# (ADR: A permanent address for the second site). These sit above everything in
# netlify.toml, because Netlify reads this file's rules first and the first
# matching rule wins.
#
# Every page is the bare path with a query naming the view, the vehicle or the
# document, and the rendering service draws it (ADR: A rendering service beside the API); each
# domain's page goes to the service under that site's name. The query goes with
# a 200 rewrite.
#
# Everything else, the bundle, the photographs and /api, goes to the one web app
# that serves both sites (ADR: One web app for every .NET process). Those two
# rules are in netlify.toml, because only a rule written there can add a header
# to what it proxies, and the web app learns which site a request is for from the
# X-Yard-Host header those rules add. Until 19 October they were here, one per
# site, each to a web app of its own.
https://theyard-cosmos.stevenstout.biz/ https://app-theyard-render-ss-zmnetj67bn5h2.azurewebsites.net/site/cosmos 200!
http://theyard-cosmos.stevenstout.biz/* https://theyard-cosmos.stevenstout.biz/:splat 301!
/ https://app-theyard-render-ss-zmnetj67bn5h2.azurewebsites.net/site/sql 200!
Live from edge/_redirects, region rules, read from this build at 99df7a8.
Everything else falls through to netlify.toml. Both rules reach the same web
app, so each says which name the visitor typed; the Cosmos DB site's rule comes
first, because the catch-all would match it too:
[[redirects]]
from = "https://theyard-cosmos.stevenstout.biz/*"
to = "https://app-theyard-one-ss-zmnetj67bn5h2.azurewebsites.net/:splat"
status = 200
force = true
headers = {X-Yard-Host = "theyard-cosmos.stevenstout.biz"}
[[redirects]]
from = "/*"
to = "https://app-theyard-one-ss-zmnetj67bn5h2.azurewebsites.net/:splat"
status = 200
force = true
headers = {X-Yard-Host = "theyard.stevenstout.biz"}
Live from netlify.toml, region proxy-rules, read from this build at 99df7a8.
theshed.stevenstout.biz, with no edge. The name is bound to the web app in
Azure, and App Service's front end routes it there by the Host header. No rule
in this repository is involved.
Inside the web app: which name. One class knows the three names and which
one a request arrived on. The Host header first, when App Service routed the
request by one of the three names; only on any other Host, which is the web
app's own address where the edge sends both Yard names, the edge's
X-Yard-Host, and only when it names one of the three. A sender can choose
between the three sites and nothing else:
public sealed class SiteHosts
{
public const string HeaderName = "X-Yard-Host";
private readonly Site[] _sites;
private readonly string? _siteUrl;
public SiteHosts(IEnumerable<Site> sites, string? siteUrl = null)
{
_siteUrl = string.IsNullOrWhiteSpace(siteUrl) || siteUrl.StartsWith("__", StringComparison.Ordinal) ? null : siteUrl.Trim().TrimEnd('/');
_sites = [.. sites
.Select(site => site with { Host = Clean(site.Host) ?? "", Store = string.IsNullOrWhiteSpace(site.Store) ? null : site.Store.Trim() })
.Where(site => site.Host.Length > 0)];
}
public static SiteHosts None { get; } = new([]);
public IReadOnlyList<Site> All => _sites;
public IEnumerable<Site> StoreSites => _sites.Where(site => site.Store is not null);
public IEnumerable<string> Guests => _sites.Where(site => site.Store is null).Select(site => site.Host);
public string? Of(HttpContext? context)
{
if (context is null)
{
return null;
}
if (Known(context.Request.Host.Host) is { } routed)
{
return routed.Host;
}
return context.Request.Headers.TryGetValue(HeaderName, out var said) ? Known(said.ToString())?.Host : null;
}
public string? StoreFor(string? host) => Array.Find(_sites, site => site.Host == host)?.Store;
public string? HostFor(string key) =>
Array.Find(_sites, site => string.Equals(site.Store, key, StringComparison.OrdinalIgnoreCase))?.Host;
public string? OriginOf(string key) => HostFor(key) is { } host ? $"https://{host}" : null;
public string? SiteOrigin(HttpContext? context) =>
Of(context) is { } host && StoreFor(host) is not null ? $"https://{host}" : null;
public string LinkOrigin(HttpContext context) =>
SiteOrigin(context) ?? _siteUrl ?? $"{context.Request.Scheme}://{context.Request.Host.Value}";
public string? GuestOf(HttpContext context) =>
Of(context) is { } host && StoreFor(host) is null ? host : null;
private Site? Known(string? host)
{
string? clean = Clean(host);
return clean is null ? null : Array.Find(_sites, site => site.Host == clean);
}
private static string? Clean(string? host) =>
string.IsNullOrWhiteSpace(host) || host.StartsWith("__", StringComparison.Ordinal)
? null
: host.Trim().TrimEnd('.').ToLowerInvariant();
}
public sealed record Site(string Host, string? Store);
Live from api/TheYard.Api/Shared/Instance/SiteHosts.cs, region site-hosts, read from this build at 99df7a8.
The Shed's name goes to The Shed. Before anything of TheYard's pipeline sees
it, a request on The Shed's name is handed to The Shed's own application,
started inside the same process from its own published folder. The mount sits
in Program.cs right after the app is built, so it runs ahead of TheYard's
whole request pipeline:
public static class HostedSiteMount
{
public static async Task MountTheHostedSitesAsync(this WebApplication app, CancellationToken stopping)
{
var sites = app.Services.GetServices<IHostedSite>().ToList();
if (sites.Count == 0)
{
return;
}
var hosts = app.Services.GetRequiredService<SiteHosts>();
var errorLog = app.Services.GetRequiredService<ErrorRings>().Server;
foreach (var site in sites)
{
try
{
await site.StartAsync(stopping);
app.Logger.LogInformation("The hosted site {Host} is running", site.Host);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
app.Logger.LogError(ex, "The hosted site {Host} did not start ({Reason}); its name answers 503", site.Host, ex.GetType().Name);
}
}
app.Use(async (context, next) =>
{
if (hosts.GuestOf(context) is not { } guest || sites.Find(site => site.Host == guest) is not { } site)
{
await next();
return;
}
if (!site.Running)
{
context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
await context.Response.WriteAsync($"The site {site.Host} is not running in this process; the log says why.", context.RequestAborted);
return;
}
try
{
await site.HandleAsync(context, context.RequestAborted);
}
catch (Exception ex) when (!context.RequestAborted.IsCancellationRequested)
{
app.Logger.LogError(ex, "The hosted site {Host} failed a request to {Path}", site.Host, context.Request.Path);
errorLog.Record(context.Request.Path, StatusCodes.Status500InternalServerError, ex.GetType().Name, StackFrames.Of(ex));
if (!context.Response.HasStarted)
{
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
await context.Response.WriteAsJsonAsync(new { title = $"{site.Host} could not answer", status = 500 }, context.RequestAborted);
}
}
});
}
}
Live from api/TheYard.Api/Shared/Sites/HostedSiteMount.cs, region hosted-sites, read from this build at 99df7a8.
The application it hands the request to is The Shed's own: its builder, its
registrations, then its request pipeline (samples/theshed/Composition/RequestPipeline.cs)
and its controllers (samples/theshed/Controllers), on a server with no socket:
public sealed class ShedApplication : IAsyncDisposable
{
private readonly WebApplication _app;
private readonly InProcessServer _server;
private readonly long? _maxRequestBytes;
private ShedApplication(WebApplication app, InProcessServer server, long? maxRequestBytes)
{
_app = app;
_server = server;
_maxRequestBytes = maxRequestBytes;
}
public static async Task<ShedApplication> StartAsync(string contentRoot, string environmentName, Action<WebApplicationBuilder> hosted, CancellationToken stopping)
{
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
ApplicationName = typeof(TestProject.Program).Assembly.GetName().Name,
ContentRootPath = contentRoot,
WebRootPath = Path.Combine(contentRoot, "wwwroot"),
EnvironmentName = environmentName,
});
var server = new InProcessServer();
builder.WebHost.UseServer(server);
hosted(builder);
builder.AddTheShedFiles();
builder.AddTheShedDocumentationAndVersion();
builder.AddTheShedApi();
builder.AddTheShedWriteLimits();
var app = builder.Build();
app.UseTheShedRequestPipeline();
app.MapControllers();
await app.StartAsync(stopping);
long? limit = app.Services.GetRequiredService<IOptions<FormOptions>>().Value.MultipartBodyLengthLimit;
return new ShedApplication(app, server, limit);
}
public async Task HandleAsync(HttpContext context, CancellationToken cancellation)
{
cancellation.ThrowIfCancellationRequested();
if (_maxRequestBytes is { } limit
&& context.Features.Get<IHttpMaxRequestBodySizeFeature>() is { IsReadOnly: false } body)
{
body.MaxRequestBodySize = limit;
}
var scope = _app.Services.CreateAsyncScope();
context.Response.RegisterForDisposeAsync(scope);
var features = new FeatureCollection(context.Features);
features.Set<IServiceProvidersFeature>(new ServiceProvidersFeature { RequestServices = scope.ServiceProvider });
var finished = await _server.HandleAsync(features);
context.Response.RegisterForDisposeAsync(finished);
}
public async ValueTask DisposeAsync()
{
using var patience = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await _app.StopAsync(patience.Token);
await _app.DisposeAsync();
}
}
public sealed class InProcessServer : IServer
{
private Func<IFeatureCollection, Task<IAsyncDisposable>>? _handle;
public IFeatureCollection Features { get; } = new FeatureCollection();
public Task StartAsync<TContext>(IHttpApplication<TContext> application, CancellationToken cancellationToken)
where TContext : notnull
{
_handle = async features =>
{
var context = application.CreateContext(features);
try
{
await application.ProcessRequestAsync(context);
}
catch (Exception ex)
{
application.DisposeContext(context, ex);
throw;
}
return new Finished(() => application.DisposeContext(context, null));
};
return Task.CompletedTask;
}
public Task<IAsyncDisposable> HandleAsync(IFeatureCollection features) =>
_handle?.Invoke(features) ?? throw new InvalidOperationException("The Shed's application has not started");
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public void Dispose()
{
}
private sealed class Finished(Action end) : IAsyncDisposable
{
public ValueTask DisposeAsync()
{
end();
return ValueTask.CompletedTask;
}
}
}
public sealed class HostedByAnotherApplication : IHostLifetime
{
public Task WaitForStartAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
Live from api/TheYard.Api/Shared/Sites/TheShed/ShedApplication.cs, region shed-application, read from this build at 99df7a8.
A Yard name picks the store. A request that names a store with
X-Yard-Store gets it, which is how the proof card and the measurements ask for
one; otherwise the name picks it, and a request on no name (a health probe, the
deploy's first read) gets the relational store. Every endpoint then asks
CurrentBackend, resolved once per request from that answer, and awaits the
store's warmth before it reads:
public sealed class Backends
{
public const string LegacyCookieName = "yard-store";
public const string HeaderName = "X-Yard-Store";
private readonly Backend[] _all;
private readonly SiteHosts _hosts;
public Backends(IEnumerable<Backend> all, string? defaultKey, string? otherSite = null, SiteHosts? hosts = null)
{
_hosts = hosts ?? SiteHosts.None;
_all = all.ToArray();
if (_all.Length == 0)
{
throw new ArgumentException("a container needs at least one store", nameof(all));
}
Default = Named(defaultKey) ?? _all[0];
OtherSite = Uri.TryCreate(otherSite, UriKind.Absolute, out var site)
&& (site.Scheme == Uri.UriSchemeHttp || site.Scheme == Uri.UriSchemeHttps)
? site.GetLeftPart(UriPartial.Authority)
: null;
}
public IReadOnlyList<Backend> All => _all;
public string? OtherSite { get; }
public Backend Default { get; }
public Backend? Named(string? key) =>
key is null ? null : Array.Find(_all, backend => string.Equals(backend.Key, key, StringComparison.OrdinalIgnoreCase));
public Backend For(HttpContext? context)
{
if (context is null)
{
return Default;
}
if (context.Request.Headers.TryGetValue(HeaderName, out var header) && Named(header) is { } byHeader)
{
return byHeader;
}
return SiteDefault(context);
}
public Backend SiteDefault(HttpContext? context) =>
Named(_hosts.StoreFor(_hosts.Of(context))) ?? Default;
public string? OtherSiteFor(HttpContext? context)
{
var here = SiteDefault(context);
var other = _all.FirstOrDefault(backend => !ReferenceEquals(backend, here));
return other is not null && _hosts.OriginOf(other.Key) is { } origin ? origin : OtherSite;
}
public static void ExpireLegacyCookie(HttpContext context)
{
if (context.Request.Cookies.ContainsKey(LegacyCookieName))
{
context.Response.Cookies.Delete(LegacyCookieName, new CookieOptions { Path = "/" });
}
}
public StoresView Describe(HttpContext? context)
{
var current = For(context);
var siteDefault = SiteDefault(context);
return new StoresView(
current.Key,
_all.Select(backend => new StoreView(
backend.Key,
backend.Name,
backend.Ready,
ReferenceEquals(backend, siteDefault))).ToArray(),
OtherSiteFor(context));
}
}
public sealed class CurrentBackend(Backends backends, IHttpContextAccessor accessor)
{
public Backend Backend { get; } = backends.For(accessor.HttpContext);
public string Key => Backend.Key;
public string Name => Backend.Name;
public StandingReader Standings => new(Backend.Inventory, Backend.Bids, Backend.Market);
}
public static class Warmth
{
public static Task EnsureAsync(Backend backend, CancellationToken cancellation) =>
backend.Inventory.IsWarm ? Task.CompletedTask : backend.Inventory.WarmAsync(cancellation);
}
public sealed record StoreView(string Key, string Name, bool Ready, bool Default);
public sealed record StoresView(string Current, IReadOnlyList<StoreView> Stores, string? OtherSite);
Live from api/TheYard.Api/Shared/Stores/Stores.cs, region backends, read from this build at 99df7a8.
The rendering service calls back. The edge sends a page to it as
/site/sql or /site/cosmos; render/server.mjs looks the name up in
YARD_SITES, where both names are the one web app's address, and the name is
also the store's key. Every read then names that store, because both sites
share one address:
type Read = <T>(path: string, signal: AbortSignal) => Promise<T | null>;
export const STORE_HEADER = 'X-Yard-Store';
function readerFor(
apiOrigin: string,
cookie: string | null,
read: typeof fetch,
store: string | null
): Read {
return async <T>(path: string, signal: AbortSignal) => {
const headers: Record<string, string> = { 'User-Agent': SELF_READ };
if (cookie) headers.Cookie = cookie;
if (store) headers[STORE_HEADER] = store;
const response = await read(`${apiOrigin}${path}`, { headers, signal });
if (!response.ok) return null;
return (path.startsWith('/api/docs/') ? await response.text() : await response.json()) as T;
};
}
function inTime<T>(work: Promise<T | null>): Promise<T | null> {
return work.catch(() => null);
}
Live from render/loaders.ts, region reads, read from this build at 99df7a8.
What sets the names. The template's one web app, its three names and The
Shed's folder:
// The names the one web app answers to. The store a request gets when it names
// none follows the name it arrived on: the SQL site's name gets Azure SQL
// Database, the Cosmos DB site's gets Azure Cosmos DB, and The Shed's name gets
// The Shed (api/TheYard.Api/Shared/Instance/SiteHosts.cs). siteUrl is where links in an email
// point when a request arrived on no Yard name. One entry; a second entry here
// is how a site gets a web app of its own again.
var sites = [
{
name: siteNames[0]
siteUrl: 'https://theyard.stevenstout.biz'
hostSql: 'theyard.stevenstout.biz'
hostCosmos: 'theyard-cosmos.stevenstout.biz'
hostShed: 'theshed.stevenstout.biz'
}
]
Live from infra/appservice.bicep, region sites-list, read from this build at 99df7a8.
What is left of the production design
Open Infrastructure (Bicep) in this menu. Until 20 September 2026
infra/main.bicep described a design nobody ran: App Service behind Azure
Front Door with the origin locked. The App Service half of it runs now, and
the file is the description of what runs: the plan, the one web app, every
setting, the identity and the registry pull. It is deployed in incremental
mode only, because the same resource group holds the databases, the registry
and the identity, and none of them is in a template on purpose (ADR: One
plan, two sites).
The rendering service's web app is the same kind of description, in
infra/render.bicep, on the same plan (ADR: A rendering service beside the
API). This is the whole of it: the image, the two sites it reads by name from the one web app, the
deadline its reads run under, and the heap ceiling that turns a leak into a
restart instead of the plan's memory:
resource render 'Microsoft.Web/sites@2023-12-01' = {
name: renderName
location: location
kind: 'app,linux,container'
identity: {
type: 'UserAssigned'
userAssignedIdentities: {
'${identity.id}': {}
}
}
properties: {
serverFarmId: plan.id
httpsOnly: true
clientAffinityEnabled: false
siteConfig: {
linuxFxVersion: 'DOCKER|${renderImage}'
alwaysOn: true
healthCheckPath: '/healthz'
http20Enabled: true
minTlsVersion: '1.2'
ftpsState: 'Disabled'
// Pulled from GitHub's registry, public, with no credential (ADR-009); the undo is the previous tag there.
acrUseManagedIdentityCreds: false
appSettings: [
{ name: 'WEBSITES_PORT', value: '8080' }
{ name: 'WEBSITES_ENABLE_APP_SERVICE_STORAGE', value: 'false' }
// Each site by name, both read at the one web app's origin; the name is the store each read
// names in X-Yard-Store, and the edge's rule for each domain names the path.
{ name: 'YARD_SITES', value: 'sql=https://${toLower(oneSite)}.azurewebsites.net,cosmos=https://${toLower(oneSite)}.azurewebsites.net' }
{ name: 'YARD_DEADLINE_MS', value: '2500' }
// Node's heap held under the measured peak's ceiling, so a leak ends in a restart and not in the plan's memory,
// measured 2026-10-19 at 18 MB of heap in use and 79 MB resident. Only the flags Node allows in NODE_OPTIONS
// go here: --optimize_for_size is not one, and set here on 19 October it stopped the container starting.
{ name: 'NODE_OPTIONS', value: '--max-old-space-size=128' }
]
}
}
}
Live from infra/render.bicep, region render-site, read from this build at 99df7a8.
What is left is Front Door and the origin lock, behind one parameter that
defaults off. The origins are reachable directly today, as the container
groups were, and what that does and does not expose is on the Security page.
When the subscription allows Front Door it is one parameter, and the domain
layer means the public URL does not change in the switch, as it did not
change in this one.