Designing a team-wide performance budget and regression system: SLO-derived budgets, BenchmarkDotNet and SQL query-count checks in CI, scheduled load tests with pass/fail thresholds, production p95 and Query Store alerts, handling noise, and getting teams to own it.
I start from user-facing SLOs: p95 and p99 latency and error rate for the handful of critical journeys. I break those into component budgets a developer can check: SQL commands per request, allocations per operation, payload size, and downstream calls. Regression checks are layered by cost and noise. Every PR gets deterministic checks that never flake: query-count tests and payload-size checks. BenchmarkDotNet (time and allocations) runs on dedicated runners against a stored baseline with statistical thresholds. Load tests run nightly or before release with explicit pass/fail criteria. Production is the final gate: canary releases, distributed tracing, p95 alerts against baseline, Query Store regressions and rollback criteria. Budgets need owners and an error-budget policy agreed with product, or they get ignored. The trade-off is pipeline time and maintenance against catching regressions while they are cheap to fix.
"A performance budget only works if it's tied to something the business cares about and checked somewhere developers will see it. So I start with SLOs for the few journeys that matter, say checkout p95 under 300 ms and search p95 under 500 ms at our expected peak. Then I translate them into component budgets a developer can reason about in a PR: this endpoint makes at most two SQL commands, allocates under 50 KB per request, and returns under 100 KB. Those are things a test can check deterministically.
Then I layer the checks by cost and noise. On every PR: query-count tests with an EF Core interceptor, allocation assertions and payload-size checks. They're fast and they never flake. Micro-benchmarks with BenchmarkDotNet for hot library code run on a dedicated runner, not shared cloud agents, against a stored baseline, failing only on a statistically significant regression above about 10%. Nightly, a k6 or Azure Load Testing run against a production-like environment with real data volumes, with thresholds on p95 and error rate. After release, canaries or slot swaps, with Application Insights alerts comparing p95 with the previous version, and Query Store regressed-query checks. For example, at [company] we [introduced query-count and nightly load-test gates across [four] teams], and in [the first quarter] they caught [several] N+1 regressions before release. Production p95 incidents dropped from [x] to [y].
The mistake I see is a big, noisy perf suite that fails randomly, so people learn to ignore it. A small, trusted set of gates beats a comprehensive one nobody believes. And there has to be an error-budget policy: if checkout blows its budget, the team fixes that before shipping features. That's a conversation with product, not just a pipeline setting."
| Level | Example | Checked by |
|---|---|---|
| User SLO | Checkout p95 < 300 ms, errors < 0.5% at 400 req/s | Load tests, production monitoring |
| Endpoint budget | β€ 2 SQL commands, β€ 1 downstream call, response β€ 100 KB | Integration tests in CI |
| Code budget | Pricing calculation β€ 5 Β΅s and 0 allocations | BenchmarkDotNet on dedicated runner |
| Data budget | Top queries β€ N logical reads per execution | Query Store baseline, tests on seeded data |
| Gate | When | Speed | Noise | Catches |
|---|---|---|---|---|
| Query count / allocation / payload tests | Every PR | Seconds | None (deterministic) | N+1, over-fetching, accidental allocations |
| BenchmarkDotNet vs baseline | PRs touching hot code, or nightly | Minutes | Medium; needs dedicated hardware | CPU and allocation regressions in hot code |
| Load test with thresholds | Nightly and pre-release | 15β60 min | Medium | Contention, pool exhaustion, plan problems at scale |
| Canary + p95 alert + Query Store | Every release | Live | Real traffic | Everything the others missed |
Across [three] teams we set budgets for [eight] critical endpoints. A query-count test blocked a PR that turned [1] SQL command into [51]. The nightly load test caught a connection pool exhaustion at [300 req/s] before a [peak trading] event. Over [six months], p95-related incidents went from [five] to [one].
Checks whether the candidate can design a sustainable, organisation-level system for performance, linking business SLOs to developer-checkable budgets and layered, trustworthy gates.
Green flags
Red flags
An SLO ("checkout p95 < 300 ms") is measured in production, after the fact. Developers need something they can check before merge. A budget breaks the SLO down into parts:
Checkout p95 300 ms
ββ API gateway + network 40 ms
ββ App CPU 30 ms
ββ SQL (β€ 2 commands) 60 ms
ββ Payment provider (p95) 150 ms
ββ Headroom 20 ms
Each part has a proxy that can be tested: command count, allocations, payload size.
Shared CI agents vary by 10β30% from run to run, so wall-clock assertions there flake. Counts don't:
DbCommandInterceptor (or an OpenTelemetry span count).[MemoryDiagnoser] Allocated column is the reliable measure and is stable across runs. GC.GetAllocatedBytesForCurrentThread() still works in .NET 10 for synchronous code, but async code resumes on other threads, so it under-counts across awaits. GC.GetTotalAllocatedBytes(precise: true) is process-wide and picks up background work. For endpoint-level allocation budgets, use a benchmark of the handler rather than an assertion inside an HTTP integration test.constant-arrival-rate) so slow responses don't reduce the load and hide problems (coordinated omission).http_req_duration: ['p(95)<300']) or Azure Load Testing failure criteria, so the run is a gate, not a report.FORCE_LAST_GOOD_PLAN, on by default in Azure SQL Database) as a safety net, not a fix.Budgets without consequences get ignored. An error-budget policy (from SRE practice) agreed with product says what happens when a budget is breached: the team prioritises the fix. Make it part of how everyone works: budgets in the definition of done, a short onboarding session on reading the dashboards, and budget status reviewed in sprint reviews with product owners, not only by engineers. Keep the gate set small and trusted. Fix or delete a flaky gate within a sprint.
DbCommandInterceptor to an integration test and assert a budget for one endpoint.constant-arrival-rate and a p(95) threshold, and make it fail by adding a deliberate Task.Delay.A per-PR budget test that is deterministic: SQL command count, allocations and payload size for one endpoint.
namespace Shop.Api.PerformanceBudgets;
using System.Data.Common;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
public sealed class CommandCounter : DbCommandInterceptor
{
private int _count;
public int Count => Volatile.Read(ref _count);
public void Reset() => Interlocked.Exchange(ref _count, 0);
public override ValueTask<DbDataReader> ReaderExecutedAsync(DbCommand command, CommandExecutedEventData eventData,
DbDataReader result, CancellationToken cancellationToken = default)
{
Interlocked.Increment(ref _count);
return ValueTask.FromResult(result);
}
}
// ShopApiFactory: a WebApplicationFactory<Program> that points the DbContext at SQL Server in Testcontainers,
// seeds production-like volumes, and registers CommandCounter as a singleton interceptor.
public sealed class CheckoutBudgetTests(ShopApiFactory factory) : IClassFixture<ShopApiFactory>
{
[Fact]
public async Task Cart_summary_stays_within_budget()
{
var counter = factory.Services.GetRequiredService<CommandCounter>();
var client = factory.CreateClient();
await client.GetAsync("/api/cart/42/summary", TestContext.Current.CancellationToken); // warm-up: JIT, query cache
counter.Reset();
var response = await client.GetAsync("/api/cart/42/summary", TestContext.Current.CancellationToken);
var body = await response.Content.ReadAsByteArrayAsync(TestContext.Current.CancellationToken);
Assert.True(counter.Count <= 2, $"SQL budget is 2 commands, got {counter.Count}"); // catches N+1
Assert.True(body.Length <= 100_000, $"Payload budget is 100 KB, got {body.Length}"); // catches over-fetching
}
}
A nightly load test whose thresholds make it a gate (k6, open load model):
import http from 'k6/http';
export const options = {
scenarios: {
checkout: { executor: 'constant-arrival-rate', rate: 400, timeUnit: '1s', duration: '15m',
preAllocatedVUs: 200, maxVUs: 1000 },
},
thresholds: {
'http_req_duration{endpoint:checkout}': ['p(95)<300', 'p(99)<800'], // the SLO as a pass/fail rule
http_req_failed: ['rate<0.005'],
},
};
export default function () {
http.post(`${__ENV.BASE_URL}/api/checkout`, JSON.stringify({ cartId: Math.ceil(Math.random() * 50000) }),
{ headers: { 'Content-Type': 'application/json' }, tags: { endpoint: 'checkout' } });
}
At staff level the hard part is not the tooling, it's trust and ownership. A gate that flakes once a week gets bypassed within a month, so I'd rather have five deterministic checks everyone believes than fifty timing checks nobody reads. I keep the expensive, noisy checks (load tests, benchmarks) off the PR path and give them a clear owner who triages failures within a day.
| Gate | When it fits | Cost | When not to |
|---|---|---|---|
| Deterministic budget tests (query count, allocations, payload) | Every critical endpoint, every PR | Low; needs a Testcontainers fixture | Highly dynamic queries with no stable count |
| BenchmarkDotNet vs baseline | Hot library code (parsers, pricing, serialisation) | Dedicated runner, baseline storage | App code dominated by I/O |
| Nightly load test with thresholds | Services with known peaks and SLOs | Environment cost, data setup | Very low-traffic internal tools |
| Canary + comparative alerts | Any service with meaningful traffic | Deployment tooling, alert tuning | Batch jobs (use duration SLOs instead) |
I'd also budget money alongside latency: vCores, DTUs and Redis tier. On Azure, a performance regression often shows up first on the bill.
A useful load test answers a specific question: can we handle peak, where do we break, or do we degrade over hours. So I choose the test type (load, stress, soak or spike) and model the real workload: the endpoint mix, data volumes, auth and cache hit rates, in a production-like environment.
I use an open model (a target arrival rate, like k6's constant-arrival-rate) because a closed model with a fixed number of virtual users slows down when the server does, which causes coordinated omission and hides the tail.
I report p50, p95 and p99 and error rate, never averages, and read them next to server-side metrics to see which resource saturates first. The trade-off: realistic tests cost environment and data effort, but unrealistic ones give confident wrong answers.
BenchmarkDotNet turns a method into a properly measured experiment: it builds a separate Release process, does warm-up and pilot runs so tiered JIT has finished, runs many iterations and reports mean, error and standard deviation.
A correct benchmark:
Baseline = true, so you get a Ratio column;[MemoryDiagnoser] for allocated bytes per operation and GC counts;[GlobalSetup] from fields with [Params] for realistic sizes, not constants the JIT can fold;Then I check that the difference is bigger than the error, on a quiet machine, before believing it. The trade-off: a micro-benchmark proves one method is faster in isolation; it doesn't prove the endpoint is, so I confirm with production numbers.
First I protect users: if the regression hurts, I roll back or turn off the feature flag, which also confirms the release caused it. If I can capture a short trace in a minute I do; if not, speed wins and I reproduce later in a test environment. I confirm it's abnormal against the historical baseline for the same time and traffic mix.
Then I narrow it down with Application Insights or OpenTelemetry: every operation or one endpoint, every instance or some, and which dependency or in-process span grew. I diff the release: code, package upgrades, config and flags, base image and infrastructure.
Next dotnet-counters tells me the class of problem (CPU, GC, ThreadPool, contention) and dotnet-trace or the Application Insights Profiler shows the code. I reproduce with a load test of old vs new builds, fix, verify p95 in production, and add a performance gate. Throughout, I keep stakeholders updated.
How to tell it (STAR)
**S:** At [company], [four] teams kept shipping performance regressions that customers found first: [five] incidents in [two quarters]. **T:** As [tech lead], I was asked to stop that without slowing delivery. **A:** I analysed the incidents and found most were N+1 or payload regressions a deterministic test could catch. With product, I set SLOs for the critical journeys and turned them into budgets per endpoint. We added fast query-count and payload tests on every PR, moved benchmarks to a dedicated runner, ran a nightly load test with p95 thresholds, and added a comparative p95 check on slot swaps. **R:** In the next [six months] the gates blocked [several] regressions before merge, p95 incidents fell from [five] to [one], and PR pipeline time grew by only [about two minutes].
Last updated 23 Nov 2026.