Skip to content

Memory, held by the build

Memory, held by the build

TheYard is a used-vehicle auction platform built in the open: a .NET 11 API, a React front end, and two databases underneath it. Two apps share one small App Service plan, a B2 with 3.5 GB of memory between them: the one web app that runs every .NET process (both sites and The Shed) and the rendering service. A megabyte one keeps is a megabyte the other cannot have, and the platform's own share comes out of the same 3.5 GB. This page is the eight rules the apps are held to, each with why it matters, the number this site moved when it applied it, and the code or test that holds it.

In plain words

A program's memory is a shared room. Anything it keeps "just in case" takes space from everything else on the same machine, and a collection that only ever grows takes all of it eventually. The rules here say what a .NET app on a small shared machine should keep, for how long, and how to make the build notice when one slips.

What that is worth: the site stopped holding a second copy of data its databases already keep, and every rule below is checked on every build instead of remembered.

The request path, before and after

A listing request before and after: process memory in the middle, then the store in the middle

Before, each site loaded all hundred thousand vehicles into its own memory, for both databases, and answered every search by walking that list. The databases held the 200 starting vehicles. After, the databases hold all hundred thousand and answer the search themselves, and the site asks for one page and keeps nothing but a five-second cache (ADR: The store does the work).

Measured before the change, on 1.0.3.176: the plan at 82 per cent of its 3.5 GB, each .NET site about 750 MB of working set and 420 to 460 MB of heap, each holding two hundred thousand vehicles. After, on 1.0.3.179 at 04:43 UTC on 19 October, ten minutes after both fills had finished: the plan at 68 per cent, each .NET site about 360 to 380 MB of working set and 80 to 110 MB of heap under a 986 MB limit, holding no vehicles. The plan did not stay there: it read 73 per cent at 11:30 UTC the same morning, with each .NET site at 366 to 396 MB, and the settled reading a day after 1.0.3.181 rolled is in the same record. The whole table, with the listing times on each store, is in ADR: The store does the work, the addenda of 19 October.

The eight rules

a. A store is not a cache

Why: data that already lives in a database and is also held whole in memory is paid for twice, and the memory copy has none of the database's guarantees: no bound, no expiry, rebuilt on every start.

Here: the catalogue was held whole in each process, about 750 MB a site. Now the store holds it and the process holds none once the store answers, which is a number the Admin tab shows and a test reads.

/// <summary>Rule a. The test host's relational store answers its catalogue, so the count it holds in memory reads zero.</summary>
[Fact]
public async Task Once_the_store_answers_the_process_holds_no_catalogue()
{
    var client = factory.CreateClient();
    // On the relational store by name, so the suite booted on Cosmos DB asks the same question.
    client.DefaultRequestHeaders.Add(Backends.HeaderName, "sql");
    await client.GetAsync("/api/vehicles?limit=1");

    using var machines = JsonDocument.Parse(await client.GetStringAsync("/api/admin/machines"));
    var catalogues = machines.RootElement.GetProperty("container").GetProperty("catalogues").EnumerateArray().ToList();
    var relational = catalogues.Single(c => c.GetProperty("store").GetString()!.Contains("SQL", StringComparison.OrdinalIgnoreCase)).GetProperty("held");

    Assert.Equal("store", relational.GetProperty("mode").GetString());
    Assert.Equal(0, relational.GetProperty("held_in_memory").GetInt32());
    Assert.Equal(TestCatalogue.Vehicles, relational.GetProperty("filled").GetInt32());
    Assert.True(machines.RootElement.GetProperty("container").GetProperty("gc").GetProperty("heap_size_mb").GetDouble() > 0);
}

Live from api/TheYard.Tests/MemoryRulesTests.cs, region rule-a, read from this build at 99df7a8.

b. Every cache is bounded, and every cache expires

Why: a dictionary that only grows is a memory leak on a delay. Bound it by a count, by bytes or both, and give every entry an expiry.

Here: one cache type, BoundedCache, used for every cache a request fills. The reset-mail limit forgets stale addresses and stops at 10,000. A miss loads once a key, so a cache whose entry has just expired costs the store one query rather than one per visitor who asked in the same moment. A test names every collection field in the six production projects with what bounds it, and fails on a new one until somebody writes its bound down.

