Skip to content
Tech Intuition
Tech Intuition

Appearance

Theme

Signal · Dark with amber

Background

Slow stars and the odd comet

Connect

Performance engineering · Lesson 15 of 44

Load testing and benchmarking

How to build a load test or benchmark that survives scrutiny: the question first, open versus closed workloads, coordinated omission, realistic data, warm-up, noise, and the statistics to compare two builds, with tested C#.

GuideApplied24 min readUpdated

  • 1 sequence flow
  • 6 code samples
  • 6 interviewer follow-ups
  • 3 self-checks

Read first: Latency, throughput and queues

By the end you will be able to
  • Choose the test type that answers your question (smoke, load, capacity, stress, spike, soak) and write the pass condition first.
  • Decide whether the workload is open or closed, and explain how that choice changes the result.
  • Recognize coordinated omission, avoid it, and cross-check a generator's numbers with Little's Law.
  • Build realistic data, key popularity and connection behavior, and keep the load generator from becoming the bottleneck.
  • Compare two builds with repeated, interleaved runs and a confidence interval, and estimate how many runs you need.

5 code samples (173 lines), collapsed so the explanation stays in focus.

A load test is an experiment on a system you cannot fully see, run with a tool that has its own limits. Most tests that mislead did so before the first request was sent: the question was vague, the load did not look like real load, the generator was the bottleneck, or the clock started in the wrong place. This lesson is about designing the experiment, so that the number you report survives a skeptical senior engineer asking "how do you know?"

HLD

Start with the question, not the tool

"Run a load test" is not a task. "Will checkout hold a p99 under 300 ms at 3,000 requests per second, the peak we expect on the sale day, with one zone down?" is. The question decides the shape of the load, the duration and what you measure.

TestQuestion it answersLoad shapeWatch
SmokeDoes the test itself work, and does the system serve minimal load?A handful of requestsErrors, test setup
LoadDoes it meet its SLO at the expected peak?Steady at the expected peakPercentiles, errors, resource use
CapacityWhere is the knee, and what is the limit per unit of hardware?A stepped ramp until the SLO breaksLatency against load, the first saturated resource
StressHow does it fail beyond capacity, and does it recover?Above capacity, then back downError behavior, queue growth, recovery time
SpikeCan it absorb a sudden jump?An instant step of 2× to 10×Latency during the step, autoscaler lag
SoakDoes it degrade over hours: leaks, fragmentation, growing logs?Steady and longMemory, handles, disk, the trend in the tail
Failover under loadDoes the SLO hold while a node or zone dies?Steady, with a fault injectedErrors and latency around the event

Write the pass condition as an SLO (the SLO lesson shows how targets and error budgets are chosen) before you see a result: a percentile, a threshold, a load, an error budget and a duration. "Pass if p99 is at most 300 ms and errors stay under 0.1% for 30 minutes at 3,000 requests per second." A threshold chosen after the fact is a story, not a test.

HLD

Open and closed workloads

The most consequential decision in a generator is what triggers the next request.

ClosedOpen
What sends the next requestThe previous response, plus think timeThe clock or an arrival process, whatever the responses do
Load when the system slowsFalls: virtual users waitUnchanged: real users keep arriving
Requests in the systemAt most the number of users, NUnbounded: a queue can grow
ModelsA fixed worker pool, a batch job, a bounded set of clientsThe public internet, mobile apps, upstream services that do not wait for you
RiskHides overload and under-reports latencyNeeds generator capacity, and can bury the system in a queue

A closed system obeys the interactive response time law, N = X × (R + Z): users equal throughput times the sum of response time and think time. Past saturation the throughput stays flat and the users simply wait longer, so latency can only grow as fast as N allows. An open system has no such cap.

Schroeder, Wierman and Harchol-Balter showed in 2006 that the choice between the two models can change measured response times, and the apparent benefit of a design change, by a large factor, and that tool users rarely notice which model their tool implements. For a service that people or other services call independently, test open. Use a closed loop where the real clients are closed: a pool of 50 workers is a closed system with N = 50.

HLD

Coordinated omission

A closed-loop generator has a quiet flaw. When the system stalls, the generator stalls with it, because it is waiting for the answer. The requests that should have been sent during the stall are never sent, and so never measured. The worst moments of the run are exactly the ones that go unrecorded. Gil Tene named this coordinated omission: the generator and the system under test coordinate, and the generator omits the data that would embarrass the system.

