📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

πŸ“š Interview question

As the technical lead for several .NET teams, how would you set performance budgets and stop performance regressions reaching production? Explain how you choose the budgets, what you test in CI (benchmarks, query counts, load tests), what you watch after release, and how you deal with noisy results and teams pushing back.

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.

Staff / Architect Architecture Expert benchmarkdotnet load-testing performance performance-budget regression-testing slo

🎯 Key points

  • Derive budgets from user-facing SLOs (p95/p99 latency, error rate per critical endpoint), then split into component budgets: SQL calls per request, allocations, payload size
  • Layered gates: fast deterministic checks on every PR (query count, payload size), benchmarks with allocation and time on dedicated runners, load tests nightly or pre-release
  • Handle noise: dedicated hardware, compare against a stored baseline with statistical tests and thresholds (e.g. >10% and significant), allocations as the stable signal
  • Load tests with explicit pass/fail criteria (k6 thresholds or Azure Load Testing failure criteria) on data with production-like volume and distribution, using an open load model
  • Production is the final gate: canary or slot swaps, distributed tracing and p95 alerts against baseline, Query Store regressed queries, profiler on demand, automatic rollback criteria
  • Budgets have owners and an error-budget policy: breaching means fix before new features, agreed with product
  • Keep it cheap and trusted: few critical paths, fast feedback, flaky checks fixed or removed, results visible on dashboards

⏱ 30-second answer

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.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"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."


From SLO to budgets

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

The layered gates

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

Making it stick

  • Owners: each budget belongs to a team, with a dashboard.
  • Policy: an error-budget breach puts reliability work ahead of features until it's fixed.
  • Exceptions: budget changes go through a PR with the reason and new numbers, like any other contract.

Production example

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].

πŸ” What the interviewer is checking

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

  • Derives budgets from user-facing SLOs and breaks them into testable proxies (command count, allocations, payload)
  • Separates deterministic PR checks from noisy benchmarks and load tests, and explains how to handle noise
  • Treats production as the final gate with canaries, comparative alerts and Query Store
  • Addresses ownership, error-budget policy and pushback

Red flags

  • "Run a load test before release" as the whole strategy
  • Wall-clock assertions on shared CI agents
  • No link between budgets and business goals, or no plan for flaky gates

πŸ“š Learn in depth

1. Why budgets, not just SLOs

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.

2. Deterministic checks beat timing checks in CI

Shared CI agents vary by 10–30% from run to run, so wall-clock assertions there flake. Counts don't:

  • SQL command count with an EF Core DbCommandInterceptor (or an OpenTelemetry span count).
  • Payload size from an integration test's response length.
  • Allocations: BenchmarkDotNet's [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.

