Skip to content

Hosting

Hosting

TheYard is on the internet at https://theyard.stevenstout.biz. This page is the parent record for how that works, written for a reviewer or anyone learning how a small production setup fits together. The records under it in this menu are its children: read this page for the shape, open a child for the full reasoning behind one decision. Everything, the infrastructure code included, is served from these menus; nothing requires opening the repository.

In plain words

This page explains how the site reaches the internet: a domain name and a free edge service (Netlify) that handles the secure connection, in front of two web apps on one Azure machine (an App Service plan): one that runs both sites and The Shed in a single process and answers each by the name typed, and a rendering service that draws every page before it leaves. The piece still waiting is a production edge (Azure Front Door) that the free trial refuses to create.

In practice, a developer sees how a small production setup fits together, with its infrastructure code served on the site, and the organization runs it on free services and one small plan while the full design waits behind one parameter.

The picture

TheYard infrastructure: a request from the browser through Wix DNS and the Netlify edge to the rendering service and the site's web app on the App Service plan on Azure; a green gate's push through the two deploys to the registry and the roll; and Azure Front Door, designed, parameterized and still refused

A preview. Open the infrastructure diagram in a new page to zoom in and follow it; every diagram on this site opens that way (ADR: Diagram pages).

Three lanes: a request from left to right, through the rendering service and the API it reads, a merge becoming a roll, and the one piece of the production design that still waits for a subscription upgrade. Every name in it is the one the records and the pipeline logs carry. The source is docs/images/infrastructure.svg; the records below explain each box.

Since 1.0.0.100 there are two sites behind that edge, and since 19 October they and The Shed are one web app. The second drawing is how the names reach it, the two Yard names through the edge and The Shed's straight to Azure, how a page reaches the rendering service beside it, and how the one process reaches both stores (ADR: A permanent address for the second site; ADR: One web app for every .NET process):

TheYard's two sites and The Shed: four names at Wix, one Netlify edge, one web app for every .NET process and the rendering service on one App Service plan, both stores behind it

A preview. Open the two-sites diagram in a new page to zoom in and follow it.

Websites and resources used

  • Azure (portal.azure.com). Runs the app: one Linux B2 App Service plan for the compute, carrying two web apps for containers: since 19 October one that runs both sites and The Shed in one process (ADR: One web app for every .NET process; from 1.0.0.156 each site had its own, ADR: One plan, two sites), and since 1.0.3.103 the rendering service that draws every page for both sites (ADR: A rendering service beside the API); Container Registry for the two images; Azure SQL Database for the store the first site is on and Azure Cosmos DB for the second's, with both stores opened by both sites since 1.0.0.94 (ADR: One container, both stores). The only place code executes. For its first three weeks the compute was Azure Container Instances, one container group per site.
  • Wix (wix.com). The domain registrar. Holds stevenstout.biz and answers DNS; two CNAME records, theyard and theyard-cosmos, point the two sites at the same edge, and a third, theshed, points The Shed at the web app itself.
  • Netlify (netlify.com). The free edge. Terminates HTTPS for both names on one certificate, and forwards every request to Azure over HTTPS: a page to the rendering service, everything else to the one web app with the name the visitor typed in an X-Yard-Host header (ADR: A permanent address for the second site; ADR: One web app for every .NET process).
  • Let's Encrypt (letsencrypt.org). Issues the certificate at no cost; Netlify renews it automatically.
  • Cloudflare (cloudflare.com). Configured and dormant; becomes the edge after the domain transfers registrars, around late October 2026.
  • GitHub (github.com/SteveStout/TheYard). Holds the code, runs the deploys when the ship's gate pushes, runs the test wall on a pull request, and feeds the edge deploys.

