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

πŸ“š Interview question

How do you load test a .NET API properly? Explain how you design a realistic workload with k6 or Azure Load Testing, open vs closed load models and coordinated omission, how you read percentiles, and how you find the breaking point.

Load testing ASP.NET Core APIs: test types (smoke, load, stress, soak, spike), realistic workload modelling, open vs closed models and coordinated omission, k6 and Azure Load Testing, reading p50/p95/p99 and finding the saturation point with server-side metrics.

Mid-Level Theory Intermediate azure-load-testing k6 load-testing percentiles performance profiling

🎯 Key points

  • Test types: smoke, load (expected peak), stress (find the limit), soak (hours, leaks), spike
  • Realistic workload: real endpoint mix, data volumes, think time, auth, cache hit rates, production-like environment
  • Open model (arrival rate, k6 constant-arrival-rate) vs closed model (fixed VUs) that hides slowdowns
  • Coordinated omission: a closed-loop tool waits on slow responses and under-reports tail latency
  • Report p50/p95/p99 and error rate, not averages; never average percentiles
  • Correlate client results with server metrics (CPU, ThreadPool queue, DB DTU, dependency latency)
  • Find the knee: increase rate until latency or errors rise; the bottleneck is the first resource to saturate
  • Thresholds as pass/fail in CI (e.g. p95 < 300 ms, errors < 1%)

⏱ 30-second 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.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"I start with the question. 'Can we handle Black Friday at 3Γ— normal traffic?' is a load test at a target rate. 'Where does it break?' is a stress test that ramps until latency or errors climb. 'Does it leak?' is a soak test for hours at normal load. Each needs a different shape, and mixing them gives numbers nobody can act on.

Then I make the workload realistic, which is where most load tests fail. I take the endpoint mix and payload sizes from production telemetry, use realistic data volumes so queries hit the same plans, include authentication, and get the cache hit rate roughly right; a test that hits one cached URL measures the cache. I use an open model: k6's constant-arrival-rate or ramping-arrival-rate executor sends requests at a fixed rate regardless of how fast the server responds. A closed model, where 50 virtual users wait for each response before sending the next, quietly sends fewer requests when the server slows down. That's coordinated omission: the tool stops measuring exactly when things get bad, and p99 looks fine.

When I read results, it's percentiles and errors, side by side with server metrics: CPU, ThreadPool queue length, GC, database DTU or CPU, and dependency latency in Application Insights. The point where p95 bends upward is the knee, and the first resource to saturate there is the bottleneck. The mistake I see is reporting average latency from a laptop against a shared dev environment, which tells you nothing about production."


Test types

Type Shape Answers
Smoke 1–5 VUs, 1 min Does the script and environment work?
Load Expected peak rate, 15–30 min Do we meet the SLO at peak?
Stress Ramp up until it breaks Where is the limit, what fails first?
Soak Normal rate, 4–24 h Leaks, pool exhaustion, log growth
Spike Sudden jump (e.g. 10Γ— for 2 min) Autoscale and recovery behaviour

Open vs closed model

Closed (fixed VUs) Open (arrival rate)
Load when server slows Drops automatically Stays at target; queue builds
Matches Fixed pool of clients, batch jobs Public APIs, user traffic
Tail latency Under-reported (coordinated omission) Realistic
k6 executor constant-vus, ramping-vus constant-arrival-rate, ramping-arrival-rate

Tools

Tool Notes
k6 JavaScript scripts, open-model executors, thresholds; run locally, in CI or Grafana Cloud
Azure Load Testing Managed service running JMeter or Locust scripts at scale from Azure regions, with server-side Azure Monitor metrics on the same dashboard
NBomber C# load tests if the team prefers .NET
bombardier / wrk Quick single-endpoint throughput checks

Production example

Before a seasonal campaign, a retail API was load tested at the forecast 900 requests/s with an open model and production-like data. The knee appeared at 650 requests/s: p95 jumped from 180 ms to 2.4 s while app CPU was 45%, and Azure SQL hit 100% DTU on one query. Adding an index and caching the product listing moved the knee to 1,500 requests/s, and the campaign peaked at 820 requests/s with p95 at 210 ms.

πŸ” What the interviewer is checking

Checks that the candidate can run a load test that produces trustworthy, actionable numbers.

