Performance investigation
1. Define “fast enough”
Get a number: “p95 of GET /orders under 300 ms at 50 rps”, “import of a 1 GB file under 2 minutes”, “page LCP under 2.5 s”. Without a target you cannot know when to stop.
2. Reproduce and measure the baseline
- Same data size and shape as production (performance bugs hide at scale).
- Measure several runs, report median and p95, not one run.
- Tools:
hyperfinefor commands;pytest-benchmark, Gotesting.B, JMH,vitest benchfor functions;k6,wrk,hey,ohafor HTTP.
3. Profile to find where time goes
| Stack | CPU profiling | Memory |
|---|---|---|
| Python | py-spy record -o profile.svg -- python app.py, python -m cProfile -s cumtime |
tracemalloc, memray |
| Node.js | node --cpu-prof app.js (open in Chrome DevTools), 0x, clinic flame |
--heapsnapshot-signal, DevTools heap snapshots |
| Go | pprof (go test -cpuprofile, net/http/pprof) |
pprof -alloc_space |
| JVM | async-profiler, JFR | JFR, heap dumps |
| Browser | DevTools Performance panel, Lighthouse | DevTools Memory panel |
| Database | EXPLAIN (ANALYZE, BUFFERS) in PostgreSQL, slow query log, pg_stat_statements |
- |
Read the profile top-down: which function or query owns most of the wall time?
4. Usual suspects (check in this order)
- I/O in loops: N+1 queries, one HTTP call per item. Batch, join, or prefetch (
select_related/prefetch_related,includes, DataLoader). - Missing index: sequential scan on a large table in
EXPLAIN. Add the index that matches the filter and sort (create it concurrently in production). - Doing work you throw away: loading whole rows/files when you need a few fields; computing results that are not used; repeated parsing.
- Wrong data structure: list membership in a loop (O(n^2)) instead of a set/dict; repeated string concatenation in loops in some languages.
- No caching of expensive, stable results (with a clear invalidation rule).
- Serialization and logging in hot paths.
- Concurrency: sequential awaits that could run in parallel; or too much parallelism exhausting a pool.
5. Fix one thing, re-measure
Change the single biggest cost, rerun the same benchmark, and record before/after. Stop when the target is met. Keep the benchmark (or a performance test with a generous threshold) so regressions are caught.
Report
Baseline -> result with the measurement method, the bottleneck found (with profile evidence), the change, and trade-offs (memory, complexity, cache staleness).
Never present an optimization as a win without a before/after measurement.