The chain, request by request

  1. DNS. theyard.stevenstout.biz and theyard-cosmos.stevenstout.biz are two CNAME records at the registrar (Wix), both pointing at the same edge. theshed.stevenstout.biz is a CNAME straight to the web app's own azurewebsites.net name, with App Service's managed certificate. TTLs sit at 30 minutes to an hour while the setup is young so changes propagate fast.
  2. Edge. Netlify's free tier terminates HTTPS for the two Yard names. The name a request arrived on picks the rules, and the path picks the origin: a page, the bare path with its query, goes to the rendering service under that site's name, and everything else, the bundle, the photographs and /api, goes to the one web app with X-Yard-Host saying which name was typed (ADR: A permanent address for the second site; ADR: A rendering service beside the API).
  3. Origin. One App Service plan, PLAN-THEYARD-SS, Linux B2 in West US 3, runs two web apps for containers in RG-THEYARD-SS: the API's image once, in APP-THEYARD-ONE-SS, which answers all three names in one process, and the rendering service's image once, which draws a page for either site by reading the API with the site's store named. Azure does all the compute; the edge only forwards. Each Yard site is one store's site by its name, and the Store bar at the top of every page links to the other at the same page (ADR: One container, both stores; ADR: One web app for every .NET process). Why one plan and why West US 3 are ADR: One plan, two sites, which also records the move from B1 to B2 when the rendering service arrived.

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:

How a request gets answered: three names at Wix, the Netlify edge's two files, the rendering service, and inside the one web app SiteHosts picking the name, ShedMount handing The Shed's name to The Shed, and Stores picking Azure SQL or Cosmos DB

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:

# The two Yard names, everything but the page, to the one web app that serves
# both sites (ADR: One web app for every .NET process). Netlify reads
# edge/_redirects first, so the page rules and the address moves there win over
# these; between these two, the first that matches wins, so the Cosmos DB site's
# name comes before the catch-all.
#
# The web app's own address is the same for both names, so each rule says which
# name the visitor typed in X-Yard-Host, and the web app picks the site's store by
# it (api/TheYard.Api/Shared/Instance/SiteHosts.cs). Only a rule written in this file can add a
# header to a proxied request; edge/_redirects cannot.
[[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:

/// <summary>
/// The public names one web app serves, as a configured list (ADR: The onion cut into vertical
/// slices, rule 3): each site is a name and, for a Yard site, the key of the store it serves; a
/// site with no store is a guest application this process hosts, The Shed today. The list is read
/// from configuration (SiteSettings.cs), so a third site or a third store is a setting, and nothing
/// here names a store or a host.
///
/// <para>Which name a request arrived on is the Host header when App Service routed it here by
/// that name, which is how a guest's domain arrives, bound straight to the web app. The Yard domains
/// arrive through the edge, which proxies to the web app's own address and says which domain the
/// visitor typed in <see cref="HeaderName"/> (netlify.toml); the header is read only when the Host
/// is not one of the configured names. A header is what the sender says it is, so it counts only
/// when it names one of them: the most a sender can choose is which configured site answers, the
/// same choice typing the other address makes.</para>
/// </summary>
public sealed class SiteHosts
{
    /// <summary>The header the edge writes with the domain the visitor typed.</summary>
    public const string HeaderName = "X-Yard-Host";

    private readonly Site[] _sites;

    /// <summary>The configured address for links when a request arrived on no Yard name (Site:Url), without its trailing slash; null when none is set.</summary>
    private readonly string? _siteUrl;

    /// <summary>The sites, each name cleaned to lower case; a site whose name is empty or a placeholder is left out.</summary>
    /// <param name="sites">The configured sites, in order.</param>
    /// <param name="siteUrl">Site:Url, the address a link falls back to; a placeholder or an empty value is none.</param>
    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)];
    }

    /// <summary>No names at all: a developer's machine or the test host, where the store comes from Store:Default.</summary>
    public static SiteHosts None { get; } = new([]);

    /// <summary>Every configured site, in order.</summary>
    public IReadOnlyList<Site> All => _sites;

    /// <summary>The names that serve a store, the Yard's own sites.</summary>
    public IEnumerable<Site> StoreSites => _sites.Where(site => site.Store is not null);

    /// <summary>The names that serve no store: guest applications this process hosts.</summary>
    public IEnumerable<string> Guests => _sites.Where(site => site.Store is null).Select(site => site.Host);

    /// <summary>
    /// The configured name this request arrived on, or null when it arrived on none of them
    /// (the web app's own azurewebsites.net address with no header, a health probe, a test).
    /// </summary>
    /// <param name="context">The request, or null outside one.</param>
    public string? Of(HttpContext? context)
    {
        if (context is null)
        {
            return null;
        }
        // The Host header first: a name App Service routed here by is the name, whatever a
        // header says. Only a request on another name (the web app's own address, which is
        // where the edge sends the Yard names) is told its name by the edge's header.
        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;
    }

    /// <summary>The key of the store a name serves when the request names none, or null for a guest's name or any other.</summary>
    /// <param name="host">A name, already one of the configured ones or null.</param>
    public string? StoreFor(string? host) => Array.Find(_sites, site => site.Host == host)?.Store;

    /// <summary>The public name of the site whose store is <paramref name="key"/>, or null when that store has no site here.</summary>
    /// <param name="key">A store's key.</param>
    public string? HostFor(string key) =>
        Array.Find(_sites, site => string.Equals(site.Store, key, StringComparison.OrdinalIgnoreCase))?.Host;

    /// <summary>The public origin of the site whose store is <paramref name="key"/>, or null when that store has no site here.</summary>
    /// <param name="key">A store's key.</param>
    public string? OriginOf(string key) => HostFor(key) is { } host ? $"https://{host}" : null;

    /// <summary>
    /// The Yard site this request arrived on, as an origin for a link (a reset email, the About
    /// page), or null when it arrived on no Yard name and the caller falls back to Site:Url.
    /// </summary>
    /// <param name="context">The request, or null outside one.</param>
    public string? SiteOrigin(HttpContext? context) =>
        Of(context) is { } host && StoreFor(host) is not null ? $"https://{host}" : null;

    /// <summary>
    /// The origin a link sent from this request carries (a reset email, the About page): the Yard
    /// site the request arrived on, then the configured Site:Url, then the request's own scheme and
    /// host on a machine with neither. Never X-Forwarded-Host: a link must not be one a sender chose.
    /// </summary>
    /// <param name="context">The request.</param>
    public string LinkOrigin(HttpContext context) =>
        SiteOrigin(context) ?? _siteUrl ?? $"{context.Request.Scheme}://{context.Request.Host.Value}";

    /// <summary>The guest site this request arrived on, or null when it arrived on a Yard name or none.</summary>
    /// <param name="context">The request.</param>
    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);
    }

    // A deploy's unreplaced placeholder ("__HOSTS_SQL__") reads as no name, as Peer:Url's does.
    private static string? Clean(string? host) =>
        string.IsNullOrWhiteSpace(host) || host.StartsWith("__", StringComparison.Ordinal)
            ? null
            : host.Trim().TrimEnd('.').ToLowerInvariant();
}