// Bounded by count and bytes, each entry expiring: the shape every cache here takes.
var pages = new BoundedCache<string, IReadOnlyList<CatalogueEntry>>(
    maxCount: 64, maxBytes: 16L << 20, expiry: TimeSpan.FromSeconds(5),
    bytesOf: page => 64 + page.Count * 1_500);
// Bounded by count and bytes, expiring after a bucket of the clock: a store's answer is reused
// for the five seconds a page of auctions cannot visibly change in, and never grows past the
// numbers here (ADR: The store does the work, rule b).
private readonly BoundedCache<string, SegmentCounts> _counts = new(512, 1L << 20, TimeSpan.FromSeconds(5), _ => 96);
private readonly BoundedCache<string, IReadOnlyList<CatalogueEntry>> _pages = new(64, 16L << 20, TimeSpan.FromSeconds(5), page => 64 + (page.Count * ExpectedVehicleBytes));
private readonly BoundedCache<string, CatalogueEntry> _vehicles = new(4_096, 8L << 20, TimeSpan.FromMinutes(10), _ => ExpectedVehicleBytes, comparer: StringComparer.Ordinal);

Live from api/TheYard.Application/Shared/Auction/CataloguePages.cs, region listing-cache, read from this build at 99df7a8.

c. Page, never materialise

Why: ToList() over a table brings every row into memory to keep a page of them. Put the filter, the order and the page in the query (Where, OrderBy, Skip, Take) so the database reads only as far as the page, and read with AsNoTracking when nothing is written back, so EF Core keeps no change-tracking copy of each row.

// The database orders by an index and stops at the page's last row.
var page = await db.Catalogue.AsNoTracking()
    .Where(row => row.Make == make)
    .OrderBy(row => row.Price).ThenBy(row => row.Seq)
    .Skip(offset).Take(limit)
    .ToListAsync();
/// <summary>
/// The filter as a WHERE clause: the store's own spellings compared with equality, the
/// segment as a comparison of the slot with now, every typed word as a range on the words
/// table (EfCatalogueWords.cs) or a status word that names the row's segment, and the ids somebody's
/// bid moved left out as one JSON parameter, however many there are.
/// </summary>
private IQueryable<CatalogueRow> Query(YardDbContext db, CatalogueFilter filter)
{
    long d = filter.SinceAnchorMs;
    var rows = db.Catalogue.AsNoTracking();
    if (_beyond)
    {
        rows = rows.Where(row => row.Seq < target);
    }
    if (filter.Make is { } make)
    {
        rows = rows.Where(row => row.Make == make);
    }
    if (filter.BodyStyle is { } bodyStyle)
    {
        rows = rows.Where(row => row.BodyStyle == bodyStyle);
    }
    if (filter.TitleStatus is { } titleStatus)
    {
        rows = rows.Where(row => row.TitleStatus == titleStatus);
    }
    if (filter.Province is { } province)
    {
        rows = rows.Where(row => row.Province == province);
    }
    // A typed word is looked for in every row, so on a SQLite file the schedule's columns are
    // then compared as "+ 0", which no index serves: SQLite's planner, which has no statistics,
    // reads the narrow words index alone rather than ranging over a schedule index and reading
    // every row in the range for its text. SQL Server's planner has statistics and is left to them.
    rows = (filter.Segment, local && filter.Tokens.Count > 0) switch
    {
        (CatalogueSegment.Live, false) => rows.Where(row => row.StartOffsetMs <= d && row.EndOffsetMs > d),
        (CatalogueSegment.Upcoming, false) => rows.Where(row => row.StartOffsetMs > d),
        (CatalogueSegment.Ended, false) => rows.Where(row => row.EndOffsetMs <= d),
        (CatalogueSegment.Live, true) => rows.Where(row => row.StartOffsetMs + 0 <= d && row.EndOffsetMs + 0 > d),
        (CatalogueSegment.Upcoming, true) => rows.Where(row => row.StartOffsetMs + 0 > d),
        (CatalogueSegment.Ended, true) => rows.Where(row => row.EndOffsetMs + 0 <= d),
        _ => rows,
    };
    if (filter.MinCondition is { } grade)
    {
        rows = rows.Where(row => row.ConditionGrade >= grade);
    }
    if (filter.PriceMin is { } low)
    {
        rows = rows.Where(row => row.Price >= low);
    }
    if (filter.PriceMax is { } high)
    {
        rows = rows.Where(row => row.Price <= high);
    }
    foreach (var token in filter.Tokens)
    {
        string text = token.Text;
        bool live = token.AlsoMatches.Contains(CatalogueSegment.Live);
        bool upcoming = token.AlsoMatches.Contains(CatalogueSegment.Upcoming);
        bool ended = token.AlsoMatches.Contains(CatalogueSegment.Ended);
        rows = _words.Holding(db, rows, text, live, upcoming, ended, d);
    }
    if (filter.Exclude.Count > 0)
    {
        string[] moved = [.. filter.Exclude];
        rows = rows.Where(row => !EF.Parameter(moved).Contains(row.Id));
    }
    return rows;
}

