Pidoku

Archive

This learning material is in the archive. It is not currently maintained and has not been updated with the latest information, so tool versions, prices and dates may be out of date.

Load Testing

Module 7 Lesson 7.f 55 min Difficulty 4/5

Prerequisites 7.e

The idea in one minute#

A load test tells you how much a service can handle while meeting its SLO, and how it fails when pushed past that. It is only useful if it is honest, and the most common way to be dishonest by accident is a closed-loop load generator: a fixed number of virtual users, each waiting for its response before sending the next request. When the service slows down, the generator slows down with it — it stops sending exactly when it should be measuring pain. This is coordinated omission, and it can make a stalling service look fine.

Real users arrive regardless of how slow you are. Test with an open-loop generator that sends at a fixed arrival rate, measure latency from when each request should have been sent, and check the SLO percentiles — not the average.

An analogy#

Measuring a bank’s queue by sending ten customers who each wait for service, then rejoin the queue. If the teller takes a 20-minute break, your ten customers simply wait once — and you record one slow visit each. Real customers would have kept arriving every minute, and twenty of them would have waited.

A picture#

flowchart TB
  subgraph CL["Closed loop — N users, each waits for its reply"]
    direction LR
    U1["user"] -->|"send"| S1["service stalls 2 s"]
    S1 -->|"reply after 2 s"| U1
    U1 -.->|"no requests sent<br/>during the stall"| X1["stall measured once<br/>per user"]
  end
  subgraph OL["Open loop — fixed arrival rate"]
    direction LR
    G["generator<br/>100 req/s, on schedule"] -->|"keeps sending"| S2["service stalls 2 s"]
    S2 --> X2["200 requests see<br/>up to 2 s of delay"]
  end
  class U1,G neutral
  class S1,S2 warn
  class X1 memory
  class X2 io

How it really works#

Kinds of load test#

TestShapeQuestion it answers
BaselineExpected peak, steady, 15–30 minDoes it meet the SLO at the load we expect?
Step / ramp (capacity)Increase the rate in steps until the SLO failsWhat is the maximum rate at SLO — the unit cost for capacity planning (7.d)?
StressBeyond capacityHow does it fail? Does load shedding work? Does it recover afterwards (6.e)?
SpikeSudden 3–10× burstDo autoscaling, shedding and queues cope with a burst?
SoakNormal load for hours or daysLeaks, slow growth in memory, connection or file-handle exhaustion, log volume
Failure under loadNormal load + kill a zone, instance or dependencyDoes redundancy actually hold at real load (Module 10)?

Rules for honest load tests#

  1. Open loop. Specify an arrival rate. In k6, use the constant-arrival-rate or ramping-arrival-rate executors; in Gatling, open injection; in wrk2 or Vegeta, a fixed rate.
  2. Correct for coordinated omission. Measure latency from the intended send time. wrk2 and HdrHistogram do this; Vegeta and k6’s arrival-rate executors send on schedule.
  3. Realistic traffic. The mix of endpoints, payload sizes, cache hit rates and user IDs of production. Replaying anonymised production traffic beats a script that requests one URL.
  4. Realistic environment. Same instance types, same config, same dependencies (or explicitly mocked ones, with their latency). A test against an empty database proves little.
  5. Do not saturate the load generator. Monitor its CPU; use several generators for high rates.
  6. Look at percentiles over time, not a single summary: p99 per 10 seconds shows GC pauses and stalls that a whole-run p99 hides.
  7. Watch the whole system: the service’s USE metrics, its dependencies, the database.
  8. Test in production carefully, if at all — with synthetic flags, off-peak, with a stop button, and with downstream owners told.

k6 example (open loop, ramping)#

javascript
// checkout-capacity.js — run with: k6 run checkout-capacity.js
import http from "k6/http";
import { check } from "k6";

export const options = {
  scenarios: {
    capacity: {
      executor: "ramping-arrival-rate",     // open loop: requests per second, not users
      startRate: 100,
      timeUnit: "1s",
      preAllocatedVUs: 200,
      maxVUs: 2000,
      stages: [
        { target: 200, duration: "5m" },
        { target: 400, duration: "5m" },
        { target: 600, duration: "5m" },
        { target: 800, duration: "5m" },
      ],
    },
  },
  thresholds: {
    http_req_failed: ["rate<0.001"],                 // availability SLO
    http_req_duration: ["p(99)<800"],                // latency SLO
  },
};

export default function () {
  const res = http.post("https://staging.example.com/v1/checkout",
    JSON.stringify({ cart: "load-test-cart", synthetic: true }),
    { headers: { "Content-Type": "application/json", "x-synthetic": "1" } });
  check(res, { "status 200": (r) => r.status === 200 });
}