/// <summary>One public name this process answers to, and the store it serves.</summary>
/// <param name="Host">The name, lower case.</param>
/// <param name="Store">The key of the store the name serves when a request names none, or null for a guest application's name.</param>
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:

/// <summary>
/// The sites this process hosts beside the Yard's own (IHostedSite), started once the host is built
/// and handed their requests first. A request whose name is a hosted site's is handed to that site
/// whole, before anything of TheYard's pipeline sees it; every other request carries on to TheYard.
/// A site that cannot start must not take the Yard down with it: its name answers 503 with a
/// sentence, the reason goes to the log, and the Yard names carry on.
/// </summary>
public static class HostedSiteMount
{
    /// <summary>Starts every hosted site and adds the one middleware that hands each its requests.</summary>
    /// <param name="app">The built host.</param>
    /// <param name="stopping">Cancelled when the host begins to stop, handed in by the composition root rather than read off the built app here (ADR: The onion cut into vertical slices, rule 6).</param>
    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)
            {
                // The site's own handler answers its errors; anything past it is logged here, in
                // TheYard's log and TheYard's error record, and answered as a problem rather than
                // a bare 500. The record takes the type and the frames, never the message, as the
                // error record does for TheYard's own requests.
                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:

/// <summary>
/// The Shed's application, built the way samples/theshed/Program.cs builds it, held in this
/// process with the in-process server standing where Kestrel would.
/// </summary>
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;
    }

    /// <summary>
    /// Builds and starts The Shed from its published folder: the same registrations (files,
    /// documents and version, the API, the write limits), the same pipeline and the same
    /// controllers as its Program.cs, in that order, with what the owning host adds.
    /// </summary>
    public static async Task<ShedApplication> StartAsync(string contentRoot, string environmentName, Action<WebApplicationBuilder> hosted, CancellationToken stopping)
    {
        var builder = WebApplication.CreateBuilder(new WebApplicationOptions
        {
            // The controllers are found in the application's own assembly, by this name.
            ApplicationName = typeof(TestProject.Program).Assembly.GetName().Name,
            ContentRootPath = contentRoot,
            WebRootPath = Path.Combine(contentRoot, "wwwroot"),
            EnvironmentName = environmentName,
        });
        var server = new InProcessServer();
        builder.WebHost.UseServer(server);
        // What the host that owns the process adds to The Shed's services (Shared/ShedMount.cs).
        hosted(builder);
        builder.AddTheShedFiles();                    // samples/theshed/Composition/FilesRegistration.cs
        builder.AddTheShedDocumentationAndVersion();  // samples/theshed/Composition/DocumentationAndVersionRegistration.cs
        builder.AddTheShedApi();                      // samples/theshed/Composition/ApiRegistration.cs
        builder.AddTheShedWriteLimits();              // samples/theshed/Composition/WriteLimitRegistration.cs
        var app = builder.Build();
        app.UseTheShedRequestPipeline();              // samples/theshed/Composition/RequestPipeline.cs
        app.MapControllers();                         // samples/theshed/Controllers
        await app.StartAsync(stopping);

        // The Shed sizes its form reader from its upload limit (FilesRegistration.cs) and asks its
        // Kestrel for the same number; that Kestrel never listens here, so the form reader's
        // limit, as The Shed resolved it, is set on each of its requests instead.
        long? limit = app.Services.GetRequiredService<IOptions<FormOptions>>().Value.MultipartBodyLengthLimit;
        return new ShedApplication(app, server, limit);
    }

    /// <summary>
    /// Hands one request to The Shed: the same connection and the same request and response,
    /// seen through a context of The Shed's own with its own request services. The context and
    /// the request's service scope are released when the response has finished, as Kestrel would
    /// release them, so anything The Shed asked to run on completion still has its services.
    /// </summary>
    /// <param name="context">The request, as TheYard's pipeline saw it.</param>
    /// <param name="cancellation">Cancelled when the visitor has gone. Read before the scope is
    /// made rather than threaded further: everything past this point is ASP.NET Core's own request
    /// pipeline, which reads the cancellation off the context it is handed.</param>
    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;
        }
        // A layer over the connection's features with The Shed's request services in it. The
        // connection's own collection may hold TheYard's, if anything ahead of this asked for
        // them, and those are not the ones The Shed's controllers are resolved from.
        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);
    }

    /// <summary>Stops The Shed's application, its hosted services first, then releases it.</summary>
    public async ValueTask DisposeAsync()
    {
        using var patience = new CancellationTokenSource(TimeSpan.FromSeconds(5));
        await _app.StopAsync(patience.Token);
        await _app.DisposeAsync();
    }
}