/// <summary>The order as an ORDER BY that one index serves, the place breaking every tie.</summary>
private static IQueryable<CatalogueRow> Ordered(IQueryable<CatalogueRow> rows, CatalogueOrder order) => order switch
{
    CatalogueOrder.EndAscending => rows.OrderBy(row => row.EndOffsetMs).ThenBy(row => row.Seq),
    CatalogueOrder.StartAscending => rows.OrderBy(row => row.StartOffsetMs).ThenBy(row => row.Seq),
    CatalogueOrder.EndDescending => rows.OrderByDescending(row => row.EndOffsetMs).ThenBy(row => row.Seq),
    CatalogueOrder.PriceAscending => rows.OrderBy(row => row.Price).ThenBy(row => row.Seq),
    CatalogueOrder.PriceDescending => rows.OrderByDescending(row => row.Price).ThenBy(row => row.Seq),
    CatalogueOrder.ConditionDescending => rows.OrderByDescending(row => row.ConditionGrade).ThenBy(row => row.Seq),
    CatalogueOrder.BidsDescending => rows.OrderByDescending(row => row.BidCount).ThenBy(row => row.Seq),
    _ => rows.OrderBy(row => row.Seq),
};

/// <summary>
/// The three segments' counts in one statement: one scan of the narrow counts index, three
/// conditional counts. A filter kept to one segment is counted without the segment in its WHERE
/// and the other two counts set to nothing here, because the conditional counts already split
/// the rows by segment, and a segment in the WHERE draws the planner to a range over a schedule
/// index that then reads every row in it for the other columns the filter names.
/// </summary>
public async Task<SegmentCounts> CountAsync(CatalogueFilter filter, CancellationToken cancellation)
{
    await using var db = await contexts.CreateDbContextAsync(cancellation);
    await _words.WordsBeforeQueryAsync(db, filter, cancellation);
    long d = filter.SinceAnchorMs;
    var counts = await Query(db, filter.In(CatalogueSegment.Any))
        .GroupBy(_ => 1)
        .Select(all => new
        {
            Live = all.Count(row => row.StartOffsetMs <= d && row.EndOffsetMs > d),
            Upcoming = all.Count(row => row.StartOffsetMs > d),
            Ended = all.Count(row => row.EndOffsetMs <= d),
        })
        .FirstOrDefaultAsync(cancellation);
    if (counts is null)
    {
        return SegmentCounts.None;
    }
    return filter.Segment switch
    {
        CatalogueSegment.Live => new SegmentCounts(counts.Live, 0, 0),
        CatalogueSegment.Upcoming => new SegmentCounts(0, counts.Upcoming, 0),
        CatalogueSegment.Ended => new SegmentCounts(0, 0, counts.Ended),
        _ => new SegmentCounts(counts.Live, counts.Upcoming, counts.Ended),
    };
}