Green flags

  • Chooses the test type from the question being asked
  • Explains open vs closed models and coordinated omission
  • Reports percentiles with error rate and server-side metrics
  • Talks about realistic data and the knee

Red flags

  • Quotes averages from a laptop test
  • Doesn't know what coordinated omission is
  • No link between client results and server resources

πŸ“š Learn in depth

1. What a load test measures

 load generator ──requests at rate λ──▢  API  ──▢ dependencies (SQL, Redis, HTTP)
      β”‚                                     β”‚
      β–Ό                                     β–Ό
 client view: latency percentiles,     server view: CPU, ThreadPool queue, GC,
 errors, status codes, achieved rate    connection pools, DB CPU/DTU, waits

You need both views. The client view says whether you meet the goal; the server view says why not. Look at status codes as well as latency: 429s from rate limiting, 503s from autoscale lag and 500s from pool exhaustion each point at a different bottleneck.

2. Little's Law, the knee and capacity planning

For a stable system, concurrency = throughput Γ— latency (L = Ξ»W). At 500 requests/s and 100 ms, about 50 requests are in flight. As load rises, some resource (CPU, a connection pool of 100, database workers) saturates; requests queue, latency rises, and in-flight work grows until timeouts and errors start. Plotted, throughput flattens and latency bends sharply upward: the knee.

The knee is the input to capacity planning. If the knee is 1,500 requests/s on 4 instances and limited by app CPU, you can reason about scaling out; if it is limited by the database, more app instances will not help and may make it worse. Operate comfortably below it (often 60–70% of the knee rate) and set autoscale rules to add capacity before you get there. Re-measure the knee after significant releases, because it moves.

3. Coordinated omission

A closed-loop client sends request n+1 only after response n returns. Suppose 10 virtual users normally get 100 ms responses, so they send 100 requests per second. If the server stalls for 2 seconds, each user is stuck waiting on one request, so during the stall the tool sends 10 requests instead of the 200 real users would have sent. It records 10 slow samples and silently omits the other 190 that would have queued behind the stall. The percentiles are computed from a sample that excludes the worst period, so p99 can look like 150 ms when real users saw seconds. The tool has 'coordinated' with the server to avoid measuring the bad moments.

Fixes: use an open-model executor (fixed arrival rate), or tools that correct for it (wrk2, HdrHistogram-based correction). k6's arrival-rate executors keep sending and allocate more VUs as needed; if it runs out (maxVUs), it reports dropped iterations, which is itself a signal.

4. Percentiles done right

  • p50 is the typical user; p95/p99 are the unlucky ones, and on a page that calls 10 APIs, most page loads will hit at least one API's p95.
  • Never average percentiles across instances or time windows; merge histograms instead.
  • Report percentiles with the achieved request rate and error rate; a fast p95 with 5% errors is a failure.