/// <summary>
/// A server with no socket: what stands in for Kestrel in an application that is handed its
/// requests by another one in the same process. ASP.NET Core's hosting layer starts it with the
/// application's request handler, which is all it keeps.
/// </summary>
public sealed class InProcessServer : IServer
{
    private Func<IFeatureCollection, Task<IAsyncDisposable>>? _handle;

    /// <summary>The server's own features: none, as nothing listens.</summary>
    public IFeatureCollection Features { get; } = new FeatureCollection();

    /// <summary>Keeps the application's handler; there is nothing to bind.</summary>
    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;
    }

    /// <summary>
    /// Runs one request through the application, and answers what to call when the response has
    /// finished: the hosting layer's end of the request (its log line, its activity, its scope).
    /// </summary>
    public Task<IAsyncDisposable> HandleAsync(IFeatureCollection features) =>
        _handle?.Invoke(features) ?? throw new InvalidOperationException("The Shed's application has not started");

    /// <summary>Nothing to stop.</summary>
    public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;

    /// <summary>Nothing to release.</summary>
    public void Dispose()
    {
    }

    /// <summary>The end of one request, run once the outer response has finished.</summary>
    private sealed class Finished(Action end) : IAsyncDisposable
    {
        public ValueTask DisposeAsync()
        {
            end();
            return ValueTask.CompletedTask;
        }
    }
}