Fig. Why a closed loop under-reports a stall
Fig. Why a closed loop under-reports a stall

Here is the experiment, in virtual time so it runs instantly. The server answers each request in 1 ms, except that it freezes for 10 seconds, 40 seconds into a 100-second test. It stands in for a stop-the-world pause, a failover or a saturated disk. The generator intends to send a request every 2 ms.

C# · LatencyRecorder, StallingServer51 lines
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

public sealed class LatencyRecorder
{
    private readonly List<double> _ms = new List<double>();

    public int Count => _ms.Count;

    public void Record(double ms) => _ms.Add(ms);

    /// <summary>Record a latency, and also the requests that should have been sent while this one was stuck.
    /// Each of them would have waited a little less than the one before (the HdrHistogram correction).</summary>
    public void RecordCorrected(double ms, double expectedIntervalMs)
    {
        _ms.Add(ms);
        for (double missed = ms - expectedIntervalMs; missed >= expectedIntervalMs; missed -= expectedIntervalMs) _ms.Add(missed);
    }

    public double Percentile(double p)
    {
        var sorted = _ms.OrderBy(x => x).ToList();
        int rank = (int)Math.Ceiling(p * sorted.Count);
        return sorted[Math.Clamp(rank, 1, sorted.Count) - 1];
    }
}

/// <summary>A one-request-at-a-time server that answers in `serviceMs`, in order, and starts nothing during its freeze.</summary>
public sealed class StallingServer
{
    private readonly double _serviceMs, _freezeStartMs, _freezeEndMs;
    private double _freeAt;

    public StallingServer(double serviceMs, double freezeStartMs, double freezeEndMs)
    {
        _serviceMs = serviceMs;
        _freezeStartMs = freezeStartMs;
        _freezeEndMs = freezeEndMs;
    }

    /// <summary>The time at which a request that arrives at `arrivalMs` is answered.</summary>
    public double Respond(double arrivalMs)
    {
        double start = Math.Max(arrivalMs, _freeAt);
        if (start >= _freezeStartMs && start < _freezeEndMs) start = _freezeEndMs;
        _freeAt = start + _serviceMs;
        return _freeAt;
    }
}

Three ways to measure the same server:

C# · 1. A closed loop: send, wait for the answer, think for 1 ms, repeat. Latency is measured…28 lines
// 1. A closed loop: send, wait for the answer, think for 1 ms, repeat. Latency is measured from the actual send time.
var closedRaw = new LatencyRecorder();
var closedCorrected = new LatencyRecorder();
{
    var server = new StallingServer(serviceMs: 1, freezeStartMs: 40_000, freezeEndMs: 50_000);
    double now = 0;
    while (now < 100_000)
    {
        double answeredAt = server.Respond(now);
        closedRaw.Record(answeredAt - now);
        closedCorrected.RecordCorrected(answeredAt - now, expectedIntervalMs: 2);   // it meant to send every 2 ms
        now = answeredAt + 1;
    }
}

// 2. An open loop: send every 2 ms whatever happens, and measure from the time each request was due.
var openLoop = new LatencyRecorder();
{
    var server = new StallingServer(1, 40_000, 50_000);
    for (double due = 0; due < 100_000; due += 2) openLoop.Record(server.Respond(due) - due);
}

Debug.Assert(closedRaw.Percentile(0.999) <= 1.5);                       // the closed loop reports 1 ms even at p99.9
Debug.Assert(closedRaw.Percentile(1.0) > 10_000);                       // and keeps the freeze as one lonely maximum
Debug.Assert(openLoop.Percentile(0.90) > 5_000);                        // the truth: a tenth of all requests waited over 5 s
Debug.Assert(openLoop.Percentile(0.99) > 9_000);
double recovered = closedCorrected.Percentile(0.99);
Debug.Assert(Math.Abs(recovered - openLoop.Percentile(0.99)) / openLoop.Percentile(0.99) < 0.10);   // the correction recovers the tail
Measurementp50p90p99p99.9max
Closed loop, as measured (45,000 samples)1 ms1 ms1 ms1 ms10.0 s
Closed loop, with the correction1 ms3 ms9.0 s9.9 s10.0 s
Open loop, the truth (50,000 samples)1 ms5.0 s9.5 s9.95 s10.0 s