/// <summary>One page: the ORDER BY, then OFFSET and FETCH in the database, so it reads only as far as the page.</summary>
public async Task<IReadOnlyList<CatalogueEntry>> PageAsync(CatalogueFilter filter, CatalogueOrder order, int skip, int take, CancellationToken cancellation)
{
    if (take <= 0)
    {
        return [];
    }
    await using var db = await contexts.CreateDbContextAsync(cancellation);
    await _words.WordsBeforeQueryAsync(db, filter, cancellation);
    bool word = local && filter.Tokens.Count > 0;
    if (!word && skip < DeepSkip)
    {
        var rows = await Ordered(Query(db, filter), order).Skip(skip).Take(take).ToListAsync(cancellation);
        return [.. rows.Select(row => row.ToEntry())];
    }
    // A page deep in the order, or a typed word on a SQLite file: the page's places first, then
    // its rows by their place. Deep, the places are read off the order's own index, which holds
    // the place, so the rows skipped over are index entries and never the table's rows (an
    // offset of 40,000 took 6.4 seconds on Azure SQL Database read the other way). With a word,
    // the places come off the words index in an order no index serves, so the planner cannot
    // walk an order's index reading every row for its text.
    var places = await (word ? Unindexed(Query(db, filter), order) : Ordered(Query(db, filter), order))
        .Skip(skip).Take(take).Select(row => row.Seq).ToListAsync(cancellation);
    if (places.Count == 0)
    {
        return [];
    }
    var found = (await db.Catalogue.AsNoTracking().Where(row => EF.Parameter(places).Contains(row.Seq)).ToListAsync(cancellation))
        .ToDictionary(row => row.Seq);
    return [.. places.Select(place => found[place].ToEntry())];
}

Live from api/TheYard.Infrastructure/Shared/Auction/EfVehicleCatalogue.cs, region ef-catalogue-query, read from this build at 99df7a8.

d. Streams over byte arrays past 85 KB

Why: an object of 85,000 bytes or more goes on the large object heap, which is collected only with the oldest generation and is not compacted by default, so a stream of large allocations fragments memory and makes the expensive collections run more often.

Here: reading a picture's size used to load the whole file, up to 941 KB, on every page that asked. It reads the header now: 24 bytes for a PNG, a seek to the frame marker for a JPEG, the first 32,768 characters of an SVG.

// Only the header is read. Reading the whole file to look at its first bytes put every
// photograph of a document, up to 941 KB, on the large object heap on every page that
// asked its size (ADR: The store does the work, rule d): a PNG's size is in its first 24
// bytes, a JPEG's in a frame marker the walk below seeks to, and an SVG's in its opening
// tag, which is in the first 32,768 characters of every drawing here.
using var stream = File.OpenRead(path);
if (extension == ".svg")
{
    char[] buffer = ArrayPool<char>.Shared.Rent(SvgHeadChars);
    try
    {
        using var reader = new StreamReader(stream);
        int read = reader.ReadBlock(buffer, 0, SvgHeadChars);
        return SvgSize(new string(buffer, 0, read));
    }
    finally
    {
        ArrayPool<char>.Shared.Return(buffer);
    }
}
Span<byte> head = stackalloc byte[24];
if (extension == ".png")
{
    return stream.ReadAtLeast(head, 24, throwOnEndOfStream: false) < 24
        ? null
        : ((head[16] << 24) | (head[17] << 16) | (head[18] << 8) | head[19],
            (head[20] << 24) | (head[21] << 16) | (head[22] << 8) | head[23]);
}
if (extension is ".jpg" or ".jpeg")
{
    Span<byte> marker = head[..9];
    long at = 2;
    while (at + 9 < stream.Length)
    {
        stream.Position = at;
        stream.ReadExactly(marker);
        if (marker[0] != 0xFF)
        {
            at++;
            continue;
        }
        if (marker[1] is >= 0xC0 and <= 0xCF and not 0xC4 and not 0xC8 and not 0xCC)
        {
            return ((marker[7] << 8) | marker[8], (marker[5] << 8) | marker[6]);
        }
        at += 2 + ((marker[2] << 8) | marker[3]);
    }
}
return null;

Live from api/TheYard.Api/Features/Docs/DocImages.cs, region header-only, read from this build at 99df7a8.

e. Workstation GC, concurrent, and a heap limit

Why: Server GC gives each core its own heap and is tuned for a machine of one's own; on a small shared plan, Workstation GC with concurrent collection keeps the footprint small. A heap limit makes a regression the runtime's problem inside its own share rather than the neighbours'.