/// <summary>
/// The lifetime of an application whose process belongs to another: it waits for nothing and
/// answers no signal, because the host that owns the process stops this one itself.
/// </summary>
public sealed class HostedByAnotherApplication : IHostLifetime
{
    /// <summary>Nothing to wait for before starting.</summary>
    public Task WaitForStartAsync(CancellationToken cancellationToken) => Task.CompletedTask;

    /// <summary>Nothing to undo when stopping.</summary>
    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:

/// <summary>
/// The stores this container runs, and which one a request gets.
///
/// <para>The choice is a header, which is how a measurement asks for a store
/// without a browser; a request that names none gets the store of the site it
/// arrived on (SiteHosts, ADR: One web app for every .NET process), and a request
/// that arrived on no site's name gets the container's default. Before one web app
/// served both, each site was a container of its own and the default alone made it one
/// store's site (ADR: One container, both stores, the addendum on the toggle
/// moving to the sites). A header naming a store this container does not have
/// is ignored, never an error.</para>
///
/// <para>A cookie named yard-store chooses nothing. A browser may still carry
/// one, so the stores endpoint expires it on sight, and the browser lands
/// where the address bar says.</para>
/// </summary>
public sealed class Backends
{
    /// <summary>A cookie that chooses nothing and is read only to be expired.</summary>
    public const string LegacyCookieName = "yard-store";

    /// <summary>The request header that names a store: "sql" or "cosmos".</summary>
    public const string HeaderName = "X-Yard-Store";

    /// <summary>Every store this container runs, in the order they were brought up.</summary>
    private readonly Backend[] _all;

    /// <summary>The site names this process answers to; none on a developer's machine and the test host.</summary>
    private readonly SiteHosts _hosts;

    /// <summary>
    /// The stores, the key of the one a request gets when it names none and arrived on no
    /// site's name, the other site's address for a container that serves one site, and the
    /// site names when one container serves both.
    /// </summary>
    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;
    }

    /// <summary>Every store this container runs.</summary>
    public IReadOnlyList<Backend> All => _all;

    /// <summary>
    /// The other site, the container whose default is the other store, as a
    /// visitor should reach it (`Peer:Site`), so the bar can put both
    /// addresses on every page. The peer endpoint reads the other container
    /// by its origin; this is the address a person types, which behind the
    /// edge is a different one. Null when there is no other site, and only
    /// ever an http or https origin, so a setting cannot put anything else in
    /// a link.
    /// </summary>
    public string? OtherSite { get; }

    /// <summary>The backend a request gets when it names none.</summary>
    public Backend Default { get; }

    /// <summary>The store with this key, ignoring case, or null when there is none.</summary>
    public Backend? Named(string? key) =>
        key is null ? null : Array.Find(_all, backend => string.Equals(backend.Key, key, StringComparison.OrdinalIgnoreCase));

    /// <summary>The backend a request asked for: the header, or its site's store, or the default.</summary>
    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);
    }

    /// <summary>
    /// The store the site this request arrived on serves when a request names none: the
    /// Cosmos DB site's name gets Azure Cosmos DB, the SQL site's gets the relational store,
    /// and any other address the container's default.
    /// </summary>
    public Backend SiteDefault(HttpContext? context) =>
        Named(_hosts.StoreFor(_hosts.Of(context))) ?? Default;

    /// <summary>
    /// The other site as a visitor reaches it, from where this request is: the other store's
    /// public name when one process serves both, otherwise the configured other site.
    /// </summary>
    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;
    }

    /// <summary>
    /// Expire the toggle's old cookie if this request carries one. The page
    /// asks for the stores on every load, so one visit is enough to clean a
    /// browser that used the old toggle. Nothing else reads it.
    /// </summary>
    public static void ExpireLegacyCookie(HttpContext context)
    {
        if (context.Request.Cookies.ContainsKey(LegacyCookieName))
        {
            context.Response.Cookies.Delete(LegacyCookieName, new CookieOptions { Path = "/" });
        }
    }

    /// <summary>What the page is told about the stores, with the one this request would get marked.</summary>
    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));
    }
}

