Learnings

Senior engineering skills

Performance and Load Testing

Performance work is a loop: measure, find the one bottleneck, change one thing, measure again. This page runs that loop on a small bank API with seven classic problems switched on, using k6 2.3 for load, cProfile and tracemalloc for profiling, and before and after numbers pasted from real 10-second runs on one laptop.

Vocabulary

Part 1 of 6 · the service, and the words for what you measure

The demo service

Vocabulary

One FastAPI service over SQLite (100 customers, 200 accounts, 200,000 transactions) and a second service that answers exchange-rate calls in 50 ms. Every problem is a switch, so each before and after is the same code with one thing changed.

ProblemEndpointSwitch (slow, then fixed)
N+1 queries/accountsmode=n1, mode=join
Missing index/accounts/7/transactionsCREATE INDEX
Small pool/reports/kindsPOOL_SIZE=2, 10
Blocking in async/fxmode=blocking, mode=async
Big payload/statement/7mode=full, compact, page
Chatty calls/dashboardmode=sequential, concurrent
No timeout/quoteno parameter, timeout=0.3
  • Every database call sleeps 1 ms first, to stand in for the network hop a real database has.
  • All numbers are from one 10-core laptop with k6 and the service on the same machine. Yours will differ: read the ratios, not the values.

Latency, throughput, concurrency

Vocabulary

