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

📚 Interview question

What is the difference between load, stress, soak and spike tests? What question does each one answer for a .NET API, which tools would you use (k6, Azure Load Testing, NBomber), and what would you look at in the results to decide whether the service is ready?

Load, stress, soak and spike tests as distinct test types: the question each answers, workload shapes, tool choice (k6, Azure Load Testing, NBomber and its licence), pass/fail criteria and what to read in the results for a .NET 10 API.

Mid-Level Theory Intermediate azure-load-testing k6 load-testing soak-testing stress-testing testing

🎯 Key points

  • Load test: expected peak traffic; does it meet the SLO (e.g. p95 < 300 ms, error rate < 0.1%)?
  • Stress test: ramp past peak until it breaks; where is the knee, does it shed load (429/503) and how fast does it recover once load drops?
  • Soak test: normal load for hours; finds memory leaks, connection pool exhaustion, log or disk growth
  • Spike test: sudden jump in traffic; tests autoscaling, cold starts and queueing
  • Pass/fail as thresholds on percentiles and error rate, not averages (one slow outlier skews an average, and averages hide the tail users feel)
  • Watch the server too: CPU, GC (dotnet-counters), ThreadPool queue length, SQL CPU and waits, dependency latency
  • k6 (open source), Azure Load Testing (managed; JMeter, and Locust since GA in March 2025; CI failure criteria), NBomber (C#, commercial licence for organisations)
  • Production-like environment and data volume; results from a smaller SKU or empty database don't transfer

⏱ 30-second answer

They are all performance tests with different workload shapes, each answering a different question. A load test runs expected peak traffic and asks "do we meet our SLO?", for example p95 under 300 ms and errors under 0.1%. A stress test ramps past peak until something breaks and asks "where is the limit, and do we degrade and recover gracefully?". A soak test holds normal load for hours to find leaks: memory, connections, handles, disk. A spike test jumps traffic suddenly to test autoscaling and cold starts. Tools: k6 or Azure Load Testing (JMeter or Locust scripts, managed, CI gates), or NBomber in C# (paid for organisational use). Read percentiles and error rates alongside server metrics. The trade-off: realistic tests need a production-like environment and data, which costs money.

🗣 Full answer (senior)

How I would answer this in an interview

"They're all performance tests; what changes is the shape of the traffic and the question. A load test runs the traffic we expect at peak, say 800 requests per second with a realistic mix of endpoints, and asks whether we meet the SLO: p95 under 300 ms, p99 under a second, errors under 0.1%. A stress test keeps ramping beyond that until something gives, and asks where the limit is, what breaks first and whether the service sheds load cleanly with 429s or 503s and recovers when traffic drops, rather than falling over. A soak test holds normal load for four to twelve hours. It finds the slow problems: memory that creeps up until the container is OOM-killed, a connection pool that leaks, a cache with no size limit. A spike test goes from 50 to 2,000 requests per second in seconds and checks autoscaling, cold starts and queues.

For tools, I'd normally write k6 scripts because they're easy to keep in the repo, and run them at scale through Azure Load Testing, which can also run JMeter or Locust scripts, fail a pipeline on thresholds and show server-side Azure Monitor metrics next to client results. NBomber is nice when a team wants scenarios in C#, but its licence requires a paid subscription for organisational use, so that's a conversation before adopting it.

The mistake I see is reading averages. An average of 120 ms can hide a p99 of 4 seconds. I look at percentiles over time, error rate, throughput, and on the server side CPU, GC pause time and ThreadPool queue length from dotnet-counters, plus SQL CPU and waits. A test only means something if the pass criteria were written down before it ran."


The four shapes

 load          stress          soak                 spike
 rps           rps             rps                  rps
  |  ____       |      /|       |  _______________   |    __
  | /    \      |    /  |       | /               \  |   |  |
  |/      \     |  /    |       |/                 \ |___|  |___
  +-------->    +-------->      +-------------------> +----------->
  30-60 min     until failure   4-12 hours            minutes
Type Question Typical failure it finds
Load Do we meet the SLO at expected peak? Slow queries, missing indexes, chatty calls
Stress Where is the limit, how do we fail and recover? ThreadPool starvation, pool exhaustion, cascading timeouts
Soak Is it stable over time? Memory leaks, unbounded caches, handle or disk growth
Spike Can we absorb a sudden jump? Slow autoscale, cold starts, queue backlogs

Tools

Tool Scripts in Strengths Watch out for
k6 (Grafana) JavaScript/TypeScript Open source, thresholds, easy in CI Single machine limits without a cloud runner
Azure Load Testing JMeter or Locust (GA since 2025) Managed scale, multi-region, Azure Monitor metrics side by side, CI fail criteria Pay per virtual user hour
NBomber C# Same language as the app Free only for personal use; organisations need a commercial licence
JMeter XML/GUI Mature, protocol-rich Heavy, awkward to review in PRs

What I read in the results

  • Client side: p50/p95/p99 latency over time, error rate by status code, achieved throughput vs target.
  • Server side: CPU, memory and GC (dotnet-counters monitor System.Runtime), ThreadPool queue length, Kestrel connection counts, HTTP client pool, SQL CPU, waits and Query Store top queries, Redis latency.
  • The knee: the throughput where latency starts rising steeply. That is your real capacity, not the point of total failure.

Production example

Before an end-of-financial-year peak, a stress test on a payments API showed p95 jumping from 180 ms to 6 s at 1,100 rps. dotnet-counters showed the ThreadPool queue climbing: a synchronous .Result call on an HTTP client. After fixing it, the knee moved to 2,400 rps, and a 6-hour soak test then found a 40 MB/hour leak from an unbounded MemoryCache, fixed with a SizeLimit before go-live.

🔍 What the interviewer is checking

Checks whether the candidate knows the distinct purposes of performance test types and can read results like an engineer, not a tool operator.

Green flags

  • Distinguishes load, stress, soak and spike by question and shape.
  • Talks in percentiles and pre-agreed thresholds.
  • Correlates client results with server metrics (GC, ThreadPool, SQL).
  • Mentions open vs closed models or coordinated omission.
  • Knows tool licensing trade-offs.

Red flags

  • Uses averages.
  • Tests against an empty database or tiny environment and trusts the numbers.
  • Can't say what "passing" means.

📚 Learn in depth

1. Open vs closed workload models

  • Closed model: a fixed number of virtual users, each waiting for a response before sending the next request. When the server slows down, the request rate drops, which hides the problem.
  • Open model: requests arrive at a fixed rate regardless of response time, like real internet traffic. k6's constant-arrival-rate and ramping-arrival-rate executors do this.

Use open models for public APIs. Closed models understate latency under overload; this is related to coordinated omission, where the load generator stops sending while waiting, so the slowest periods are under-sampled.

2. Little's Law

 concurrency = throughput x latency
 800 rps x 0.25 s = 200 requests in flight

If latency doubles at the same throughput, in-flight requests double, which is what exhausts connection pools and ThreadPool threads during a stress test.

3. What breaks first in a .NET API

 traffic rises
   -> SQL CPU or locking saturates -> queries queue
   -> DbContext connections held longer -> pool (default max 100) exhausted
   -> requests wait for connections -> latency climbs
   -> sync-over-async code blocks ThreadPool threads -> starvation
   -> timeouts and retries add more load -> cascading failure

A good stress test shows which link fails first, so you know what to fix or protect with rate limiting and timeouts.

4. Soak tests and slow failures

Soak tests find problems with a rate, not a threshold: memory growing 30 MB/hour, a socket leak from creating HttpClient per request, log files filling a disk, Gen 2 heap growth from an event handler never unsubscribed. Plot memory and handle counts over the whole run; a sawtooth is healthy, a ramp is a leak.

5. Test environment and data

  • Same SKU and instance count as production (or scale results carefully).
  • Production-like data volume, synthetic not copied (Privacy Act 1988: don't move real personal information into test environments).
  • Warm-up period excluded from results (JIT, tiered compilation, caches).
  • Run from the same region as real users, for Australian traffic Australia East.

Try it yourself

  1. Write a k6 script with a ramping-arrival-rate executor and thresholds on http_req_duration p95 and http_req_failed.
  2. Run it against a local API while watching dotnet-counters monitor -n MyApi System.Runtime.
  3. Add Thread.Sleep(50) to an endpoint and watch ThreadPool queue length during a stress ramp.
  4. Run the same script in Azure Load Testing and compare client and server metrics side by side.
  5. Run a 2-hour soak and plot working set; look for a ramp.

💻 Code

A k6 script with load and stress stages and pass/fail thresholds, plus an Azure Load Testing config that fails the pipeline:

// load-test.js
import http from 'k6/http';
import { check } from 'k6';

export const options = {
  scenarios: {
    orders: {
      executor: 'ramping-arrival-rate', // open model: fixed arrival rate
      startRate: 50,
      timeUnit: '1s',
      preAllocatedVUs: 200,
      maxVUs: 2000,
      stages: [
        { target: 800, duration: '5m' },   // ramp to expected peak (load)
        { target: 800, duration: '20m' },  // hold peak
        { target: 2400, duration: '10m' }, // keep going (stress)
        { target: 0, duration: '5m' },     // recovery
      ],
    },
  },
  thresholds: {
    http_req_duration: ['p(95)<300', 'p(99)<1000'],
    http_req_failed: ['rate<0.001'],
  },
};

export default function () {
  const res = http.get(`${__ENV.BASE_URL}/orders?page=1`);
  check(res, { 'status 200': (r) => r.status === 200 });
}
# Azure Load Testing test config (load-test.yaml)
version: v0.1
testId: orders-peak
testType: Locust   # or JMX for JMeter
testPlan: locustfile.py
engineInstances: 4
failureCriteria:
  - p95(response_time_ms) > 300
  - percentage(error) > 0.1

A small C# endpoint guard that makes stress tests fail gracefully instead of collapsing:

namespace Orders.Api;

using System.Threading.RateLimiting;

public static class LoadSheddingSetup
{
    public static IServiceCollection AddLoadShedding(this IServiceCollection services) =>
        services.AddRateLimiter(o =>
        {
            o.RejectionStatusCode = StatusCodes.Status503ServiceUnavailable;
            // Cap concurrent work so overload returns fast 503s, not 30 s timeouts.
            o.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(_ =>
                RateLimitPartition.GetConcurrencyLimiter("global", _ => new ConcurrencyLimiterOptions
                {
                    PermitLimit = 400,
                    QueueLimit = 200,
                    QueueProcessingOrder = QueueProcessingOrder.OldestFirst
                }));
        });
}

⚠ Common mistakes

  • Mistake: Reporting average latency. Why it is wrong: averages hide the slow tail that users feel. Instead: report p95 and p99 over time, plus error rate.
  • Mistake: Using a closed workload model for a public API. Why it is wrong: the generator slows down when the server does, hiding overload (coordinated omission). Instead: use an arrival-rate (open) executor.
  • Mistake: Load testing a tiny test environment with an empty database. Why it is wrong: query plans, cache hit rates and capacity are completely different. Instead: production-sized SKU and synthetic data at production volume.
  • Mistake: Running without pass criteria. Why it is wrong: any result can be argued as "fine". Instead: agree SLO thresholds first and encode them in the script or failure criteria.
  • Mistake: Only watching client-side numbers. Why it is wrong: you see that it's slow, not why. Instead: collect dotnet-counters, Application Insights and SQL metrics during the run.
  • Mistake: Skipping soak tests. Why it is wrong: leaks only show after hours, usually in production at 3 a.m. Instead: run a multi-hour soak before major releases.
  • Mistake: Adopting NBomber across a company without checking the licence. Why it is wrong: organisational use needs a commercial subscription. Instead: budget for it or use k6 or Azure Load Testing.
  • Mistake: Including warm-up in results. Why it is wrong: JIT and cold caches inflate the first minutes. Instead: exclude a warm-up stage.

🏛 Senior insight: trade-offs

The four test types answer four different questions, and picking the wrong one wastes the run. Before a seasonal peak I'd do a load test to confirm SLOs, a stress test to find the knee and confirm we shed load cleanly and recover (time from load dropping to p95 back under SLO is a metric in its own right), and a soak test before any release that touched caching, connections or background work. Spike tests matter most when autoscaling or serverless is involved, because scale-out takes minutes while spikes take seconds.

What makes it senior is the loop and the baseline. Keep a recorded baseline per release (throughput at the knee, p95 at peak, memory per replica) so a regression shows up as a diff, not a feeling, and run a reduced load test nightly against the same baseline. After go-live, the same SLO thresholds become Application Insights and Azure Monitor alerts, so production keeps testing the assumptions the load test made. And protect the service from the stress case in production with rate limiting, timeouts and bulkheads, so the stress test result is "returns 503s quickly and recovers in a minute" rather than "falls over".

Approach When it fits Cost When not to
k6 locally or in CI Fast feedback, small scale Free Need thousands of rps from many regions
Azure Load Testing Scale, Azure metrics, CI gates Per virtual-user hour Very small services where k6 on one agent is enough
NBomber Team wants C# scenarios Commercial licence for organisations Budget or licence approval is a blocker
Nightly reduced load test vs baseline Catching gradual performance regressions CI minutes plus an environment Services with no latency SLO

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions designing a realistic load test or reading percentiles. Why: Checks workload design, coordinated omission and percentile reading in more depth.
    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 watching server metrics during a test. Why: Checks the candidate can use .NET diagnostics tools to explain what a load test found.
    How to answer

    The .NET diagnostics tools all talk to the runtime over its diagnostics IPC channel, so they work on Windows, Linux and in containers without a debugger.

    • dotnet-counters shows live metrics (CPU, GC heap size, allocation rate, ThreadPool queue length, exceptions) with almost no overhead. It tells you what kind of problem you have.
    • dotnet-trace records an EventPipe trace with CPU samples and runtime events; it tells you where time goes.
    • dotnet-gcdump captures the managed heap graph (types, sizes and references). Comparing snapshots shows what is growing; the reference paths show what keeps it alive. dotnet-dump captures the whole process for SOS analysis of hangs and native memory.
    • dotnet-monitor wraps all of this as an HTTP API or sidecar with triggers, which is how you use them in Kubernetes or Container Apps.

    I start with counters because they are cheap, then pick the heavier tool the symptom points to. The trade-off is overhead and data sensitivity: a full dump contains every secret in memory.

  3. When: Candidate mentions soak tests finding memory leaks. Why: Checks how the candidate would chase a leak found by a soak test.
    How to answer

    First I confirm it is managed memory: in dotnet-counters, if gc-heap-size grows with the working set and survives Gen 2 collections, it's a managed leak; if the working set grows but the heap doesn't, it's native, and I switch to dotnet-dump (eeheap, maddress) and native tools.

    For managed growth I take two or three dotnet-gcdump snapshots under the same load, minutes apart, and compare them in Visual Studio or PerfView. The type whose count and size keep rising is the suspect, and its paths to root show what holds it: usually a static cache, an event subscription, a timer, or services resolved from the root DI scope. If the heap grows but object counts don't, I check LOH fragmentation from long-lived large buffers.

    I fix the root, not the symptom, and verify with a soak test that the heap flattens. The trade-off: each gcdump forces a full blocking GC, so I take few snapshots and avoid peak traffic when I can.

🛠 Real-world problems: how you handle them

Soak test finds a memory leak a week before go-live
Situation
A [ticketing] API on Azure Container Apps in Australia East was going live before a [major event on-sale]. Load and stress tests had passed, with p95 at 140 ms at the expected [1,500] rps. The team planned to skip a soak test to save time.
Signals
A 6-hour soak at 60% of peak showed working set rising steadily from 380 MB to 1.4 GB, then the replica was OOM-killed and restarted at hour 5. Latency spiked to 8 s during each restart. Gen 2 heap size in dotnet-counters climbed and never dropped after full GCs.
Investigation
Ran `dotnet-counters monitor System.Runtime` during the soak to confirm Gen 2 growth, then took two `dotnet-gcdump` snapshots an hour apart and compared them in Visual Studio. The growing type was cache entries in a `MemoryCache` keyed by event ID and seat section, created with no `SizeLimit` and only sliding expiration that kept being refreshed. Azure Load Testing server-side metrics confirmed memory per replica, not total load, was the trigger.
Resolution
Immediate: set `SizeLimit` on the cache and a `Size` on each entry, plus an absolute expiration of 5 minutes. Rerun the 6-hour soak: memory stabilised at 520 MB with a normal sawtooth. Longer term: moved shared seat-availability data to Azure Managed Redis via `HybridCache` with explicit limits.
Prevention
Added a 4-hour soak test to the pre-release checklist for anything touching caching, connections or background services. Added an Azure Monitor alert on working set growth per hour, and an analyser rule flagging `MemoryCache` created without `SizeLimit`.

How to tell it (STAR)

**S:** We were [a week] from go-live for a [ticketing] API and our load and stress tests had passed comfortably. **T:** I argued we still needed a soak test, because nothing we'd run lasted more than 40 minutes. **A:** I ran a 6-hour soak at 60% of peak in Azure Load Testing while watching dotnet-counters. Memory climbed steadily until the container was OOM-killed at hour five. Two gcdump snapshots showed an unbounded MemoryCache. I added a size limit and absolute expiry and reran the soak. **R:** Memory flattened at about 520 MB instead of hitting 1.4 GB, the on-sale ran at [peak rps] with no restarts, and soak tests became a standard pre-release step.

More in Test Types

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me