/// <summary>
/// The backend serving this request, resolved once per request from the
/// request's own headers. Endpoints ask this rather than the
/// container, so the same handler serves whichever store the request named.
/// </summary>
public sealed class CurrentBackend(Backends backends, IHttpContextAccessor accessor)
{
    /// <summary>The store this request named, or the container's default; for the shared wiring, never an endpoint.</summary>
    public Backend Backend { get; } = backends.For(accessor.HttpContext);

    /// <summary>The key of the store this request is on, which a session's token names.</summary>
    public string Key => Backend.Key;

    /// <summary>The store as it describes itself, for a sentence a visitor reads.</summary>
    public string Name => Backend.Name;

    /// <summary>
    /// The request store's vehicles as every query reads them: the catalogue, the bids and the room,
    /// their reading sides only (ADR-115: A request is a query or a command). A new one per read is
    /// three references and nothing more, and it always sees what the backend holds right now,
    /// including after the store is attached. The writing sides are handed to the command handlers
    /// by their slice's Module and to nothing else.
    /// </summary>
    public StandingReader Standings => new(Backend.Inventory, Backend.Bids, Backend.Market);
}

// #region warm-before-reading
/// <summary>
/// The request's store, warm before any endpoint reads it.
///
/// <para>The host starts the default store's catalogue loading beside the
/// server and warms the others in the background on a deployed group, so a
/// request that arrives before a store's load has finished, any request in the
/// first minutes after a roll, a visitor following the toggle, or any request
/// to the other store in a test application where the background warm is off,
/// finds a catalogue still loading. <c>Stock</c>'s synchronous accessors then blocked the
/// request thread on the load, on a container with one vCPU and therefore one
/// thread pool worker to start with: the exact shape ADR: The ports learn to
/// wait argued against (ADR: Three readers with no memory of the project).</para>
///
/// <para>So the pipeline awaits the warm, once per request, before the
/// endpoint runs. After the first time it is an await on a task that finished
/// at startup, which is no wait at all. The bid replay is awaited by the
/// writing methods already and read by the reads as whatever has loaded, so
/// it is not gated here; a listing during the seconds a store's bids replay
/// shows the dataset's prices until the replay lands.</para>
/// </summary>
public static class Warmth
{
    /// <summary>Warms the backend's catalogue if it is not warm; a warm one is a task already finished.</summary>
    /// <param name="backend">The store this request is on.</param>
    /// <param name="cancellation">
    /// The request's. One warm-up is shared, so this ends the request's wait and not the
    /// warm-up: a visitor who closed a tab during the seconds after a roll must not abandon the
    /// load every other request is queued behind (ADR: The ports learn to wait, the addendum on
    /// the token).
    /// </param>
    public static Task EnsureAsync(Backend backend, CancellationToken cancellation) =>
        backend.Inventory.IsWarm ? Task.CompletedTask : backend.Inventory.WarmAsync(cancellation);
}
// #endregion warm-before-reading

/// <summary>One store on the toggle: its key, its name, whether it came up, and whether it is the container's default.</summary>
/// <param name="Key">The store's key.</param>
/// <param name="Name">The store's display name.</param>
/// <param name="Ready">True when the store came up.</param>
/// <param name="Default">True when it is the store a request on this site gets when it names none.</param>
public sealed record StoreView(string Key, string Name, bool Ready, bool Default);

/// <summary>The bar's answer: which store this request is on, the stores there are (one of them this site's default), and the other site if there is one.</summary>
/// <param name="Current">The key of the store this request is on.</param>
/// <param name="Stores">Every store on the toggle.</param>
/// <param name="OtherSite">The other site's http or https origin, or null when there is none.</param>
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:

/** One read of the API: its JSON, or null on anything but a 200. */
type Read = <T>(path: string, signal: AbortSignal) => Promise<T | null>;

/** The header that names the store a read is for, as the API names it (api/TheYard.Api/Shared/Stores/Stores.cs). */
export const STORE_HEADER = 'X-Yard-Store';