The raw closed loop says the service is excellent at p99.9. The open loop says that a fifth of the requests in the test were delayed by a freeze, a tenth of them for more than five seconds. The only trace of it in the first row is the maximum, which most dashboards do not show.

Avoiding it. Schedule requests by the clock, not by completions, and measure each latency from the time the request was due. If the generator falls behind, the lateness counts as latency. Tools built around this include wrk2, the arrival-rate executors in k6, the open injection profiles in Gatling and Vegeta. Many tools default to closed loops (JMeter thread groups, Locust users) unless you add a throughput timer or a constant-rate mode, so check which one you are running.

Repairing a closed-loop result is possible but imperfect. The correction above recovers the extreme tail (9.0 s against the true 9.5 s) but misses the backlog that builds behind the freeze and drains afterward, so its p90 is still wrong. It is a patch, not a substitute for an open loop.

Detecting it in results you did not produce:

  • Apply Little's Law (see latency, throughput and queues). A generator with 50 connections and no think time should show throughput near 50 ÷ mean latency. If the reported throughput is far lower, the generator spent time somewhere it did not measure.
  • Compare planned and achieved request counts. A 100-second test at 500 requests/s that sent 45,000 requests lost 5,000 of them.
  • Look at the maximum. A max that is thousands of times the p99.9 is a stall that the percentiles failed to see.

HLD

Make the workload real