Here: Workstation and concurrent since ADR-094; the limit is DOTNET_GCHeapHardLimitPercent=0x1E on the .NET web app (one since 19 October). Settings read from the environment are hexadecimal, so 0x1E is thirty per cent, and a plain 30 would have been forty-eight.

/// <summary>
/// Rule e. Both .NET sites carry a heap limit of thirty per cent, written in the hexadecimal the
/// runtime reads GC settings from the environment in, and keep their catalogues in the store.
/// </summary>
[Fact]
public void Each_site_has_a_heap_limit_of_thirty_per_cent_and_keeps_its_catalogue_in_the_store()
{
    string template = File.ReadAllText(Path.Combine(Repo.Root(), "infra", "appservice.bicep"));

    Assert.Contains("{ name: 'DOTNET_GCHeapHardLimitPercent', value: '0x1E' }", template, StringComparison.Ordinal);
    Assert.Equal(30, Convert.ToInt32("1E", 16));
    Assert.Contains("{ name: 'Catalogue__Keep', value: 'true' }", template, StringComparison.Ordinal);
    Assert.Contains("{ name: 'DOTNET_GCConserveMemory', value: '7' }", template, StringComparison.Ordinal);
    string render = File.ReadAllText(Path.Combine(Repo.Root(), "infra", "render.bicep"));
    Assert.Contains("{ name: 'NODE_OPTIONS', value: '--max-old-space-size=128' }", render, StringComparison.Ordinal);
    // A V8 flag Node does not allow in NODE_OPTIONS stops the process before it starts: this one took the
    // rendering service down for twenty minutes on 19 October.
    Assert.DoesNotMatch(@"value: .[^']*optimize_for_size", render);
}

Live from api/TheYard.Tests/MemoryRulesTests.cs, region rule-e, read from this build at 99df7a8.

f. Pool what is expensive

Why: a new HttpClient per call opens a new connection per call and can run a machine out of sockets; one per class is a pool per class. Microsoft's guideline for .NET 5 and later is one long-lived handler with PooledConnectionLifetime set, or IHttpClientFactory where clients are built by dependency injection. One CosmosClient per process, for the same reason.

Here: seven readers held seven static clients. They share one handler now, which retires each connection after two minutes so a changed DNS answer is picked up.

/// <summary>
/// One <see cref="SocketsHttpHandler"/> for the process, and a cheap client over it per call. This
/// is the pooling IHttpClientFactory gives code that is built by dependency injection, in the
/// form Microsoft documents for code that is not: the handler holds the connections and is never
/// disposed, each connection is retired after two minutes so a changed DNS answer is picked up,
/// and a client is a wrapper that carries one caller's timeout. Seven readers each held a static
/// client of their own before this, seven pools for the same few hosts.
/// </summary>
public static class OutboundHttp
{
    private static readonly SocketsHttpHandler Handler = new()
    {
        PooledConnectionLifetime = TimeSpan.FromMinutes(2),
        PooledConnectionIdleTimeout = TimeSpan.FromMinutes(1),
    };

    /// <summary>
    /// A handler that answers in place of the network for the flow that set it, and only that
    /// flow: a test routes its own reader's calls to recorded answers while every other test,
    /// running beside it, still sees the real pool (and, having no credential, reads nothing).
    /// </summary>
    private static readonly AsyncLocal<HttpMessageHandler?> Routed = new();

    /// <summary>A client over the shared pool with one caller's timeout; disposing it leaves the pool alone.</summary>
    /// <param name="timeout">How long one call may take.</param>
    public static Outbound Client(TimeSpan timeout) => new(new HttpClient(Routed.Value ?? Handler, disposeHandler: false) { Timeout = timeout });

    /// <summary>
    /// A client to this container's own address, with cookies off: the keep-warm loop, the performance proof and the
    /// page sweep each read the site the way a visitor does, and the proof holds one session per store by hand, which
    /// a cookie jar would merge. Its own connections, because the loopback is not a host the pool's readers call.
    /// </summary>
    /// <param name="address">The address the server listens on.</param>
    /// <param name="timeout">How long one call may take.</param>
    public static Outbound Loopback(Uri address, TimeSpan timeout) =>
        new(new HttpClient(new HttpClientHandler { UseCookies = false }) { BaseAddress = address, Timeout = timeout });