3. Benchmarks in CI done properly

  • Run on dedicated, fixed hardware (a self-hosted runner), with power management and turbo controlled where possible.
  • Store results (BenchmarkDotNet JSON exporters) as the baseline from main.
  • Compare with a statistical test (BenchmarkDotNet supports statistical tests such as Mann–Whitney with a threshold, and the dotnet/performance repo's ResultsComparer tool does similar comparisons), and fail only on a significant change above a threshold.
  • Treat allocation regressions as stricter than time regressions, because they are less noisy.

4. Load tests that mean something

  • Production-like data, both in volume and in distribution: skew (a few customers with 100,000 orders), realistic text lengths and null rates, and hot keys. Plans, memory grants and cache hit rates depend on all of that, so uniform synthetic data can hide parameter-sniffing and hot-key problems.
  • Production-like traffic mix: the ratio of reads to writes and which endpoints get called, taken from Application Insights.
  • Open load model (constant arrival rate, e.g. k6's constant-arrival-rate) so slow responses don't reduce the load and hide problems (coordinated omission).
  • Pass/fail thresholds in the script (http_req_duration: ['p(95)<300']) or Azure Load Testing failure criteria, so the run is a gate, not a report.
  • Run in Azure Australia East if production is there, so latency to dependencies is realistic.

5. Production as the last gate

  • Progressive delivery: App Service deployment slots or a canary percentage, with a comparison period.
  • Distributed tracing (OpenTelemetry into Application Insights): compare span durations and dependency calls per request between versions to find which hop regressed.
  • Alerts on change, not just on absolute values: p95 now vs the same hour last week, and dependency calls per request.
  • On-demand profiling: the Application Insights Profiler or dotnet-monitor trace collection triggered on high CPU or latency after a deploy.
  • Query Store: regressed queries after a deploy, with automatic plan correction (FORCE_LAST_GOOD_PLAN, on by default in Azure SQL Database) as a safety net, not a fix.
  • Rollback criteria written down before the release.

6. The organisational part

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.

Try it yourself

  1. Add a command-counting DbCommandInterceptor to an integration test and assert a budget for one endpoint.
  2. Export BenchmarkDotNet results to JSON on main, then compare a branch with a statistical threshold and see what counts as noise on your runner.
  3. Write a k6 script with constant-arrival-rate and a p(95) threshold, and make it fail by adding a deliberate Task.Delay.
  4. Seed test data with a skewed distribution (one customer with 50,000 orders) and see whether any query plan changes.
  5. Set up an Application Insights alert comparing an endpoint's p95 with its value a week earlier.
  6. Write a one-page error-budget policy for one critical endpoint.

πŸ’» Code

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' } });
}

⚠ Common mistakes

  • Mistake: Optimising without measuring, for example setting budgets from guesses instead of current baselines and SLOs. Why it is wrong: Budgets that are too tight block every PR; too loose catches nothing. Instead: Measure current p95, command counts and allocations, then set budgets with headroom against the SLO.
  • Mistake: Micro-optimising cold paths by benchmarking everything. Why it is wrong: The suite becomes slow and noisy, and hot paths get no more attention than admin screens. Instead: Budget the few critical journeys and the hot code under them.
  • Mistake: Asserting wall-clock times in unit tests on shared CI agents. Why it is wrong: 10–30% run-to-run noise makes the tests flaky, so people ignore or delete them. Instead: Assert counts in CI; measure time and allocations with BenchmarkDotNet on dedicated runners with statistical comparison.
  • Mistake: Load testing on a near-empty database, or on uniform synthetic data. Why it is wrong: Plans, memory grants and cache hit rates depend on volume and on the distribution (skewed customers, hot keys), so the test misses parameter-sniffing and hot-key problems. Instead: Generate synthetic or masked data that matches production volume, skew and shape. Copying real personal data into test environments is a Privacy Act risk.
  • Mistake: Using a closed load model with fixed virtual users. Why it is wrong: When the system slows down, load drops too (coordinated omission), so the test looks healthier than reality. Instead: Use a constant arrival rate.
  • Mistake: Treating the CI gates as enough and skipping production checks. Why it is wrong: Real traffic patterns, data skew and plan changes only show up live. Instead: Use canaries, distributed tracing, comparative p95 alerts and Query Store regression checks with rollback criteria.
  • Mistake: Budgets with no owner or consequence. Why it is wrong: Breaches become background noise. Instead: Assign owners, put budgets in the definition of done, and agree an error-budget policy with product.

πŸ› Senior insight: trade-offs

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.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions nightly load tests or coordinated omission Why: Checks they can design realistic load tests and read percentiles correctly.
    How to answer

    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.

  2. When: Candidate mentions BenchmarkDotNet in CI Why: Checks they can write benchmarks whose results are valid enough to gate on.
    How to answer

    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:

    • marks one method Baseline = true, so you get a Ratio column;
    • adds [MemoryDiagnoser] for allocated bytes per operation and GC counts;
    • builds inputs in [GlobalSetup] from fields with [Params] for realistic sizes, not constants the JIT can fold;
    • makes the work observable, by returning the result or consuming the sequence, so the JIT can't remove it as dead code.

    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.

  3. When: Candidate mentions catching regressions in production after release Why: Checks their end-to-end investigation when a regression does reach production.
    How to answer

    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.

πŸ›  Real-world problems: how you handle them

Repeated p95 regressions after releases across several teams
Situation
[Online marketplace] with [four] .NET teams sharing Azure SQL and an API gateway in Australia East. Over [two quarters], [five] releases caused p95 incidents on checkout or search, each found by customers or on-call after the fact.
Signals
Application Insights p95 alerts firing hours after deploys; Query Store showing new expensive queries after releases; post-incident reviews repeatedly finding N+1 queries and over-fetching that tests didn't catch; teams disagreeing on what 'fast enough' meant.
Investigation
Reviewed the incidents: [four of five] were query-count or payload regressions detectable by deterministic tests, and one was pool exhaustion visible only under load. Measured current baselines (p95, SQL commands per request, payload size) for the [eight] critical endpoints, and tested CI runner noise with repeated BenchmarkDotNet runs: [±20%] on shared agents.
Resolution
Agreed SLOs with product for the critical journeys and derived endpoint budgets. Added per-PR budget tests (command count, payload) with Testcontainers, moved benchmarks to a dedicated runner with baseline comparison, added a nightly k6 load test with thresholds, and introduced slot swaps with a 30-minute comparative p95 check and rollback criteria.
Prevention
Error-budget policy signed off by product; budget dashboard per team; owners triage nightly failures within one business day; quarterly review of budgets against traffic growth; ADR describing the gate layers.

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].

More in EF and SQL Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me