A test that answers a question about production must look like production in the ways that matter.

  • Request mix and payload sizes. Read-heavy or write-heavy, small or large bodies, the proportion of expensive endpoints. A mix of 95% cheap requests hides the 5% that dominate CPU.
  • Connection behavior. New connections cost a TCP and TLS handshake; reused ones do not. Test the real ratio, because handshake rate is a different bottleneck from request rate, and a load balancer or firewall may limit connections per second long before it limits throughput.
  • Key popularity. Real keys are skewed: a few are hot. Uniform random keys overstate cache misses and understate hot-key contention. The sample below shows how different the two are.
  • Data volume. A test database that fits in memory measures RAM, not the database. Use a data set whose ratio to memory matches production, and consider the cache state: cold, warm, or both as separate scenarios.
  • Dependencies. Replace third parties with stubs that return after a realistic delay drawn from a production latency histogram. A stub that answers in 0 ms hides pool exhaustion and queueing, which are exactly what a slow dependency causes.
  • Side effects. Use test tenants and sinks for emails, payments and writes. Replaying real traffic is realistic but has to be filtered for privacy and for non-idempotent calls.
  • Time. Real traffic has bursts, daily cycles and retries. A perfectly smooth arrival rate is a gentler test than the one production gives you (recall the variability term in Kingman's formula).

Popularity is often modeled as a Zipf distribution, where the key of rank k receives traffic proportional to 1 ÷ k^s. With s = 1 and 10,000 keys, the hottest 1% of keys receive 53% of requests. A cache that holds that hottest 1% answers about half of Zipf traffic, and 1% of uniform traffic.

C# · Zipf29 lines
public sealed class Zipf
{
    private readonly double[] _cumulative;
    private readonly Random _random;

    public Zipf(int keys, double s, int seed)
    {
        _cumulative = new double[keys];
        double sum = 0;
        for (int rank = 1; rank <= keys; rank++)
        {
            sum += 1.0 / Math.Pow(rank, s);
            _cumulative[rank - 1] = sum;
        }
        for (int i = 0; i < keys; i++) _cumulative[i] /= sum;      // turn the running total into a probability
        _random = new Random(seed);
    }

    /// <summary>The next key's rank: 1 is the hottest key.</summary>
    public int Next()
    {
        int at = Array.BinarySearch(_cumulative, _random.NextDouble());
        if (at < 0) at = ~at;
        return at + 1;
    }

    /// <summary>The share of all requests that go to the `count` hottest keys.</summary>
    public double ShareOfTop(int count) => _cumulative[count - 1];
}
C#
var popularity = new Zipf(keys: 10_000, s: 1.0, seed: 5);
Debug.Assert(Math.Abs(popularity.ShareOfTop(100) - 0.53) < 0.001);      // 1% of the keys take 53% of the requests

int toHottest = 0;
for (int draw = 0; draw < 200_000; draw++) if (popularity.Next() <= 100) toHottest++;
Debug.Assert(Math.Abs(toHottest / 200_000.0 - 0.53) < 0.01);           // and the generator really does draw them that way

HLD

Keep the load generator honest

The generator is a system under load too, and when it saturates it produces a convincing flat line. Treat it as a suspect.

  • Measure the generator first. Point it at a trivial server that answers immediately. That gives its own latency floor and its maximum rate. Test the real target at no more than about half of that.
  • Watch its resources during the run: CPU per core, garbage collection or runtime pauses, memory, network interface limits.
  • Know the connection limits. On Linux the default ephemeral port range is about 28,000 ports, and a connection closed by the client lingers in TIME_WAIT for 60 seconds, so one source address can open only a few hundred new connections per second to a single destination before it runs out (unless tuned). The default soft limit on open file descriptors is often 1,024. A test that opens a connection per request often measures these limits.
  • Keep the hot path small. Pre-build payloads, use asynchronous I/O, and never log per request. Record raw timestamps and compute statistics afterward.
  • Synchronize clocks if several machines generate load, and merge their results as histograms. To go beyond one machine's capacity, spread generators across hosts and networks so no shared link or load balancer becomes the thing you measure.
  • Use Little's Law on the output, as above.

HLD

Environment, warm-up and noise

  • Be explicit about what differs from production (instance size, replica count, data size, network path) and what each difference can and cannot tell you. A scaled-down environment can show a scalability curve and the cost per request. It cannot give an absolute capacity number.
  • Control what you can. Same OS, kernel and runtime versions. A fixed CPU frequency governor, or at least a record of it. Dedicated hosts or pinned cores if you can get them. In the cloud, watch for steal time and run the baseline and the candidate on the same machines.
  • Warm up. Caches fill, pools open, and managed runtimes compile hot code in the background after starting it unoptimized, so the first seconds are slower and different. Discard that period, and decide when steady state starts by checking that the trend has flattened rather than waiting a fixed time. Cold start deserves its own scenario if it matters.
  • Run long enough to contain the periodic events: garbage collections, compactions, log rotation, cache expiry, autoscaler cycles. A five-minute test of something that stalls every ten minutes will not see the stall.
  • Beware of invisible bias. Mytkowicz and co-authors showed that changes which should not matter, such as the size of the environment or the order in which code is linked, shifted measured performance by amounts comparable to the effects people report. Randomizing and repeating are the defenses.

HLD

Reading the results

Report a capacity at an SLO, not a maximum. "The service handled 5,200 requests per second" is meaningless if the p99 was three seconds. A capacity test ramps in steps long enough to stabilize (two to five minutes each), and the answer is the last step that still met the objective.

StepOffered load (req/s)Achieved (req/s)p99 (ms)Errors
11,0001,000380%
22,0002,000410%
33,0003,000470%
44,0003,990850.01%
54,5004,3103100.4%
65,0004,1502,9006%

These numbers are illustrative. Against an objective of p99 ≤ 100 ms and errors ≤ 0.1%, the sustainable load is 4,000 requests per second, the knee sits between 4,000 and 4,500, and step 6 shows what overload looks like: achieved throughput falls (4,310 to 4,150) as retries and timeouts burn capacity. That is goodput collapsing under overload, and it is why a design must shed load before this point.

Three habits make results believable:

  • Show time series, not just a final number: p99 per ten-second window, next to CPU, queue depth and garbage collection. A single aggregate averages over the event you came to find.
  • Store histograms, not summaries, so results from different generators and runs can be merged and compared later.
  • Benchmark actively. While the test runs, observe the system with other tools, as Brendan Gregg advises (the next lesson, on profiling and finding the bottleneck, is that toolbox). If you cannot explain why the limit is where it is (which resource is full), you have not finished; you have produced a number.

LLD

Comparing two builds

"Build B is 3% faster" is a statistical claim, and it needs a procedure.

  • The unit of replication is the run. Samples inside one run are correlated: a slow period affects thousands of requests together. Compute the statistic you care about (median, p99) per run, then compare the sets of per-run values. Pooling every request from every run makes the interval absurdly narrow.
  • Interleave. Run A, B, A, B on the same hosts instead of all of A then all of B, so drift (a warming machine, a neighbor, a busy hour) hits both equally. Randomize the order.
  • Report the change with an interval, not a p-value alone. A bootstrap resamples the runs with replacement thousands of times and reads the interval from the spread of the results. It needs no assumption that latency is normally distributed, which it is not.
  • Decide the smallest change that matters (say 3%) beforehand. Flag only when the interval excludes zero and the effect is larger than that.
  • Budget the runs. To detect a shift δ when run-to-run noise has standard deviation σ, you need about n = 16 × (σ ÷ δ)² runs per build (two-sided 5% significance, 80% power, normal approximation). With 1% noise and a 2% target, 4 runs are enough; with 3% noise, 36; with 4% noise, 64. When the number is absurd, reduce the noise first: fewer moving parts, dedicated hosts, longer runs, or a deterministic metric such as instructions retired.
  • Mind multiple comparisons. Test 100 benchmarks at a 5% false-alarm rate and you expect five alarms per change even when nothing changed. Gates that run many benchmarks need a higher bar, or alerts on sustained shifts instead of single points.
C# · Compare, Synthetic51 lines
public static class Compare
{
    /// <summary>Relative change of the median from baseline to candidate, with a bootstrap confidence interval.
    /// Each value is one run's result (a per-run median or p99), not an individual request.</summary>
    public static (double Change, double Low, double High) MedianChange(
        double[] baseline, double[] candidate, int resamples, int seed, double confidence = 0.95)
    {
        var g = new Random(seed);
        var changes = new double[resamples];
        for (int i = 0; i < resamples; i++)
        {
            double a = Median(Resample(baseline, g)), b = Median(Resample(candidate, g));
            changes[i] = (b - a) / a;
        }
        Array.Sort(changes);
        int low = (int)Math.Floor((1 - confidence) / 2 * resamples);
        int high = (int)Math.Ceiling((1 + confidence) / 2 * resamples) - 1;
        double a0 = Median(baseline), b0 = Median(candidate);
        return ((b0 - a0) / a0, changes[low], changes[high]);
    }

    /// <summary>Runs per build to detect a shift of `delta` when runs vary by `sigma` (same units; 5% significance, 80% power).</summary>
    public static int RunsNeeded(double sigma, double delta) => (int)Math.Ceiling(16 * (sigma / delta) * (sigma / delta));

    private static double[] Resample(double[] xs, Random g)
    {
        var picked = new double[xs.Length];
        for (int i = 0; i < picked.Length; i++) picked[i] = xs[g.Next(xs.Length)];
        return picked;
    }

    private static double Median(double[] xs)
    {
        var sorted = (double[])xs.Clone();
        Array.Sort(sorted);
        int n = sorted.Length;
        return n % 2 == 1 ? sorted[n / 2] : (sorted[n / 2 - 1] + sorted[n / 2]) / 2;
    }
}

public static class Synthetic
{
    /// <summary>`n` run results around `mean` with run-to-run noise `sd` (a bell curve, via Box-Muller).</summary>
    public static double[] Runs(Random g, int n, double mean, double sd)
    {
        var runs = new double[n];
        for (int i = 0; i < n; i++)
            runs[i] = mean + sd * Math.Sqrt(-2 * Math.Log(1 - g.NextDouble())) * Math.Cos(2 * Math.PI * g.NextDouble());
        return runs;
    }
}

The check: 30 runs of a baseline at 100 ms with 3 ms of noise, then a build with no change and a build that is 5% slower.

C#14 lines
var noise = new Random(3);
double[] baseline = Synthetic.Runs(noise, 30, mean: 100, sd: 3);
double[] sameBuild = Synthetic.Runs(noise, 30, mean: 100, sd: 3);
double[] slowerBuild = Synthetic.Runs(noise, 30, mean: 105, sd: 3);

var unchanged = Compare.MedianChange(baseline, sameBuild, resamples: 2000, seed: 9);
Debug.Assert(unchanged.Low < 0 && unchanged.High > 0);                   // the interval contains zero: no evidence of a change

var regression = Compare.MedianChange(baseline, slowerBuild, resamples: 2000, seed: 9);
Debug.Assert(regression.Low > 0.02 && regression.High < 0.10);           // about 5% slower, and zero is outside the interval

Debug.Assert(Compare.RunsNeeded(sigma: 1, delta: 2) == 4);
Debug.Assert(Compare.RunsNeeded(sigma: 3, delta: 2) == 36);
Debug.Assert(Compare.RunsNeeded(sigma: 4, delta: 2) == 64);

HLD

Microbenchmarks

A microbenchmark times one small piece of code in isolation. It is the right tool to choose between two implementations of a hot function, and the wrong one to predict how a service will behave. Use a harness that handles the hard parts (BenchmarkDotNet for .NET, JMH for Java, Google Benchmark for C++), and know what it protects you from:

  • Dead-code elimination and constant folding. If the result is unused or the inputs are constants, the compiler may delete the work. Return or consume the result.
  • Warm-up and tiered compilation. The first iterations run unoptimized code. Let the harness warm up and report steady state.
  • Setup inside the timed region, and data that is too regular: sorted input makes branch prediction look better than real data would.
  • Cache effects. A tiny working set stays in the CPU cache and hides memory cost.
  • Allocation. Time alone misses the garbage a method creates, which another thread pays for later. Record allocations too.
Example · BenchmarkDotNet example (not run by the site's tests)
// Each method returns a value, so the work cannot be optimized away.
[MemoryDiagnoser]
public class RequestLineBenchmarks
{
    private readonly string _line = "GET /v1/items/42 HTTP/1.1";

    [Benchmark(Baseline = true)]
    public int Split() => _line.Split(' ').Length;

    [Benchmark]
    public int Span() => _line.AsSpan().Count(' ') + 1;
}

Then confirm that a win in the microbenchmark shows up in the system-level test. Many do not, because the function was never on the critical path.

Senior depth

What senior interviews ask about load testing

Interviewer follow-upL5What is the difference between a load test and a stress test?How to answer

A load test checks that the system meets its objectives at the expected peak, and passes or fails against an SLO. A stress test pushes beyond capacity to learn how the system fails and whether it recovers: does it shed load cleanly, do queues drain, does goodput collapse. Both are needed. Capacity tests (stepped ramps) sit between them and find the knee.

Interviewer follow-upL6Your load test says p99 is 12 ms, and production says 400 ms. What are the suspects?How to answer

Check the workload first: uniform keys against a skewed real distribution (hot keys, contention), a data set that fits in memory, smaller payloads, a warm cache, reused connections instead of the real TLS handshake rate, and stubs with zero latency. Then the measurement: coordinated omission, a generator that is itself the bottleneck, and percentiles taken from too little data. Then the environment: noisy neighbors, different instance types, cross-zone hops, a different network path, CPU throttling in containers, background jobs. Finally, the system: autoscaling, garbage collection under real heap sizes, and dependencies that behave differently under real load. Compare the two with the same dashboards to see which resource differs.

Interviewer follow-upL6What is coordinated omission, and how would you tell that a tool suffers from it?How to answer

A closed-loop generator waits for each response before it sends the next request, so when the system stalls it stops sending, and the requests that would have been delayed are never measured. Percentiles come out far too good. Tell by checking whether the tool sends on a fixed schedule and measures from the intended send time; by comparing planned and achieved request counts; by applying Little's Law to connections, throughput and latency; and by running a test in which you deliberately freeze the server for ten seconds and seeing whether the report shows it.

Interviewer follow-upL6How do you load test a service that calls a payment provider you cannot hammer?How to answer

Replace the provider with a stub whose latency and error rates come from production histograms, not a stub that answers instantly. Run it in the real call path so pools, timeouts and retries behave. Test failure modes on purpose: slow responses, errors and timeouts, since those are where capacity is lost. Validate against the real provider only at a low rate, in its sandbox, to check the contract.

Interviewer follow-upL7Design the acceptance rule for a performance gate that must be quiet on noise but catch a 3% regression.How to answer

Measure the noise first: run the benchmark many times on the same build to get σ per run. Compute the runs needed (about 16 × (σ ÷ δ)² per side), and if that is too many, reduce noise before adding runs. Interleave baseline and candidate on the same hosts. Compare per-run statistics with a bootstrap interval. Alert only if the interval excludes zero and the effect exceeds the minimum that matters, and decide the re-run policy in advance (one fixed-size confirmation batch, never "run until green"). Across many benchmarks, raise the bar or alert on sustained changes. Auto-bisect to the offending commit.

Interviewer follow-upL7One load generator machine tops out at 30,000 requests/s and you must test at 200,000. What changes?How to answer

Distribute generation across machines and networks, sized so each runs at half its measured maximum; synchronize their clocks and start times; and merge their histograms instead of averaging summaries. Watch for shared limits that become the thing you measure: a load balancer's connection or bandwidth limits, source-port exhaustion (use more source addresses), NIC and switch capacity. Keep per-generator CPU headroom, and confirm the aggregate with Little's Law.

HLD

How to answer a load-testing question in an interview

  1. State the question and the pass condition: the SLO, the load, the duration.
  2. Choose the test type and the load shape (steady, stepped ramp, spike, soak).
  3. Model the workload: open or closed, request mix, key skew, connection behavior, data size.
  4. Name the measurement traps: coordinated omission, generator capacity, warm-up, noise.
  5. Say what you will watch besides latency: utilization and saturation of each resource, errors, garbage collection.
  6. Explain the comparison: repeated, interleaved runs, an interval, a minimum effect size.
  7. Close the loop: the result becomes a capacity number at an SLO, a regression check in CI and an alert in production.

Summary

A trustworthy load test starts with a question and an SLO, uses an open model when real clients are independent, measures from the intended send time to avoid coordinated omission, and uses data, keys, connections and dependencies that look like production. It keeps the generator out of the picture, warms up, runs long enough to see periodic events, and reports a capacity at an SLO with the time series behind it. Comparing builds is statistics: per-run values, interleaving, an interval, a minimum effect and enough runs.

Check yourself

Try answering out loud before you reveal each answer.

QuestionA generator keeps 50 connections busy with no think time and reports 10,000 requests/s with a 2 ms mean latency. Is that consistent?Reveal answer

No. By Little's Law, 50 connections at 2 ms should complete about 50 ÷ 0.002 = 25,000 requests/s. The generator accounts for only 10,000 × 0.002 = 20 requests in flight. It spent the remaining time somewhere it did not measure, such as waiting to send, which is the signature of coordinated omission or a saturated generator.

QuestionYou want to detect a 2% regression and your run-to-run noise is 4% (standard deviation). Roughly how many runs per build, and what do you do about it?Reveal answer

About 16 × (4 ÷ 2)² = 64 runs per build. That is usually impractical, so reduce the noise first: dedicated hosts, fewer moving parts, longer runs, or a more deterministic metric. At 1% noise the same detection needs only 4 runs.

QuestionWhy is a closed-loop test with 100 virtual users a poor model of a public website?Reveal answer

Real visitors arrive independently of how fast the site responds. In a closed loop the users wait for slow responses, so the offered load falls as the system slows, which hides overload and queue growth. An open model keeps arriving on schedule, as real traffic does.

Sources and further reading

  • Gil Tene, "How NOT to Measure Latency" (talk, 2015), and the HdrHistogram library: coordinated omission and the expected-interval correction.
  • Schroeder, Wierman and Harchol-Balter, "Open Versus Closed: A Cautionary Tale", NSDI 2006.
  • Georges, Buytaert and Eeckhout, "Statistically Rigorous Java Performance Evaluation", OOPSLA 2007: run-to-run variance and confidence intervals.
  • Mytkowicz, Diwan, Hauswirth and Sweeney, "Producing Wrong Data Without Doing Anything Obviously Wrong!", ASPLOS 2009: measurement bias.
  • Brendan Gregg, "Active Benchmarking", and Systems Performance, 2nd edition, Addison-Wesley, 2020.
  • The BenchmarkDotNet documentation, for the microbenchmark pitfalls above.
Lesson 15 of 44

Nice. Lock it in, then keep going.

Up next · Lesson 16Profiling and finding the bottleneckA method for "the service is slow": narrow from the outside in, check every resource with the USE method, read flame graphs, find waiting time that a CPU profile cannot see, and recognize the usual culprits, with tested C#.

Send a message

It goes straight to my inbox. I usually reply within a few days.