Three numbers describe a service under load, and any two give you the third: throughput = concurrency / latency (Little's law).

Latency of one request is its time in the queue plus its time in service.
TermMeaningUnit
LatencyTime for one request, including waitingms, as percentiles
ThroughputRequests completed per secondreq/s
ConcurrencyRequests in the system at one momenta count
SaturationThe busiest resource has no spare capacity, so work queuesqueue length, wait time

Worked number: 20 users on /statement/7 saw 489 ms on average, so 20 / 0.489 s = 40.9 req/s. k6 reported 40.3.

Percentiles, and why the mean lies

Vocabulary

/balance/7?tail=1 answers in about 2 ms, except that 2 requests in 100 take 400 ms. This script, used for most runs below, hits one URL with a fixed number of users.

StatisticValueWhat it says
p50 (median)2.18 msHalf the requests were faster than this
p954.33 msStill looks healthy: the tail is thinner than 5%
p99403.92 ms1 request in 100 waits this long or longer
Mean10.8 msNo request took 10.8 ms: 5 times the median, 37 times under the tail
  • A page that makes 10 such calls hits the slow path 1 − 0.9810 = 18% of the time. Tails multiply.
  • Never average percentiles from several instances. Merge the histograms, or take the worst.

Saturation and the knee

Vocabulary

Latency stays flat while there is spare capacity, then turns sharply upward: that corner is the knee. Each point below is a 10-second run of /reports/kinds at a fixed arrival rate (rate.js).

Flat to 140 req/s, then 197 ms, 598 ms and 1 s. The limit is about 165 req/s.

With a fixed number of users instead, saturation shows as throughput that stops rising. Same service, /statement/7, one process:

UsersThroughputAverage latency
185 req/s12 ms
293 req/s21 ms
481 req/s49 ms
2040 req/s489 ms
  • Past saturation, extra concurrency buys latency, not throughput. Here it even costs throughput.
  • Runs near the knee are noisy: 140 req/s gave a p95 of 71 ms in one run and 458 ms in another.

Method

Part 2 of 6 · how to work, before any tool

Measure first, one change at a time

Method

Guessing where the time goes is wrong often enough that the rule is absolute: no change without a measurement before and after.

The loop ends at the target, not when the code runs out of things to tune.
  • Target: a number with a load, such as "p95 under 200 ms at 300 req/s".
  • One change: two changes in one run cannot be told apart, and one of them may have made things worse.
  • Same conditions: same data, same machine, same script, and a warm-up before the numbers count.

The bottleneck rule and Amdahl's law

Method

A request passes through stages, and the system's throughput is the capacity of the slowest one. Speeding up any other stage changes nothing.

Example capacities. The pool sets the limit until it is fixed, then the database does.
  • Measured in the pool chapter: pool 2 gave 49 req/s, pool 10 gave 134, pool 20 gave 133. Fixing a bottleneck moves it.

Amdahl's law is the same rule for time: the gain from speeding up one part is capped by that part's share of the total. The numbers are one real /statement/7 request: 11.6 ms, of which 3.1 ms is JSON encoding.

Interview point: the same formula limits parallelism. If 10% of a job is serial, no number of machines makes it more than 10 times faster.

Where the time goes

Part 3 of 6 · timing a request, then profiling CPU and memory

The timeline of one request

Where the time goes

Latency is a sum of stages, and most of them are waiting, not computing.

Five places to lose time: network, queueing, app CPU, database, serialisation.
  • The server can time only what happens after it picks the request up.
  • Queueing appears in two places: before a worker, and before a database connection.

Timing middleware

Where the time goes

The cheapest tool: time each stage into a per-request dict and return it in a Server-Timing header. Whatever is not in a named stage is reported as app.

  • 66 of 67.5 ms is db. Nothing in the Python code is worth optimising here.
  • Browsers show Server-Timing in the network panel. Across services the same idea is distributed tracing.

Server-side and client-side latency

Where the time goes

The same request, timed from both ends. On localhost the gap is under a millisecond, which is the best it will ever be.

The server cannot seeShows up as
DNS, TCP and TLS setupSlow first request per connection
Load balancer and accept queuesClient p99 far above server p99 under load
Response downloadLarge bodies, slow mobile networks
Client retries and timeoutsThe user waited 3 attempts, the server logged 3 fast ones

Rule: set targets on latency measured at the load balancer or the client. Use server-side timing to explain it.

CPU profile with cProfile

Where the time goes

When the time is in app, profile the handler's work outside the web server. build_statement(7, "full") formats 941 rows and encodes them as JSON.

  • cumtime includes callees, tottime does not. Read cumtime top down to find the branch, then tottime to find the line.
  • json.dumps is half the time, in encoder.py: passing indent=2 switches off the C encoder. strptime on every row is another quarter.
  • cProfile slows call-heavy Python the most, so trust the ranking more than the seconds. The basics are in Python Performance.

Sampling profilers and flame graphs

Where the time goes

A sampling profiler reads the stack of a live process about 100 times a second, with almost no overhead, so it can run in production. py-spy 0.4.4 would not attach here ("This program requires root on OSX"), so these commands were not run for this page.

Its output is a flame graph. This sketch is drawn by hand from the cProfile shares above:

  • Look for wide boxes near the top: that is where the CPU is. Left to right order is alphabetical, not time.
  • A default flame graph shows CPU. Time spent waiting needs an off-CPU or wall-clock mode (py-spy record --idle).

Memory with tracemalloc

Where the time goes

This handler keeps every request in a list "for auditing". A debug endpoint takes a tracemalloc snapshot on its first call, and on later calls prints the top three lines of snapshot.compare_to(baseline, "lineno").

  • Lines 196 and 197 are the append. The signature of a leak is a count that tracks the request count: 5,000 requests, 5,000 strings.
  • Fix by bounding it: collections.deque(maxlen=1000), a TTL, or an LRU limit.

Waiting or computing?

Where the time goes

Compare wall-clock time with CPU time for the same work. The answer picks the fix, so find it before choosing one.

Waiting (I/O)Computing (CPU)
CPU during loadLow, yet latency is highA core pinned near 100%
ProfilercProfile shows sleep, recv, executeYour own functions on top
FixFewer round trips, concurrency, pools, timeoutsLess work, better algorithm, more processes

Seven bottlenecks, reproduced and fixed

Part 4 of 6 · each with before and after numbers from k6

N+1 queries

Seven bottlenecks

One query for 50 accounts, then one more per account for its owner: 51 round trips where one JOIN would do.

ModeQueriesOne request, db20 users, p95Throughput
n15164.7 ms258 ms150 req/s
join11.3 ms28 ms1,112 req/s
  • The cost is round trips, not rows, so it hides on a laptop database and hurts on a networked one.
  • Spot it by counting queries per request. ORM causes and fixes are in Python and Databases.

A missing index

Seven bottlenecks

The 20 latest transactions of one account, from a table of 200,000 rows with no index on account_id. Ask the database for its plan before and after.

One request, db20 users, p95Throughput
No index9.8 ms124 ms317 req/s
Index1.3 ms23 ms1,364 req/s
  • SCAN reads every row and grows with the table. SEARCH ... USING INDEX does not.
  • Filter column first, sort column second: the composite index also removed the temporary sort.
  • Every index slows writes. Add them for queries you have measured, not for every column.

A connection pool that is too small

Seven bottlenecks

/reports/kinds runs one 35 ms aggregate. With 20 users and 2 connections, 18 requests are always waiting for a connection.

The query is fast. The wait in front of it is ten times longer.
POOL_SIZEp95Throughput
2566 ms49 req/s
10231 ms134 req/s
20223 ms133 req/s
  • Pool wait is invisible in query time. Time it separately, as pool does here.
  • 10 to 20 changed nothing: the bottleneck had moved to the database's CPU.
  • Pool size times app instances must stay under the database's connection limit.

A blocking call in an async handler

Seven bottlenecks

An async def handler runs on the event loop, and the loop is one thread. A synchronous 50 ms call inside it stops every other request for 50 ms.

Blocking turns concurrent requests into a single-file queue.
Mode, 20 usersp95ThroughputServer log for one request
blocking1.09 s18 req/stotal=1089.0ms app=1089.0
async55 ms376 req/stotal=50.6ms app=50.6
  • 20 users times 50 ms is about 1 s: the latency is the queue. Large unexplained app time in an async service means a blocked loop.
  • Fixes: an async client, await asyncio.to_thread(call) (Python 3.9+), or a plain def handler, which FastAPI runs in a thread pool.

Oversized payloads and serialisation

Seven bottlenecks

mode=full returns all 941 transactions, pretty-printed, with dates reformatted per row. compact drops the formatting and page returns 20 rows and a cursor.

ModeBodyOne request20 users, p95Throughput
full196,361 bytes11.6 ms591 ms40 req/s
compact84,007 bytes3.6 ms440 ms63 req/s
page1,836 bytes1.7 ms22 ms1,343 req/s
full, 4 processes196,361 bytes196 ms195 req/s
  • Return what the screen shows: paginate, and let clients choose fields. It beat every encoder tweak here.
  • CPU work in threads does not scale in Python: one process fell from 85 to 40 req/s as users rose (see the knee). uvicorn --workers 4 gave 195.

Chatty calls to a downstream service

Seven bottlenecks

The dashboard needs five exchange rates at 50 ms each. In sequence the latency is the sum, concurrently it is the slowest one.

ModeOne request, rates5 users, p95Throughput
sequential265.5 ms276 ms19 req/s
concurrent55.2 ms121 ms57 req/s
  • Better than concurrent calls is one call: ask the downstream team for a batch endpoint.
  • gather sends the downstream service five times the burst. Cap it with a semaphore.
  • Rates change slowly, so this is also a cache candidate: see Caching Strategies.

No timeout on a slow dependency

Seven bottlenecks

The rates service is made to take 3 seconds per call. Without a timeout the bank API becomes exactly as slow, and with one it answers from the last good value.

DependencyTimeout20 users, p95ThroughputAnswer
Healthy, 50 msnone143 ms296 req/s"stale":false
Slow, 3 snone3.06 s6.6 req/s"stale":false
Slow, 3 s0.3 s319 ms63 req/s"stale":true
  • requests has no default timeout and waits for ever. httpx defaults to 5 seconds, which is still too long for most calls.
  • Set the timeout a little above the dependency's normal p99, and decide what to return when it fires.
  • Every waiting request holds a worker, a connection and memory. That is how one slow dependency takes down its callers.

Load testing with k6

Part 5 of 6 · scripts, the summary, thresholds, workload models

A first script

Load testing with k6

A k6 script is JavaScript: options describe the load, and the default function is one user's journey, repeated. This one ramps to 20 users, holds, and ramps down.

  • Think time: without sleep, 20 virtual users behave like hundreds of real ones. With it, 20 users made about 30 req/s.
  • Test data: one account id tests one cached row. Spread requests over realistic ids, sizes and users.
  • Tags: name groups URLs that differ only by id, and lets a threshold target one endpoint.

Reading the summary

Load testing with k6

k6 run journey.js prints this at the end (k6 v2.3.0).

FieldRead it as
http_req_durationLatency per request, send to last byte. Read p95 and p99, not avg.
{ expected_response:true }The same, successful responses only. Fast errors can make the line above look good.
http_req_failedShare of responses with status 400 or above, or no response. Check it first.
http_reqsRequests and throughput: 29.7 req/s
iterations, iteration_durationWhole journeys: 3 requests plus 1.5 s of think time each
vus, vus_maxVirtual users at the last sample (ramped down to 1), and the peak
checksAssertions on responses. A failed check does not fail the run: a threshold does.

Thresholds: pass or fail

Load testing with k6

Thresholds turn a run into a test. The same script, first as written, then with the N+1 listing switched back on.

  • The overall p95 passed while one endpoint got 13 times slower. Put thresholds on the endpoints you care about.
  • Exit code 99 is what a CI job fails on.

Open and closed workloads

Load testing with k6

A closed model has a fixed number of users, each waiting for its answer before sending again. An open model starts requests on a schedule, whether or not earlier ones have come back.

Coordinated omission: the closed user waited politely, so it never sent the requests that would have been slow.

Both models against the blocking /fx, which can serve about 18 req/s:

ModelLoad offeredp95k6 also reports
Closed, 20 usersWhatever the server allows: 18 req/s1.09 sNothing wrong
Open, 40 req/s40 req/s, regardless7.65 sdropped_iterations: 117, VUs grew to 167
  • Internet traffic is open: users do not slow down because your server did. Use arrival-rate executors for capacity questions.
  • Closed models fit a fixed worker fleet or a batch client, and are fine for comparing before and after.

Five kinds of test

Load testing with k6

The script stays the same. Only the load shape changes, and with it the question being asked.

Smoke: does the script and the system work at all?
Load: do we meet the targets at the expected peak?
Stress: where is the knee, and what breaks first beyond it?
Spike: do we survive a sudden jump, and recover after it?
Soak: does anything leak or fill up over hours?
KindLoadLengthRun it
Smoke1 to 5 users1 minuteOn every change to the script or the service
LoadExpected peak10 to 30 minutesBefore each release, nightly
StressSteps past the peakUntil it bendsBefore a launch, after an architecture change
SpikeIdle to several times peak in secondsMinutesBefore a sale, a campaign, a push notification
SoakNormal load4 to 24 hoursBefore a launch, after dependency or runtime upgrades

Not run: the runs on this page are 10 to 20 seconds, so they are smoke-sized. The leak in the tracemalloc chapter is what a soak test exists to find.

Capacity and production

Part 6 of 6 · sizing a fleet, protecting it, keeping it fast

From one instance to a fleet

Capacity and production

Measure one instance to its limit, plan well below it, then divide. The figures are from the knee chapter.

Scale up (bigger machine)Scale out (more instances)
Helps whenOne process can use the extra cores or memoryThe service is stateless
LimitThe largest machine, and one failure takes everythingWhatever is shared: the database, its connections
Measured hereOne process, more threads: no gain (GIL)4 processes: 40 to 195 req/s
  • Autoscale on a leading signal: CPU for CPU-bound services, requests or concurrency per instance for I/O-bound ones, queue depth for workers.
  • Latency is a poor scaling signal: it moves only after the knee, and a slow dependency raises it without any need for more instances.
  • New instances take minutes. Headroom is what serves traffic until they arrive.

Why 80% is the limit

Capacity and production

Requests arrive at random, so a busy server sometimes gets two at once and one waits. For the simplest queue (one server, random arrivals) the average wait is service time × u / (1 − u), where u is utilisation.

UtilisationAverage wait, in service timesWith a 35 ms service time
50%135 ms
70%2.382 ms
80%4140 ms
90%9315 ms
95%19665 ms
  • From 80% to 90% the wait more than doubles. That curve is the knee.
  • More servers behind one queue push the knee to the right, which is why the 10-connection service above stayed flat to 85% of its limit. The shape stays.

Guardrails

Capacity and production

Past the knee a service must refuse work, or it does all of it badly. Each guardrail turns an unbounded wait into a fast, explicit answer.

Limits on the way in, timeouts on the way out, and a planned answer for each refusal.
GuardrailDoesWithout it
TimeoutCaps the wait on every outbound call6.6 req/s
LimitCaps requests per client and work in progressOne caller starves the rest
BackpressureA full queue slows or refuses the producerQueues grow until memory runs out
Load sheddingRejects excess early with 503 and Retry-AfterEvery request is slow, then every request fails

Trap: retries without backoff and a budget multiply load exactly when the system is weakest.

Budgets, CI and dashboards

Capacity and production

A performance budget is a threshold someone agreed to, checked on every merge. The step below is a sketch and was not run for this page: the k6 exit code is what fails the job.

Dashboard rowGraphs
TrafficRequests per second, by endpoint
Errors5xx and timeout rate, shed (429, 503) rate
Latencyp50, p95, p99 per endpoint, measured at the load balancer
SaturationCPU, memory, pool in use and pool wait, queue depth, event loop lag
DependenciesLatency and error rate of each downstream call and of the database
  • CI machines are noisy. Use generous thresholds there to catch large regressions, and a dedicated environment for real numbers.

Symptom to likely cause

Capacity and production

SymptomLikely causeCheck
Slow at any load, CPU idleN+1, sequential downstream callsQueries and calls per request
Slower as the table growsMissing indexEXPLAIN: a scan
Fast alone, slow under load, CPU idlePool or thread limitPool wait time
Async service, every endpoint slow togetherBlocked event loopLoop lag, a sync call in async def
One core at 100%, throughput flatCPU-bound handlerProfile, then add processes
p99 bad, p50 fineA slow path, GC, lock, or one bad instanceSlice p99 by endpoint and host
Everything slow when one dependency isNo timeoutOutbound call durations
Memory climbs until a restartUnbounded list or cachetracemalloc diff, soak test
Throughput falls as load risesPast saturation, retries piling onShed load, find the limit

Pre-launch checklist

Capacity and production

CheckDone when
Targetsp95 and p99 per key endpoint, at a stated peak rate, are written down
Load testTargets met at peak, open workload model, production-sized data
Stress and soak testsThe limit of one instance is known, and memory is flat over hours
TimeoutsEvery outbound call has one, with a fallback or a clear error
Pools and limitsPool size times instances fits the database, and queues are bounded
HeadroomPeak fits in 70% of capacity with one instance down
Dashboards and alertsLatency, errors, saturation and dependencies are visible before launch day

Interview questions

Capacity and production

QuestionShort answer
An endpoint is slow. What do you do first?Measure where the time goes (stage timings, a trace) before changing anything.
Why p99 and not the average?The average hides the tail, and users with many requests meet the tail often.
How are latency, throughput and concurrency related?Throughput = concurrency / latency. Past saturation, more concurrency only adds latency.
What is coordinated omission?A closed-loop tester slows down with the server, so it under-samples the slow period. Use an arrival rate.
CPU is at 20% and the service is slow. Why?It is waiting: on a pool, a lock, a dependency or a blocked event loop.
How many instances do you need?Measure one to its knee, plan at about 70%, divide the peak by that, add a spare.
Why not run at 95% utilisation?Queueing: the wait is 19 service times at 95% and 4 at 80%.
What happens when a dependency gets slow?Without timeouts and limits, callers queue up and fail too. With them, the service degrades and stays up.

Back to Senior Skills.