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
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.
| Problem | Endpoint | Switch (slow, then fixed) |
|---|---|---|
| N+1 queries | /accounts | mode=n1, mode=join |
| Missing index | /accounts/7/transactions | CREATE INDEX |
| Small pool | /reports/kinds | POOL_SIZE=2, 10 |
| Blocking in async | /fx | mode=blocking, mode=async |
| Big payload | /statement/7 | mode=full, compact, page |
| Chatty calls | /dashboard | mode=sequential, concurrent |
| No timeout | /quote | no 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
Three numbers describe a service under load, and any two give you the third: throughput = concurrency / latency (Little's law).
| Term | Meaning | Unit |
|---|---|---|
| Latency | Time for one request, including waiting | ms, as percentiles |
| Throughput | Requests completed per second | req/s |
| Concurrency | Requests in the system at one moment | a count |
| Saturation | The busiest resource has no spare capacity, so work queues | queue 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
/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.
| Statistic | Value | What it says |
|---|---|---|
| p50 (median) | 2.18 ms | Half the requests were faster than this |
| p95 | 4.33 ms | Still looks healthy: the tail is thinner than 5% |
| p99 | 403.92 ms | 1 request in 100 waits this long or longer |
| Mean | 10.8 ms | No 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
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).
With a fixed number of users instead, saturation shows as throughput that stops rising. Same service, /statement/7, one process:
| Users | Throughput | Average latency |
|---|---|---|
| 1 | 85 req/s | 12 ms |
| 2 | 93 req/s | 21 ms |
| 4 | 81 req/s | 49 ms |
| 20 | 40 req/s | 489 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
Guessing where the time goes is wrong often enough that the rule is absolute: no change without a measurement before and after.
- 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
A request passes through stages, and the system's throughput is the capacity of the slowest one. Speeding up any other stage changes nothing.
- 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
Latency is a sum of stages, and most of them are waiting, not computing.
- 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
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-Timingin the network panel. Across services the same idea is distributed tracing.
Server-side and client-side latency
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 see | Shows up as |
|---|---|
| DNS, TCP and TLS setup | Slow first request per connection |
| Load balancer and accept queues | Client p99 far above server p99 under load |
| Response download | Large bodies, slow mobile networks |
| Client retries and timeouts | The 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
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.
cumtimeincludes callees,tottimedoes not. Readcumtimetop down to find the branch, thentottimeto find the line.json.dumpsis half the time, inencoder.py: passingindent=2switches off the C encoder.strptimeon 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
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
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?
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 load | Low, yet latency is high | A core pinned near 100% |
| Profiler | cProfile shows sleep, recv, execute | Your own functions on top |
| Fix | Fewer round trips, concurrency, pools, timeouts | Less 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
One query for 50 accounts, then one more per account for its owner: 51 round trips where one JOIN would do.
| Mode | Queries | One request, db | 20 users, p95 | Throughput |
|---|---|---|---|---|
n1 | 51 | 64.7 ms | 258 ms | 150 req/s |
join | 1 | 1.3 ms | 28 ms | 1,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
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, db | 20 users, p95 | Throughput | |
|---|---|---|---|
| No index | 9.8 ms | 124 ms | 317 req/s |
| Index | 1.3 ms | 23 ms | 1,364 req/s |
SCANreads every row and grows with the table.SEARCH ... USING INDEXdoes 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
/reports/kinds runs one 35 ms aggregate. With 20 users and 2 connections, 18 requests are always waiting for a connection.
POOL_SIZE | p95 | Throughput |
|---|---|---|
| 2 | 566 ms | 49 req/s |
| 10 | 231 ms | 134 req/s |
| 20 | 223 ms | 133 req/s |
- Pool wait is invisible in query time. Time it separately, as
pooldoes 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
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.
| Mode, 20 users | p95 | Throughput | Server log for one request |
|---|---|---|---|
blocking | 1.09 s | 18 req/s | total=1089.0ms app=1089.0 |
async | 55 ms | 376 req/s | total=50.6ms app=50.6 |
- 20 users times 50 ms is about 1 s: the latency is the queue. Large unexplained
apptime in an async service means a blocked loop. - Fixes: an async client,
await asyncio.to_thread(call)(Python 3.9+), or a plaindefhandler, which FastAPI runs in a thread pool.
Oversized payloads and serialisation
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.
| Mode | Body | One request | 20 users, p95 | Throughput |
|---|---|---|---|---|
full | 196,361 bytes | 11.6 ms | 591 ms | 40 req/s |
compact | 84,007 bytes | 3.6 ms | 440 ms | 63 req/s |
page | 1,836 bytes | 1.7 ms | 22 ms | 1,343 req/s |
full, 4 processes | 196,361 bytes | 196 ms | 195 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 4gave 195.
Chatty calls to a downstream service
The dashboard needs five exchange rates at 50 ms each. In sequence the latency is the sum, concurrently it is the slowest one.
| Mode | One request, rates | 5 users, p95 | Throughput |
|---|---|---|---|
sequential | 265.5 ms | 276 ms | 19 req/s |
concurrent | 55.2 ms | 121 ms | 57 req/s |
- Better than concurrent calls is one call: ask the downstream team for a batch endpoint.
gathersends 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
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.
| Dependency | Timeout | 20 users, p95 | Throughput | Answer |
|---|---|---|---|---|
| Healthy, 50 ms | none | 143 ms | 296 req/s | "stale":false |
| Slow, 3 s | none | 3.06 s | 6.6 req/s | "stale":false |
| Slow, 3 s | 0.3 s | 319 ms | 63 req/s | "stale":true |
requestshas no default timeout and waits for ever.httpxdefaults 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
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:
namegroups URLs that differ only by id, and lets a threshold target one endpoint.
Reading the summary
k6 run journey.js prints this at the end (k6 v2.3.0).
| Field | Read it as |
|---|---|
http_req_duration | Latency 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_failed | Share of responses with status 400 or above, or no response. Check it first. |
http_reqs | Requests and throughput: 29.7 req/s |
iterations, iteration_duration | Whole journeys: 3 requests plus 1.5 s of think time each |
vus, vus_max | Virtual users at the last sample (ramped down to 1), and the peak |
checks | Assertions on responses. A failed check does not fail the run: a threshold does. |
Thresholds: pass or fail
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
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.
Both models against the blocking /fx, which can serve about 18 req/s:
| Model | Load offered | p95 | k6 also reports |
|---|---|---|---|
| Closed, 20 users | Whatever the server allows: 18 req/s | 1.09 s | Nothing wrong |
| Open, 40 req/s | 40 req/s, regardless | 7.65 s | dropped_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
The script stays the same. Only the load shape changes, and with it the question being asked.
| Kind | Load | Length | Run it |
|---|---|---|---|
| Smoke | 1 to 5 users | 1 minute | On every change to the script or the service |
| Load | Expected peak | 10 to 30 minutes | Before each release, nightly |
| Stress | Steps past the peak | Until it bends | Before a launch, after an architecture change |
| Spike | Idle to several times peak in seconds | Minutes | Before a sale, a campaign, a push notification |
| Soak | Normal load | 4 to 24 hours | Before 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
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 when | One process can use the extra cores or memory | The service is stateless |
| Limit | The largest machine, and one failure takes everything | Whatever is shared: the database, its connections |
| Measured here | One 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
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.
| Utilisation | Average wait, in service times | With a 35 ms service time |
|---|---|---|
| 50% | 1 | 35 ms |
| 70% | 2.3 | 82 ms |
| 80% | 4 | 140 ms |
| 90% | 9 | 315 ms |
| 95% | 19 | 665 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
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.
| Guardrail | Does | Without it |
|---|---|---|
| Timeout | Caps the wait on every outbound call | 6.6 req/s |
| Limit | Caps requests per client and work in progress | One caller starves the rest |
| Backpressure | A full queue slows or refuses the producer | Queues grow until memory runs out |
| Load shedding | Rejects excess early with 503 and Retry-After | Every 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
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 row | Graphs |
|---|---|
| Traffic | Requests per second, by endpoint |
| Errors | 5xx and timeout rate, shed (429, 503) rate |
| Latency | p50, p95, p99 per endpoint, measured at the load balancer |
| Saturation | CPU, memory, pool in use and pool wait, queue depth, event loop lag |
| Dependencies | Latency 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
| Symptom | Likely cause | Check |
|---|---|---|
| Slow at any load, CPU idle | N+1, sequential downstream calls | Queries and calls per request |
| Slower as the table grows | Missing index | EXPLAIN: a scan |
| Fast alone, slow under load, CPU idle | Pool or thread limit | Pool wait time |
| Async service, every endpoint slow together | Blocked event loop | Loop lag, a sync call in async def |
| One core at 100%, throughput flat | CPU-bound handler | Profile, then add processes |
| p99 bad, p50 fine | A slow path, GC, lock, or one bad instance | Slice p99 by endpoint and host |
| Everything slow when one dependency is | No timeout | Outbound call durations |
| Memory climbs until a restart | Unbounded list or cache | tracemalloc diff, soak test |
| Throughput falls as load rises | Past saturation, retries piling on | Shed load, find the limit |
Pre-launch checklist
| Check | Done when |
|---|---|
| Targets | p95 and p99 per key endpoint, at a stated peak rate, are written down |
| Load test | Targets met at peak, open workload model, production-sized data |
| Stress and soak tests | The limit of one instance is known, and memory is flat over hours |
| Timeouts | Every outbound call has one, with a fallback or a clear error |
| Pools and limits | Pool size times instances fits the database, and queues are bounded |
| Headroom | Peak fits in 70% of capacity with one instance down |
| Dashboards and alerts | Latency, errors, saturation and dependencies are visible before launch day |
Interview questions
| Question | Short 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.