agentleFS
reddygopalkrishnareddygopalkrishna/developer-agent-skills/skills/performance-profiling/SKILL.md

performance-profiling

Skill8 starsChanged 9 days agoMITView on GitHub

Finds and fixes backend and application performance problems by measuring first - define the target metric, reproduce under realistic load, profile CPU, memory, I/O and locks, fix the biggest bottleneck, re-measure, and add a regression guard. Use when code or a service is slow, p95 or p99 latency is high, CPU or memory usage is too high, throughput is too low, startup is slow, or the user asks to optimize, profile or benchmark. Not for page-load tuning (use web-performance) or tuning a single SQL query (use sql-optimization).

25 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use intelligent-routing, bash-linux and 10 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • SKB3002Skill

    intelligent-routing

    Automatic agent selection and intelligent task routing. Analyzes user requests and automatically selects the best specialist agent(s) without requiring explicit user mentions.

    Also in 5 projects that use this

  • xenitV1Skill

    bash-linux

    Bash/Linux terminal patterns. Critical commands, piping, error handling, scripting. Use when working on macOS or Linux systems.

    Also in 6 projects that use this

  • xenitV1Skill

    red-team-tactics

    Red team tactics principles based on MITRE ATT&CK. Attack phases, detection evasion, reporting.

    Also in 6 projects that use this

  • SKB3002Skill

    nextjs-react-expert

    React and Next.js performance optimization from Vercel Engineering. Use when building React components, optimizing performance, eliminating waterfalls, reducing bundle size, reviewing code for performance issues, or implementing server/client-side optimizations.

    Also in 3 projects that use this

  • +8 more from xenitV1

The file

Show its rules and text

We split this skill into the rules it gives an agent

13 rules. 0 are common, 12 are distinctive, and 1 is very specific to this project.

  • 0

    Common

    Most of the 14 edited versions we read keep these.

  • 12

    Distinctive

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Never optimize what you have not measured.

    line 9
  2. Distinctive:

    Not for: browser page-load and rendering (web-performance), a single slow SQL query (sql-optimization), or capacity planning without a …

    line 19
  3. Distinctive:

    Find what bounds you: before opening a profiler: CPU, memory/GC, I/O, locks, or a downstream dependency.

    line 26
  4. Distinctive:

    Look for wide plateaus near the top: that is self time worth optimizing.

    line 62
  5. Distinctive:

    Use a real harness, not a stopwatch loop:

    line 85
  6. Distinctive:

    Run many iterations and several processes.

    line 98
  7. Distinctive:

    Use realistic inputs. Sorted, tiny, or always-cached data gives misleading results.

    line 101
  8. Distinctive:

    Keep the machine quiet: no other heavy processes, power plugged in, same hardware for before and after.

    line 102
  9. Distinctive:

    Use a load generator such as k6, wrk2, vegeta, hey or Locust against a staging environment.

    line 107
  10. Very specific:

    Prefer open-model (fixed arrival rate) load, e.g.

    line 108
  11. Distinctive:

    Do not run load tests against production or shared environments without explicit confirmation from the user.

    line 113
  12. Distinctive:

    Ask before attaching a profiler to a production process.

    line 114
  13. Distinctive:

    Never trade correctness for speed silently (skipping validation, weakening consistency, unbounded caches).

    line 115

“Common” is measured: kept by at least 6 in 10 of the 14 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Performance Profiling

Never optimize what you have not measured. Profile, fix the largest bottleneck, measure again under the same conditions. A change without a before/after number is a guess.

When to use

  • A request, job, function or command is slower than it should be.
  • Tail latency (p95/p99) is high or spiky, even if the average looks fine.
  • CPU, memory, GC time, or cloud cost is too high.
  • Throughput tops out before hardware does.
  • The user asks to "make it faster", profile, or benchmark something.

