Posts about .NET performance usually open with Span<T> and end with SIMD. I went looking for those in EstimateFlow, the app I've been building since April. The whole codebase has one ReadOnlySpan<byte>, no stackalloc, no ArrayPool and not a single benchmark.
It still has performance work in it, though none of it looks like those posts. Here's what I measured and fixed, and what I haven't.
76 of 90 seconds were one assertion
The slowest thing in the project was a unit test.
EstimateFlow prices jobs from a contractor's rates, and one test checks every possible combination of answers a customer could give for a trade. For a multi-select question, that means every subset of its options. Inside the loop it made a few assertions per scenario, and one of them was this:
scenarios[index].Additions.ShouldAllBe(addition => addition.Amount >= 0, description);
The unit suite took 90 seconds, and that one line accounted for 76 of them.
ShouldAllBe comes from Shouldly, and it takes an expression tree, not a delegate. That lets it print the failed condition in the error message. To evaluate the expression it has to compile it, and it compiles it on every call. Compiling an expression tree is slow, and I was doing it once for every combination of every trade.
The replacement makes the same check with an ordinary delegate:
// A plain check, not ShouldAllBe: that takes an expression and // compiles it on every call, which over every combination of a // trade's answers was most of this suite's running time. scenarios[index].Additions.All(addition => addition.Amount >= 0).ShouldBeTrue(description);
The suite now takes about 15 seconds.
My first suspect would have been the pricing code, since that's the code I wrote. It was fine. The time was going into a helper in the test library, and no amount of reading my own code would have found that.
A health check that hung for 30 seconds
The app has two health endpoints. /alive says the process is up. /health says it's ready for traffic, which includes being able to reach PostgreSQL.
I stopped the database container to see what a real outage would look like:
/health -> HTTP=000 TIME=30.006s (curl -m 30, no response) /alive -> Healthy HTTP=200 TIME=0.004s
/health didn't report "unhealthy". It didn't answer at all. The database check opens a connection, and with no timeout of its own it inherited Npgsql's connect timeout. The readiness probe runs every ten seconds, so in an outage each probe would have timed out without ever getting a response to act on.
The fix puts a ceiling on every check, wherever it was registered:
public static readonly TimeSpan ReadinessCheckTimeout = TimeSpan.FromSeconds(3);
builder.Services.PostConfigure<HealthCheckServiceOptions>(options =>
{
foreach (var registration in options.Registrations)
{
if (registration.Timeout == Timeout.InfiniteTimeSpan || registration.Timeout > ReadinessCheckTimeout)
{
registration.Timeout = ReadinessCheckTimeout;
}
}
});
With the database down, /health now returns 503 in 3.01 seconds. When the database comes back it returns 200 in 24ms, and the app doesn't need a restart. I haven't yet verified this against the real probe in Azure Container Apps, only locally.
I count this as performance work, although nothing got faster. A request that takes thirty seconds to fail does more damage than one that fails immediately.
The request that runs on every page view
Contractors install the estimator by adding a script tag to their website. That script is requested on every page of their site, by every visitor. It's the one endpoint in the app where traffic depends on somebody else's popularity.
I wanted to know which sites an estimator was installed on, which means recording something on each load. Writing to the database from that endpoint was out of the question. So the recording happens after the response has been sent, and it's built to drop work before it will slow anything down:
private readonly Channel<PendingLoad> _queue = Channel.CreateBounded<PendingLoad>(
new BoundedChannelOptions(QueueCapacity)
{
SingleReader = true,
FullMode = BoundedChannelFullMode.DropWrite,
});
private readonly ConcurrentDictionary<string, byte> _seen = new(StringComparer.Ordinal);
public void RecordLoad(Guid widgetId, string hostname)
{
// ...
var key = $"{widgetId:N}|{host}|{now.UtcDateTime:yyyyMMdd}";
if (_seen.Count >= MaxSeenKeys)
_seen.Clear();
// Already noted today: the database already knows, so skip the queue
// entirely. This is the branch that nearly every request takes.
if (!_seen.TryAdd(key, 0))
return;
There are three layers. The endpoint calls the recorder from HttpResponse.OnCompleted, so the visitor already has the script. The recorder keeps a set of "this estimator, this host, today" in memory, and almost every call ends at that lookup. Only the first load of the day for a given site gets as far as the channel, and the channel is bounded with DropWrite. If the database is down and the queue fills up, new entries are thrown away.
So a busy site costs one database write per day. A broken database costs me a statistic and costs the contractor's visitors nothing.
Analytics events from the estimator work the same way, with batching added. The background reader waits for one event, takes up to 200 more if they're already queued, and saves them in a single call.
Don't retry the thing a person is waiting for
Aspire's service defaults give every HttpClient a standard resilience handler with retries. For most outbound calls that's what you want. For the AI chat it was wrong:
// Default Aspire resilience retries 429; for AI chat this just blocks UI.
// Prefer fast failure with actionable message.
.AddStandardResilienceHandler(options =>
{
options.Retry.ShouldHandle = _ => ValueTask.FromResult(false);
});
When the model provider returns a rate-limit error, a retry with backoff means the customer stares at a typing indicator for several more seconds and then quite possibly gets the same error. I'd rather show them a clear message straight away.
The same endpoint is the only one that costs money per call, so it has three rate limits stacked on it: per IP address, per estimator, and per estimator per day. ASP.NET Core only applies one rate-limiting policy to an endpoint, so I wrote a small limiter that acquires from several in turn and releases what it holds if any of them refuses.
The inbox loaded everything
One fix was pure embarrassment. The lead inbox fetched every lead a contractor had ever received and then searched, filtered and sorted them in the browser.
Nobody notices that with ten leads. But the response grew with every lead a contractor received, and it was sent in full on every visit.
Paging, filtering and sorting now happen in the database, with the page size capped at 100. The search box waits 300ms after the last keystroke before it sends anything. I verified it: six quick keystrokes, one request.
The one span
For completeness, this is the only span in the codebase. Contractors can upload pictures for the options in their estimator, and the server checks what the bytes really are before storing them:
public static string? Detect(ReadOnlySpan<byte> data)
{
if (data.Length >= 3 && data[0] == 0xFF && data[1] == 0xD8 && data[2] == 0xFF)
{
return "image/jpeg";
}
if (data.Length >= 8 && data[..8].SequenceEqual<byte>([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]))
{
return "image/png";
}
if (data.Length >= 12
&& data[..4].SequenceEqual("RIFF"u8)
&& data.Slice(8, 4).SequenceEqual("WEBP"u8))
{
return "image/webp";
}
return null;
}
I used a span here because it reads well. Slicing the first eight bytes and comparing them to a literal is the clearest way to write the check, and it happens to allocate nothing. Those images are also the only responses in the app that carry a long-lived cache header. Their URL contains an id that changes whenever the picture changes, so they're served as immutable for a year.
What I haven't done
Here's what a performance review of this app would flag today.
- The loader script does a database lookup on every request and is served with no
Cache-Controlheader. I was careful to keep the install tracking off that path and then left the main query on it. It's the obvious next fix. - There's no caching layer anywhere: no
IMemoryCache, output caching or ETags. - There are no benchmarks and no load tests. Every number in this post came from a stopwatch,
curlor the test runner. - One method blocks on async code. It's in an EF interceptor that came with the project template:
DispatchDomainEvents(eventData.Context).GetAwaiter().GetResult(). It only runs if something calls the synchronousSaveChanges, but it's there. - The logging step in the request pipeline looks up the user's name in the database for every authenticated request, just to put it in a log line.
- A static property that returns the list of trades builds a new collection each time it's read.
None of these has hurt yet, and I can't tell you which will hurt first, because I haven't measured them.
What I take from this
None of the performance problems that mattered in this app was about CPU cycles. A test compiled the same expression thousands of times, nobody had set a timeout, and I had to decide what's allowed to happen on the busiest request.
The pipeline has one piece of permanent instrumentation, a behaviour that times every request and logs a warning for anything over 500ms. It's a dozen lines and it'll tell me where to look next.
Spans, pooling and SIMD are real tools. On this project I've had no reason to reach for them, and I'd be making one up if I did.