/**
 * Reads from one API origin, forwarding only the visitor's cookie, so a page
 * for a signed-in visitor is read as that visitor and nothing else they sent
 * goes on. Every read carries the self mark on its agent, so the Site activity
 * card does not count the page twice: the browser's own reads after it are the visit.
 * Since one web app serves both sites, every read also names the site's store,
 * because the API's address no longer says which site it is.
 */
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;
  };
}

/** A read that fails, or is cut off at the deadline, answers null, and the browser asks for it instead. */
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.

Inside the web app: the onion cut into slices

The one web app is one process, and the code it runs is built in rings cut into slices: every feature is one folder of the same name in the host and in Application, with its adapters at the inner rings' roots, each with a Module that registers and maps it, and Program.cs loops over the modules (ADR: The onion cut into vertical slices). A request that reaches the process lands in exactly one slice and asks exactly one handler.

The onion cut into vertical slices: five rings as bands, four slices cut through every ring, the Shared column, the rules the gate holds, and one bid through one slice

The certificate

Let's Encrypt at the edge, issued and renewed automatically, one certificate for all four names (the bare domain, www, theyard and theyard-cosmos). Nothing was purchased and nothing expires by surprise. The edge-to-origin hop was plain HTTP while the origin was a container group with no TLS listener; since 1.0.0.156 it is HTTPS, on the certificate Azure manages for azurewebsites.net, so both legs are encrypted: the browser to Netlify, and Netlify to the origin. The Shed's name has one leg, the browser to App Service, on its managed certificate.

Why not Front Door today

The free trial refuses to create it, and that was measured rather than assumed (see ADR: Deployment strategy). The registrar also refuses nameserver changes, which rules out Cloudflare's free tier until the domain can transfer, earliest late October 2026. The pattern survived both walls. Only the vendor is temporary.

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.

The box agent

WickedAwsome, the Linux box that runs the job hunt's 6 AM program, reports itself to the Admin tab's WickedAwsome card (ADR: The box reports itself). Its agent is scripts/box-agent/theyard_box_agent.py, Python's standard library only, run by the user unit theyard-box-agent.service under the box owner's account with lingering on, so it runs with no one signed in and no window.

  • Install: bash scripts/box-agent/install.sh copies the script to ~/.local/bin, the unit to ~/.config/systemd/user, writes the site's address to ~/.config/theyard/site, and enables the unit when the key file is there; it then posts once and prints the two answers.
  • The key file: ~/.config/theyard/admin-key, the web app's Admin__Key, mode 600, in a folder of mode 700. The agent refuses to start when the file is readable by anyone else or shorter than sixteen characters, and never prints or logs it.
  • What it sends: every two seconds a live sample to POST /api/admin/cloud/box/live, every thirtieth tick a snapshot to POST /api/admin/cloud/box/snapshot, on one kept-open HTTPS connection to the web app's own name, not through the edge.
  • A dry run: python3 ~/.local/bin/theyard_box_agent.py --dry-run prints one snapshot and one sample as JSON and posts nothing; --once posts one of each and prints the two statuses.
  • What a roll does: the site holds the samples and the newest snapshot in memory, so a roll empties them for the two to five minutes nothing listens. The agent backs off (2, 4, 8, 16, 32, then 60 s), keeps its last sixty snapshots, and posts them when the site answers; the card's three-minute rule counts from the new process's start, so the roll never reads as the box being down.
  • Its journal: journalctl --user -u theyard-box-agent holds one line when the state changes (posting, backing off, back) and one summary every ten minutes, never a line a post.

Files

Store

The Yard, home

Steven StoutStaff .NET engineerRemote

Production .NET that stays up. Built with AI, measured on every version.

Steven Stout

Hi, I'm Steve. I build the systems that make delivery boring in the best way, then coach people inside them.

  • 200+

    production releases, none took the platform down

    Conway Investment Research, 2019 to 2024. Sole engineer for the first three years on a live financial advisory platform.

    See how
  • 50%

    shorter release cycle

    Storee Construction, 2024 to 2026. Four ASP.NET applications onto one .NET 10 platform on Azure, with a four-person team I hired and mentored.

    See how

01Verified

Steven Stout