Not for: browser page-load and rendering (web-performance), a single slow SQL query (sql-optimization), or capacity planning without a concrete bottleneck.

Workflow

  1. State the problem as a number. Metric, current value, target, conditions. Example: "p99 of POST /orders is 1.8 s at 300 req/s on staging; target under 400 ms." If the user gives no target, propose one and confirm it.
  2. Pick the right metric (table below). Use percentiles, never the mean, for latency.
  3. Reproduce in a production-like setup. Release/optimized build, realistic data volume and shape, same config and dependency versions, no debugger attached, JIT warmed up. Record a baseline over several runs and note the spread.
  4. Find what bounds you before opening a profiler: CPU, memory/GC, I/O, locks, or a downstream dependency. Use traces or APM first if they exist: is the time even spent in this process?
  5. Profile with the right tool for the bound and the stack. See references/profilers.md. Prefer low-overhead sampling profilers.
  6. Form one hypothesis and make one change. Fix the widest bar in the profile first. Leave code that takes 1% of time alone.
  7. Re-measure under identical conditions. Compare distributions (several runs), not single numbers. Confirm the profile changed the way you expected.
  8. Check correctness. Tests pass; output is identical; no new race conditions or stale-cache bugs.
  9. Add a regression guard (benchmark in CI, load test, or alert) so the win stays.
  10. Report a before/after table, what changed, why it helped, and any trade-offs (memory for speed, staleness for speed, complexity).

Choose the metric

GoalMeasureNotes
User-facing latencyp50, p95, p99 (and max) per endpointMean hides tail problems.
ThroughputRequests or items per second at a fixed latency SLO and error rateThroughput without a latency bound is meaningless.
MemoryRSS, live heap after GC, allocation rate, GC pause timeSteady growth over hours suggests a leak.
StartupTime to ready / first successful requestMeasure cold and warm separately.
Batch / CLIWall-clock time and cost per itemUse hyperfine for command-line comparisons.
CostCPU-seconds or dollars per requestUseful when latency is already fine.

Find the bound

SymptomLikely boundNext step
CPU near 100% of available cores; latency grows with loadCPUCPU sampling profiler, flame graph
CPU low but latency highWaiting: I/O, locks, downstream calls, pool exhaustionTraces, wall-clock/off-CPU profile, thread dump, pool metrics
Memory grows steadily and never dropsLeak or unbounded cache/queueCompare two heap snapshots taken minutes apart
High GC time, frequent pausesAllocation pressureAllocation profiler
Periodic latency spikesGC pauses, scheduled jobs, cache expiry stampede, noisy neighbourCorrelate spike times with GC logs, cron, cache TTLs
Only p99 is badContention, GC, cold caches, retries, one slow dependencyLook at slowest traces, not averages
Node.js latency rises for all requests at onceEvent-loop blockingEvent-loop delay metric, CPU profile
.NET or Java requests queue while CPU is lowThread pool starvation from blocking calls in async codeThread-pool queue length, thread dump

Reading a flame graph

  • Width is the share of samples (time). The x-axis is not time order.
  • The y-axis is stack depth; the top edge is where the CPU actually was.
  • Look for wide plateaus near the top: that is self time worth optimizing.
  • A CPU profile only shows on-CPU time. If the process waits (I/O, locks), use a wall-clock or off-CPU mode, or traces.
  • Compare a before and after flame graph of the same workload to confirm the fix.

Common wins (check in this order)