5. Realism checklist

  • Endpoint mix and payloads from production telemetry (Application Insights request counts), weighted by business impact (checkout matters more than a settings page).
  • Data volume similar to production (a 1,000-row table hides missing indexes).
  • Authentication and token refresh in the script.
  • Cache hit rate similar to production (randomise IDs from a realistic distribution).
  • Same SKU, instance count, region (Australia East if that's production) and autoscale settings.
  • Network conditions: generators in the region your users come from, through the same gateway, WAF and TLS termination.
  • Downstream services: real, or realistic stubs with production-like latency and error rates; monitor them during the test so a slow dependency isn't mistaken for a slow API, and never load test a partner's production API without agreement.
  • Enough load generators: scale generator count with the target rate and watch their CPU and network; a saturated generator caps the test and looks like a server limit.

6. In CI and afterwards

Run a short load test on every release candidate with thresholds (http_req_duration: ['p(95)<300'], http_req_failed: ['rate<0.01']) against a stable environment; run stress and soak tests on a schedule. Keep dashboards and alerts on during tests so you also test your monitoring. After each significant test, write a one-page summary: workload, knee, limiting resource, actions. Track results over time to catch gradual regressions.

Try it yourself

  1. Write a k6 script with constant-vus and another with constant-arrival-rate against an endpoint with an artificial 2-second stall every 30 seconds; compare p99.
  2. Ramp the arrival rate on a sample API and plot achieved rate vs p95 to find the knee; watch dotnet-counters during the run.
  3. Add thresholds and make the test fail the CI step.
  4. Run the same JMeter or Locust script in Azure Load Testing and view the app's Azure Monitor metrics in the same dashboard.
  5. Run a 2-hour soak and plot gc-heap-size.

πŸ’» Code

A k6 script using an open model, a realistic endpoint mix and pass/fail thresholds.

import http from 'k6/http';
import { check } from 'k6';

export const options = {
  scenarios: {
    peak: {
      executor: 'ramping-arrival-rate',   // open model: no coordinated omission
      startRate: 100,
      timeUnit: '1s',
      preAllocatedVUs: 200,
      maxVUs: 1000,                       // if exhausted, k6 reports dropped iterations
      stages: [
        { target: 900, duration: '5m' },  // ramp to forecast peak
        { target: 900, duration: '15m' }, // hold
      ],
    },
  },
  thresholds: {
    http_req_failed: ['rate<0.01'],                    // < 1% errors
    'http_req_duration{name:search}': ['p(95)<300'],   // SLO per endpoint
    'http_req_duration{name:product}': ['p(95)<150'],
  },
};

const token = __ENV.TEST_TOKEN;                    // synthetic test account
const productIds = JSON.parse(open('./product-ids.json')); // realistic id distribution

export default function () {
  const headers = { Authorization: `Bearer ${token}` };
  // 70/30 mix taken from production request counts
  if (Math.random() < 0.7) {
    const id = productIds[Math.floor(Math.random() * productIds.length)];
    const res = http.get(`${__ENV.BASE_URL}/api/products/${id}`, { headers, tags: { name: 'product' } });
    check(res, { 'product 200': (r) => r.status === 200 });
  } else {
    const res = http.get(`${__ENV.BASE_URL}/api/search?q=shoes&page=1`, { headers, tags: { name: 'search' } });
    check(res, { 'search 200': (r) => r.status === 200 });
  }
}

Watching the server while the test runs:

dotnet-counters monitor -n Shop.Api \
  --counters System.Runtime[cpu-usage,threadpool-queue-length,gc-heap-size],Microsoft.AspNetCore.Hosting

⚠ Common mistakes

  • Mistake: Optimising without measuring under load: tuning code that a profile at idle showed. Why it is wrong: Bottlenecks under load (pools, locks, the database) are different from idle hot spots. Instead: Find the knee and the first saturated resource, then optimise that.
  • Mistake: Micro-optimising cold paths the load test barely touches. Why it is wrong: The workload mix decides what matters. Instead: Weight effort by production traffic share and business impact.
  • Mistake: Using a closed model (fixed VUs) for a public API. Why it is wrong: Coordinated omission hides tail latency. Instead: Arrival-rate executors.
  • Mistake: Mixing test goals in one run (ramping to failure and then holding for hours). Why it is wrong: You can't tell whether a slowdown is the capacity limit or a leak, so neither number is usable. Instead: Separate stress, load and soak runs, each with one question.
  • Mistake: Reporting average latency. Why it is wrong: Averages hide the tail users feel. Instead: p50/p95/p99 plus error rate, status codes and achieved rate.
  • Mistake: Testing one cached URL with tiny data. Why it is wrong: You measure the cache and a table that fits in memory. Instead: Realistic data volumes and ID distribution.
  • Mistake: Load testing a shared dev environment from a laptop. Why it is wrong: The laptop or network becomes the bottleneck, and results don't transfer. Instead: Production-like environment and distributed generators (Azure Load Testing).
  • Mistake: Ignoring server metrics. Why it is wrong: You know it's slow but not why. Instead: Read CPU, ThreadPool, GC, pools and DB metrics alongside.
  • Mistake: Keeping results in one person's head or a screenshot. Why it is wrong: Decisions about scaling and releases get made on memory and the next test can't be compared. Instead: A short written summary with workload, knee, limiting resource and actions, stored with the test scripts.
  • Mistake: Using real customer data or hammering third-party production APIs. Why it is wrong: Privacy Act exposure and possible abuse of a partner's service. Instead: Synthetic data and stubs for third parties.

πŸ› Senior insight: trade-offs

A load test is only as good as its workload model, so I spend more time on realism than on scripting: production endpoint mix, data volume, cache behaviour and downstream latency. The deliverable isn't 'it passed' but a capacity statement: 'the knee is 1,500 requests/s on 4 instances, limited by Azure SQL CPU; we operate below 1,000'. That gives the business a number and the team a known next bottleneck. I keep a short threshold-based test in CI for regressions and run stress and soak tests on a schedule, because they take longer and need a stable environment.

Approach When it fits Cost When not to
k6 in CI Per-release regression gates Stable test environment Very large scale
Azure Load Testing (JMeter/Locust) Large scale from Azure regions, server metrics side by side Service cost, script format Quick local checks
NBomber .NET-only teams, complex C# scenarios Fewer integrations Teams already on k6
bombardier / wrk One-endpoint throughput check None Realistic mixed workloads

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions setting a p95 goal before testing Why: Checks they have the end-to-end measure-fix-verify method
    How to answer

    I treat performance as an experiment, not a hunch. First I agree a goal as a number: for example p95 under 200 ms at 300 requests a second. Then I measure a baseline with the same tools I'll use to verify: Application Insights for request and dependency timings, dotnet-counters for CPU, GC and ThreadPool, and a repeatable load test.

    Next I find the bottleneck: is time going to CPU, garbage collection, waiting on I/O (database, HTTP) or waiting on locks? Only then do I change one thing, re-run the same measurement and keep the change only if the numbers moved. I stop once the goal is met.

    The trade-off is time: measuring first feels slower, but guessing usually optimises code that wasn't the problem.

  2. When: Candidate says they profile the service while the load test runs Why: Checks they can read a CPU profile captured under load
    How to answer

    dotnet-trace with the default cpu-sampling profile uses EventPipe's sample profiler: roughly every millisecond it records each managed thread's call stack. Aggregated, those samples become a call tree or flame graph, where a frame's width is the share of samples it appears in.

    I read it top-down from my entry point to find the wide paths, then bottom-up by exclusive (self) time to find the methods that actually burn CPU.

    • Inclusive time: the method and everything it calls.
    • Exclusive time: just its own code.

    A wide frame is not always CPU work: EventPipe also samples threads that are waiting on a lock or I/O, and an awaiting async request holds no thread, so it doesn't appear at all. I cross-check with dotnet-counters and distributed traces. The trade-off: sampling is cheap enough for production but statistical, so short events can be missed; I capture under real load for 30–60 seconds and verify fixes with a second profile.

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

Load test finds the real limit is one Azure SQL query, not the API
Situation
A retail API on [App Service, 4 instances, Australia East] expected [3×] normal traffic for a seasonal campaign; forecast peak [900 requests/s]. The plan was to scale the app to 10 instances.
Signals
In a ramping-arrival-rate k6 test, p95 bent from [180 ms] to [2.4 s] at about [650 requests/s]; errors rose to [3%] (timeouts); app CPU only [45%]; k6 reported dropped iterations near the knee.
Investigation
Server-side metrics during the run: App Service CPU moderate, ThreadPool queue rising, Application Insights dependency latency for SQL climbing from [8 ms] to [900 ms]. Azure SQL showed [100%] DTU; Query Store's top query by duration was the product listing with a clustered index scan on [4 million] rows.
Resolution
Immediate: postponed the app scale-out (it wouldn't help). Fix: a covering non-clustered index for the listing query and a 60-second HybridCache entry for the first pages of each category. Re-test: knee moved to [1,500 requests/s], p95 at peak rate [190 ms].
Prevention
A 10-minute k6 test with thresholds on every release candidate; a monthly stress test documenting the knee and limiting resource; Query Store regression alerts.

How to tell it (STAR)

**S:** At [company] we had a campaign expected to bring about [3×] normal traffic, and the plan was to scale the API to 10 instances. **T:** I was asked to confirm we could handle [900 requests per second]. **A:** I built a k6 test with an open arrival-rate model, our real endpoint mix and production-sized synthetic data, and watched server metrics while ramping. p95 bent at [650 requests per second] while app CPU was only [45%]; the database was the limit, on one listing query. I added a covering index and a short cache and re-ran the test. **R:** The knee moved to [1,500 requests per second], we didn't need the extra instances, and the campaign peaked at [820 requests per second] with p95 at [210 ms].

↩ Usually asked after

More in Profiling

Last updated 23 Nov 2026.

🌐 Sangam's Webring

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