The capacity is the highest stage at which both thresholds hold. Divide by the instance count for the per-instance unit cost.

Reading the results#

PatternLikely cause
Latency flat, then a sharp kneeNormal saturation (7.e); the knee is your capacity
Latency climbs steadily at constant loadA leak, a growing queue, GC pressure — run a soak test
Periodic latency spikesGC, cron jobs, log rotation, compaction
Errors begin before CPU is highA software limit: pool, file descriptors, rate limit, lock
Throughput plateaus while the generator’s rate risesThe service is saturated — or the generator is
Service does not recover after a stress test endsA sustaining effect: metastable (6.e)

A worked example#

A team load-tests an API with closed-loop virtual users. The API has a hidden problem: every 10 seconds a background job holds a lock for 1 second, stalling every request. The test reports p99 = 5 ms — the normal response time. Production users complain of one-second hangs.

Re-running with an open-loop generator at the same average rate, measuring from intended send time, reports p99 ≈ 930 ms — the hang is visible. The closed-loop test also sent about 10% fewer requests: those are the ones it “omitted” while it was stuck waiting. The program below reproduces both results in a simulation.

Code#

Go
// omission.go — closed-loop vs open-loop load generation against a service that stalls.
package main

import (
	"fmt"
	"sort"
)

const (
	serviceMs  = 5.0      // normal response time
	stallEvery = 10_000.0 // ms: a background job...
	stallFor   = 1_000.0  // ...stalls everything for 1 s
	durationMs = 120_000.0
)

// respond returns when a request sent at time t completes (single-threaded service).
type service struct{ freeAt float64 }

func (s *service) respond(t float64) float64 {
	start := t
	if s.freeAt > start {
		start = s.freeAt
	}
	// If the request starts inside a stall window, it waits until the stall ends.
	phase := mod(start, stallEvery)
	if phase < stallFor {
		start += stallFor - phase
	}
	s.freeAt = start + serviceMs
	return s.freeAt
}

func mod(a, b float64) float64 { return a - b*float64(int(a/b)) }

func pct(xs []float64, p float64) float64 {
	sort.Float64s(xs)
	return xs[int(p*float64(len(xs)-1))]
}

func main() {
	// Closed loop: 1 virtual user, sends the next request as soon as the previous one returns,
	// paced to the same average rate (one every 20 ms) when the service is fast.
	{
		s := &service{}
		var lat []float64
		t := 0.0
		for t < durationMs {
			done := s.respond(t)
			lat = append(lat, done-t)
			next := t + 20
			if done > next {
				next = done // the user was blocked: requests it "should" have sent are never sent
			}
			t = next
		}
		fmt.Printf("closed loop: %6d requests  p50 %6.1f ms  p99 %7.1f ms  p99.9 %7.1f ms\n",
			len(lat), pct(lat, 0.5), pct(lat, 0.99), pct(lat, 0.999))
	}
	// Open loop: a request every 20 ms on schedule, latency measured from the intended send time.
	{
		s := &service{}
		var lat []float64
		for t := 0.0; t < durationMs; t += 20 {
			done := s.respond(t)
			lat = append(lat, done-t)
		}
		fmt.Printf("open loop:   %6d requests  p50 %6.1f ms  p99 %7.1f ms  p99.9 %7.1f ms\n",
			len(lat), pct(lat, 0.5), pct(lat, 0.99), pct(lat, 0.999))
	}
	fmt.Printf("\nThe service stalls for %.0f ms every %.0f s — 10%% of the time.\n", stallFor, stallEvery/1000)
	fmt.Println("Users arriving during a stall wait up to a second; only the open-loop test sees them.")
}

Remember this#

  • Closed-loop generators slow down with the service and hide stalls (coordinated omission).
  • Use open-loop, arrival-rate tests; measure from the intended send time; look at percentiles over time.
  • Baseline, capacity ramp, stress (and recovery), spike, soak, and failure under load each answer a different question.
  • Realistic traffic and environment, a generator that is not saturated, and the whole system watched.

Try it#

  1. Run omission.go. Change the stall to 200 ms. Does the closed-loop test notice it at all?
  2. Install k6 and run the script above against a local service (for example server.go from 6.f with the sleep removed). Find its capacity.
  3. Run a 2-hour soak test of a service you own and graph its memory. Does it plateau?

Check yourself#

  1. What is coordinated omission?
  2. Why does an open-loop test measure latency from the intended send time?
  3. Which kind of test finds a memory leak? Which finds a metastable failure?
  4. Errors begin at 40% CPU. What kind of limit should you look for?

Sources#

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in