ProblemHow to spot itFix
N+1 queriesMany near-identical queries per request in logs or a trace waterfallBatch, join, eager-load, or a data loader
Missing index or bad query planSlow query log, DB time dominates tracesSee sql-optimization
Chatty networkMany sequential calls in one traceBatch requests, run independent calls in parallel, cache
Blocking I/O on a hot pathEvent-loop lag (Node), thread-pool starvation (.NET/Java), sync calls inside async codeUse async APIs end to end; move CPU work to workers
Serialization overheadJSON encode/decode wide in the profileSmaller payloads, avoid serializing twice, faster serializer
Allocations in hot loopsAllocation profile, high GC timePreallocate, reuse buffers, avoid boxing and repeated string concatenation
Lock contentionThreads blocked, low CPU, wide lock frames in wall-clock profileShrink critical sections, shard state, use concurrent data structures
Repeated expensive workSame computation or remote call with same inputsMemoize or cache with a size bound, TTL and invalidation; prevent stampedes
Wrong algorithm or data structureNested loops over large inputs, linear lookups in a loopHash maps/sets, sorting once, indexing
Logging on the hot pathFormatting or I/O of logs visible in the profileLower level, check level before formatting, sample
Pool sizingTime spent waiting for a connection or workerRight-size the pool; never above what the database can serve
Regex backtrackingOne regex dominates CPU on certain inputsAnchor and simplify the pattern, or use a linear-time engine

Benchmarking properly

  • Use a real harness, not a stopwatch loop:

    StackHarness
    Java/KotlinJMH
    C#/.NETBenchmarkDotNet (add [MemoryDiagnoser] for allocations)
    Pythonpyperf, pytest-benchmark, or python -m timeit for one-liners
    Gogo test -bench=. -benchmem -count=10, compare runs with benchstat
    Rustcriterion
    JS/TStinybench or mitata
    Any CLIhyperfine --warmup 3 'old-cmd' 'new-cmd'
  • Warm up before measuring (JIT, caches, connection pools).
  • Run many iterations and several processes; report median and spread. Treat differences inside the noise as no difference.
  • Benchmark optimized builds only (--release, -c Release, production NODE_ENV).
  • Guard against dead-code elimination and constant folding: consume results (JMH Blackhole, return values).
  • Use realistic inputs. Sorted, tiny, or always-cached data gives misleading results.
  • Keep the machine quiet: no other heavy processes, power plugged in, same hardware for before and after.
  • A microbenchmark proves a local speedup; only an end-to-end measurement proves user impact.

Load testing

  • Use a load generator such as k6, wrk2, vegeta, hey or Locust against a staging environment.
  • Prefer open-model (fixed arrival rate) load, e.g. k6's constant-arrival-rate executor or wrk2's -R. Closed-loop tools that wait for each response under-report latency when the system slows down (coordinated omission).
  • Ramp up gradually and record where latency or errors break the SLO; that is the real capacity.

Safety

  • Do not run load tests against production or shared environments without explicit confirmation from the user.
  • Ask before attaching a profiler to a production process. Prefer low-overhead samplers. Heap dumps can pause the process and contain secrets and personal data: treat dump files as sensitive and never commit or share them.
  • Never trade correctness for speed silently (skipping validation, weakening consistency, unbounded caches). Call out every such trade-off.

Anti-patterns

  • Optimizing by intuition — the real bottleneck is rarely where you guess. Profile first.
  • Reporting the mean — averages hide the tail users feel.
  • Benchmarking debug builds or cold JITs — numbers will not transfer.
  • Changing several things at once — you cannot tell which change helped or hurt.
  • Micro-optimizing a function that is 1% of the profile — no visible effect, more complexity.
  • Caching without bounds or invalidation — trades a latency problem for a memory or correctness problem.
  • Tiny test data — hides N+1s, missing indexes and O(n²) code.
  • Declaring victory on one run — noise can exceed the improvement.

Done when

  • Before and after numbers exist for the target metric under the same conditions, over several runs.
  • The target is met, or the report explains what limits further gains.
  • A new profile shows the bottleneck moved or shrank.
  • Tests pass and behaviour is unchanged.
  • A regression guard (benchmark, load test, or alert) is in place.
  • Trade-offs are written down in the PR or a code comment.

References

  • references/profilers.md — read when choosing or running a profiler, heap analyzer, tracer or load generator for a specific language or OS.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.