    /// <summary>Sends this flow's outbound calls to <paramref name="handler"/> until the returned scope is disposed. The suite's seam.</summary>
    /// <param name="handler">What answers in place of the network.</param>
    public static IDisposable RouteTo(HttpMessageHandler handler)
    {
        var before = Routed.Value;
        Routed.Value = handler;
        return new Restore(before);
    }

    /// <summary>
    /// The last day of the leaf certificate <paramref name="site"/> answers with, from one handshake with a handler
    /// of its own (the pool's connections are already open and would show no certificate); null when it cannot be
    /// read. The platform's own verdict on the chain is kept: an invalid chain still fails.
    /// </summary>
    /// <param name="site">The site's public https address.</param>
    /// <param name="cancellation">The reading's cancellation.</param>
    public static async Task<DateTimeOffset?> CertificateNotAfterAsync(Uri site, CancellationToken cancellation)
    {
        DateTimeOffset? notAfter = null;
        using var handler = new SocketsHttpHandler
        {
            SslOptions = new SslClientAuthenticationOptions
            {
                RemoteCertificateValidationCallback = (_, certificate, _, errors) =>
                {
                    if (certificate is X509Certificate2 leaf)
                    {
                        notAfter = new DateTimeOffset(leaf.NotAfter.ToUniversalTime(), TimeSpan.Zero);
                    }
                    return errors == SslPolicyErrors.None;
                },
            },
        };
        using var client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(10) };
        try
        {
            using var response = await client.GetAsync(new Uri(site, "/healthz"), cancellation);
        }
        catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or OperationCanceledException)
        {
            // No answer is no reading; the card says it was not read.
        }
        return notAfter;
    }

    private sealed class Restore(HttpMessageHandler? before) : IDisposable
    {
        /// <summary>Puts back the handler that was routed before, so a test that routed one leaves the next test the pool it expected.</summary>
        public void Dispose() => Routed.Value = before;
    }
}

/// <summary>
/// One caller's way out over HTTP. The host holds this, never an HttpClient: it builds the request and reads the
/// answer, and the socket is opened here. The members are the ones the readers use.
/// </summary>
/// <param name="client">The client this wraps; disposing the Outbound disposes it.</param>
public sealed class Outbound(HttpClient client) : IDisposable
{
    /// <summary>An Outbound over a client somebody else built: a test's in-memory server, or a recorded handler.</summary>
    /// <param name="client">The client.</param>
    public static Outbound Over(HttpClient client) => new(client);

    /// <summary>The address relative paths are read against, or null.</summary>
    public Uri? BaseAddress => client.BaseAddress;

    /// <summary>Sends a request the caller built.</summary>
    /// <param name="request">The request.</param>
    /// <param name="cancellation">The call's cancellation.</param>
    public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellation = default) => client.SendAsync(request, cancellation);

    /// <summary>Sends a request the caller built, answering once the headers arrive when <paramref name="completion"/> says so.</summary>
    /// <param name="request">The request.</param>
    /// <param name="completion">When the call counts as answered.</param>
    /// <param name="cancellation">The call's cancellation.</param>
    public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption completion, CancellationToken cancellation) => client.SendAsync(request, completion, cancellation);

    /// <summary>A GET.</summary>
    /// <param name="address">The address, absolute or relative to <see cref="BaseAddress"/>.</param>
    /// <param name="cancellation">The call's cancellation.</param>
    public Task<HttpResponseMessage> GetAsync(Uri address, CancellationToken cancellation = default) => client.GetAsync(address, cancellation);

    /// <summary>A GET that counts as answered when <paramref name="completion"/> says, the headers alone or the whole body.</summary>
    /// <param name="address">The address, absolute or relative to <see cref="BaseAddress"/>.</param>
    /// <param name="completion">When the call counts as answered.</param>
    /// <param name="cancellation">The call's cancellation.</param>
    public Task<HttpResponseMessage> GetAsync(Uri address, HttpCompletionOption completion, CancellationToken cancellation) => client.GetAsync(address, completion, cancellation);

    /// <summary>A GET.</summary>
    /// <param name="address">The address, absolute or relative to <see cref="BaseAddress"/>.</param>
    /// <param name="cancellation">The call's cancellation.</param>
    public Task<HttpResponseMessage> GetAsync(string address, CancellationToken cancellation = default) => client.GetAsync(address, cancellation);

    /// <summary>A POST of <paramref name="content"/>.</summary>
    /// <param name="address">The address.</param>
    /// <param name="content">The body.</param>
    /// <param name="cancellation">The call's cancellation.</param>
    public Task<HttpResponseMessage> PostAsync(string address, HttpContent content, CancellationToken cancellation = default) => client.PostAsync(address, content, cancellation);

    /// <summary>Disposes the client; a client over the shared pool leaves the pool alone.</summary>
    public void Dispose() => client.Dispose();
}

