Performance bottleneck diagnosis
Start with evidence, not a guess
A slow bookstore search might be caused by CPU, garbage collection, database locking, disk throttling, a full connection pool, network delay, cold cache, or retries. Use the same time window for offered load, successful throughput, error rate, queue age, utilization and end-to-end latency. Break down by endpoint, outcome and payload size. Correlate a trace with service and dependency metrics; aggregate percentiles from raw observations or compatible histogram buckets, not an average of per-host p95s. A high p95 is a symptom, not the identity of the bottleneck.
Use the nearest-rank definition here: sort N samples, select rank ceil(p/100 × N), counting from 1. For 10 latencies [30, 40, 50, 60, 70, 80, 90, 100, 110, 300] ms, p50 is 70 ms (rank 5); p95 rank 10 is 300. With ten samples p95 and p99 both select the maximum. Other percentile implementations may interpolate; state the method. Report sample count and timeout/rejection handling; excluding failures can make the successful-request latency distribution look deceptively good.
Diagnose by changing one thing at a time
| Observation (fictional) | Candidate cause | Follow-up test |
|---|---|---|
| CPU 95%, ready queue rises, dependency latency stable | CPU saturation | Profile hot paths; compare same workload with more usable CPU |
| CPU 25%, database span and connection wait grow | Database or pool bottleneck | Inspect lock/wait metrics; measure query plans and pool occupancy |
| Disk latency and throttled operations rise | Storage limit | Compare IOPS, throughput, queue depth and instance ceiling |
| RAM pressure, GC pauses and p99 increase | Memory pressure | Compare working set and allocation rates, controlled memory change |
| Cache hits fall, database queries rise | Cold cache or expiry wave | Compare warm/cold state with same traffic and correct cache keys |
| Retries rise while goodput falls | Retry amplification | Bound retries, add jitter, inspect first failure and deadlines |
None proves causality alone. A full connection pool could be an upstream symptom of slow queries, not a reason to raise pool size. Increased concurrency can overload the dependency. Keep the workload and other variables fixed, compare repeated bounded tests, and preserve the original baseline. Use a rollback threshold for errors and latency.
Run a bounded deterministic local model
This is a discrete-time arithmetic simulation, not a load generator or real performance benchmark. Python standard library only, no sockets, sleeps, cloud access or external requests. One step models one second, work units are indivisible requests, and service occurs before the queue cap is applied at the step boundary. Real systems need event ordering, deadlines, service-time distributions and queue age. Here the queue carries work forward and rejects overflow. Run the finite example locally with Python 3; it simulates four seconds and ten synthetic latency samples. The function limits scenarios to 100 steps; do not extend it into an uncontrolled load generator.
from math import ceil
def percentile(values, p): if not values or not 0 < p <= 100 or any(v < 0 for v in values): raise ValueError("nonempty nonnegative samples and 0 < p <= 100 required") return sorted(values)[ceil(len(values) * p / 100) - 1]
def simulate(arrivals, capacities, limit): # Each step is one simulated second. Service existing/new work first, # then bound the remaining backlog. FIFO age is not modeled. if len(arrivals) != len(capacities) or limit < 0 or len(arrivals) > 100: raise ValueError("invalid bounded scenario") backlog = 0 rows = [] for incoming, capacity in zip(arrivals, capacities): if min(incoming, capacity) < 0: raise ValueError("counts must be nonnegative") available = backlog + incoming completed = min(available, capacity) waiting = available - completed rejected = max(0, waiting - limit) backlog = waiting - rejected rows.append([completed, backlog, rejected]) return rows
samples = [30, 40, 50, 60, 70, 80, 90, 100, 110, 300]print("p95 ms:", percentile(samples, 95))for second, row in enumerate(simulate([300, 300, 300, 240], [240, 240, 360, 360], 100), 1): print(second, *row)Expected output:
p95 ms: 3001 240 60 02 240 100 203 360 40 04 280 0 0Each row is second, completed, backlog, rejected. Across four seconds, offered = 1,140, completed = 1,120, rejected = 20, final backlog = 0. The balance equation is initial backlog + arrivals = completions + rejections + final backlog. At second 2, the queue would hold 120, but the limit 100 rejects 20. Increasing capacity in second 3 reduces backlog by 60; only 280 work units are available in second 4. The p95 is from a separate invented sample array, not inferred from queue counts. This model cannot estimate real request latency.
Design a reproducible measurement plan
Before a real performance test, define permissions, isolated target, test data, rate and concurrency ceiling, maximum duration, stop conditions, and owner. In this course do not run remote load tests. Model steady demand, peak, short spike and sustained load separately. Open-loop workload schedules arrivals independently of responses; closed-loop workload waits for response before issuing more work, which may hide overload because the arrival rate decreases when latency rises. For a real authorized test, report scheduled versus achieved rate, timeouts, rejections and missed arrivals to avoid hiding coordinated omission.
Record a reproducibility manifest: hardware model and usable cores/RAM, OS and runtime version, app build, configuration, workload distribution and request sizes, sample count, warm-up, warm/cold cache state, run duration and repetitions, resource limits, region/zone if cloud, timestamps, and measurement method. Record baseline and comparison distributions plus actual error counts. For this simulation hardware and region do not determine the arithmetic; record local Python version and platform if running it. Samples = 10, simulation steps = 4, cache state not modeled, region not applicable. No measured latency, hardware speed or throughput benchmark is claimed. If a future real test is authorized, stop at preset limits (e.g. error rate above target or resource exhaustion) and never use unbounded traffic.
Choose a change and verify the outcome
Compare the application’s latency target against successful requests and separately track failures. For this sample p95 = 300 ms exceeds 180 ms, but cannot attribute the cause because the array is synthetic and independent of the queue. The simulated backlog and rejected work indicate that capacity lag and queue size are candidates in that model. Try ready capacity 300 from the first second, keep arrivals unchanged, and compare completed/rejected/backlog. No overflow occurs with capacities [300, 300, 360, 360]; that is an arithmetic result, not a promise about a real server. A larger queue may prevent rejections but increase waiting time. Prefer bounded admission and realistic deadlines. Validate changes against the original workload and cost, including cold-cache and dependency constraints.
Official guidance: AWS workload evaluation, Azure performance testing, Google resource allocation. Search excerpts reviewed; consult current provider testing policies before any authorized cloud test.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Performance bottleneck diagnosis — knowledge check
Choose the best answer for each offline scenario.
For ten sorted samples, what rank is nearest-rank p95?
CPU is low but database spans and pool waits rise. What is the next step?
In the bounded model, 120 units remain after service and queue limit is 100. How many are rejected?
What is wrong with averaging per-host p95 values?
What must a performance report include?