A real person, and the work is mine.

  • Identity

    Checked by LinkedIn, not by me.

    LinkedIn verified my government ID.

  • Running system

    You are looking at it.

    Version 1.0.5.273 is live. Nothing ships unless it passes the automated gates first.

That's who I am. Here's how I work.

02Strengths

Ten strengths, each with the proof beside it. The numbers match my resume and LinkedIn, and the live ones are read from this site as you look.

  • 01

    Keeps production alive

    200+ releases on a live financial platform, and none took it down. Sole engineer for the first three years.

    See the Conway work

  • 02

    Simplifies messy systems

    Four ASP.NET applications onto one .NET 10 platform on Azure, and a release cycle 50% shorter.

    See the Storee work

  • 03

    Marries dev and infrastructure

    Blue-green releases at Storee that flipped in about 5 seconds with nobody signed out, and Azure Front Door at two employers.

    See this site's cloud

  • 04

    Designs data that holds up

    White-label clients on one shared database, the isolation built into the data, and no cross-client issues.

    See the Conway work

  • 05

    Keeps AI-written code honest

    15 quality numbers that may only improve: 273 releases in a row with none worse.

    See the quality numbers

  • 06

    Resourceful

    $30,000+ cut from Azure and vendor spend at Conway. This site's Azure bill is public, resource by resource.

    See the bill

  • 07

    Builds people up

    Hired and mentored a four-person team. 13 colleagues recommend me by name.

    Read the recommendations

  • 08

    Takes ideas to production

    This site: designed, built and run solo, with 352 versions measured through one gate.

    How it was built

  • 09

    Writes clearly

    Posts on real engineering problems, in plain words.

    Read the blog

  • 10

    Owns decisions

    153 decision records, each with its tradeoff and the call I made.

    See the decision records

Built with AI. Gated so quality never slides.

Steven Stout’s showcase: a used-vehicle auction on .NET and React, built and run by one engineer, live on Azure, with its decisions written down.

No quality number has gotten worse at any release since 1.0.5.1 on 10 November: 273 releases in a row.

One engineer, an AI agent and a gate that checks 15 quality numbers on every release. 352 versions measured, with every result public, the worst days included.

82 releases in the last 7 days, each through the same gate.

Async methods with no CancellationToken, may only fall

11091.0.3.1391.0.5.2731.0.4.115, the ratchet
Every number, on the Quality page

TheYard, right nowLive

Answering in

unread

02505007501,000

server time at p95, the usual five minutes of the last day.

Azure this month

unread

the bill, by resource, read from Azure. The Admin tab shows every line.

Since the last roll

unread

 

rolled in place by the pipeline, behind one gate.

People who have visited

unread

30 days agotoday

Scanners, my own tools' and my own reads left out.

03Start here

04Where teams are heading

How I see engineering with AI, and the setup on this site that backs it.

AI-augmented teams · Architecture and ownership

AI writes more of the code. Someone still has to own what ships.

Teams are going to be heavily AI-augmented. That moves the senior job toward architecture and technical ownership: deciding what to build in pieces small enough to verify, and owning what ships.

  • Task tracking will get automated too. Judgment stays human: seeing a design fail at scale before it does.
  • On this site the AI's first design held the whole catalogue in memory. I caught it when the App Service plan hit 82 per cent and moved the work to the store.

What the AI wrote, what I decided

07Tech stack

  •    
  •    
  •    

Read from the build, never typed by hand

What TheYard runs on

What we use, where it runs, its AWS twin, the version as built, and the file that proves it.

Cloud patterns, not one vendor: every Azure piece in this stack has a named AWS twin. Mapped, not yet run on AWS.

  • .NET 1114 projects
  • React 19.3TypeScript 7.0
  • Azure9 Bicep files
  • 11GitHub Actions workflows
The whole stack, with the file that proves each line

The last release the gate stopped was 1.0.5.258 on 2 December, at its browser 1 of 2 job.

08How it is built

09How it is run

10Who and why

Next step

11What has to work, where is it today, and what does success look like?

Book 20 minutes opens an email to me with those three questions in it, and I answer with a time.

Book 20 minutes

Your email app should have opened with this message. If it did not, copy it and send it from any mailbox.

Or message me on LinkedIn