Live from api/TheYard.Infrastructure/Shared/Http/OutboundHttp.cs, region outbound-http, read from this build at 99df7a8.

g. No static collection that grows with traffic

Why: a static field lives as long as the process, so a static list that every request adds to is a leak that no collection can fix. Logs and recent errors are ring buffers of a fixed size.

Here: none was found; the request, log, error and SQL rings were already rings. The collection test above holds that.

h. Every app measured the same way

Why: a rule nobody measures is a guess. The Node rendering service ran under --max-old-space-size=192; whether that was tight or padded is a reading, not an opinion. Read on 19 October it used 18 MB of heap with 79 MB resident, so it runs under --max-old-space-size=128 now, with room still to spare. --optimize_for_size was tried beside it the same night and is a flag Node refuses in NODE_OPTIONS: the container did not start until it was taken out, and a test now holds it out, and each .NET site runs with DOTNET_GCConserveMemory=7, which has the collector compact the large object heap once it is fragmented.

Here: the rendering service's /readyz answers its heap used against its limit, and the .NET web app's /api/admin/machines answers the collector's own reading.

/// <summary>
/// The garbage collector's own account of this process, read once: the mode in effect, the
/// heap against the limit it may grow to, the two generations that hold long-lived and large
/// objects, how much of the heap is pinned or fragmented, and the share of time spent in
/// collections. The numbers ADR: The store does the work records before and after.
/// </summary>
public static object GcReading()
{
    var info = GC.GetGCMemoryInfo(GCKind.Any);
    static double Mb(long bytes) => Math.Round(bytes / 1024d / 1024d, 1);
    var generations = info.GenerationInfo;
    return new
    {
        mode = System.Runtime.GCSettings.IsServerGC ? "server" : "workstation",
        concurrent = AppContext.TryGetSwitch("System.GC.Concurrent", out bool concurrent) ? concurrent : true,
        heap_size_mb = Mb(info.HeapSizeBytes),
        committed_mb = Mb(info.TotalCommittedBytes),
        limit_mb = Mb(info.TotalAvailableMemoryBytes),
        gen2_mb = generations.Length > 2 ? Mb(generations[2].SizeAfterBytes) : 0,
        large_object_heap_mb = generations.Length > 3 ? Mb(generations[3].SizeAfterBytes) : 0,
        fragmented_mb = Mb(info.FragmentedBytes),
        pinned_objects = info.PinnedObjectsCount,
        pause_percent = Math.Round(info.PauseTimePercentage, 2),
        allocated_mb = Mb(GC.GetTotalAllocatedBytes(precise: false)),
        collections = new { gen0 = GC.CollectionCount(0), gen1 = GC.CollectionCount(1), gen2 = GC.CollectionCount(2) },
    };
}

Live from api/TheYard.Api/Shared/MachineReadings/Machines.cs, region gc-reading, read from this build at 99df7a8.

Reading the collector's own numbers

GET /api/admin/machines answers, for the process that served it, the GC mode in effect, the heap against the limit it may grow to, generation 2 and the large object heap after the last collection, how much is pinned or fragmented, the share of time spent in collections, and how many vehicles the process holds. The two numbers worth watching first are the heap against the limit and the catalogue held, which reads zero.

The card Memory against traffic, under Cloud infrastructure, draws the working set and the processor against requests a minute and reads red when memory climbs while traffic is flat, the shape a leak or an unbounded cache makes; on the readings the site kept it reads red the week the catalogue moved into each process (ADR: Memory follows traffic).

Further reading

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