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.
[Fact]
public async Task Once_the_store_answers_the_process_holds_no_catalogue()
{
var client = factory.CreateClient();
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.
var pages = new BoundedCache<string, IReadOnlyList<CatalogueEntry>>(
maxCount: 64, maxBytes: 16L << 20, expiry: TimeSpan.FromSeconds(5),
bytesOf: page => 64 + page.Count * 1_500);
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.
var page = await db.Catalogue.AsNoTracking()
.Where(row => row.Make == make)
.OrderBy(row => row.Price).ThenBy(row => row.Seq)
.Skip(offset).Take(limit)
.ToListAsync();
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);
}
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;
}
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),
};
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),
};
}
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())];
}
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.
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.
[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);
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.
public static class OutboundHttp
{
private static readonly SocketsHttpHandler Handler = new()
{
PooledConnectionLifetime = TimeSpan.FromMinutes(2),
PooledConnectionIdleTimeout = TimeSpan.FromMinutes(1),
};
private static readonly AsyncLocal<HttpMessageHandler?> Routed = new();
public static Outbound Client(TimeSpan timeout) => new(new HttpClient(Routed.Value ?? Handler, disposeHandler: false) { Timeout = timeout });
public static Outbound Loopback(Uri address, TimeSpan timeout) =>
new(new HttpClient(new HttpClientHandler { UseCookies = false }) { BaseAddress = address, Timeout = timeout });
public static IDisposable RouteTo(HttpMessageHandler handler)
{
var before = Routed.Value;
Routed.Value = handler;
return new Restore(before);
}
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)
{
}
return notAfter;
}
private sealed class Restore(HttpMessageHandler? before) : IDisposable
{
public void Dispose() => Routed.Value = before;
}
}
public sealed class Outbound(HttpClient client) : IDisposable
{
public static Outbound Over(HttpClient client) => new(client);
public Uri? BaseAddress => client.BaseAddress;
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellation = default) => client.SendAsync(request, cancellation);
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption completion, CancellationToken cancellation) => client.SendAsync(request, completion, cancellation);
public Task<HttpResponseMessage> GetAsync(Uri address, CancellationToken cancellation = default) => client.GetAsync(address, cancellation);
public Task<HttpResponseMessage> GetAsync(Uri address, HttpCompletionOption completion, CancellationToken cancellation) => client.GetAsync(address, completion, cancellation);
public Task<HttpResponseMessage> GetAsync(string address, CancellationToken cancellation = default) => client.GetAsync(address, cancellation);
public Task<HttpResponseMessage> PostAsync(string address, HttpContent content, CancellationToken cancellation = default) => client.PostAsync(address, content, cancellation);
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.
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.