SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
  • Three Pillars of Observability
  • Logging Best Practices
  • Log Aggregation
  • Metrics and Instrumentation
  • Distributed Tracing
  • Alerts and Monitoring
  • Dashboards and Runbooks
  • SLOs and Error Budgets
  • Incident Management and Postmortems
  • Profiling
  • Audit Logs
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Operations and Security/Observability

Profiling

Find out which code uses the time and memory: CPU profiles, flame graphs and continuous profiling.

โฑ 12 min readIntermediateHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Profiling measures where a running program spends its time and memory, down to the function or line. Metrics tell you that something is slow. A profile tells you which code is making it slow.

  • Kinds: CPU, memory (heap and allocations), lock contention, I/O and garbage collection.
  • Flame graph: the usual picture. A wide frame means a lot of time. Look for wide plateaus.
  • Rule: measure first, change one thing, measure again. Guessing is how teams optimise the wrong code.

02Concept: What is it?

Your dashboards say the p99 latency of a service doubled. Tracing says the time is spent inside one service. Now what? You need to look inside that process. A profiler does this: it records which functions are running (and who called them) many times a second, and adds up the result.

Sampling and instrumenting

A sampling profiler looks at the program's call stack about 100 times a second and counts what it sees. It is cheap, and safe enough to run in production. An instrumenting profiler adds code around every function to time it exactly, but slows the program down, sometimes a lot, and can change what it measures.

Sampling: a photo of the call stack, many times a second
๐Ÿ“ธSample 1main โ†’ handle โ†’ waitForDb
๐Ÿ“ธSample 2main โ†’ handle โ†’ parseJson
๐Ÿ“ธSample 3main โ†’ handle โ†’ waitForDb
โ†’โ†“count
๐Ÿ”ฅFlame graphwidth = share of samples
If 40 of 100 photos show the program inside waitForDb, about 40% of the time is spent there.

How to read a flame graph

  • Width is time (or memory). It is not a timeline from left to right.
  • Height is call depth. The caller is above (or below, in an icicle chart), and its callees sit next to it.
  • Self time is the part of a frame not covered by the frames on top of it. This is where the function itself is working.
  • Look for wide plateaus: a wide frame with little above it is a hot spot.
๐Ÿง Profile first, then optimise
Programmers are famously bad at guessing where their code is slow. The profile is cheap, the wrong optimisation is not.

03Real-Life Example

๐ŸตThe Slow Morning Commute
You want to shorten your commute. You could buy a faster car, but a trip log shows 5 minutes driving, 20 minutes in a traffic jam, 5 minutes parking. A car twice as fast saves just 2.5 minutes. The log (the profile) says the jam is the thing to fix, so you change your leaving time instead.
Commute
Profiling
A log of every leg of the trip
A profile of where time goes
The 20-minute jam
A wide frame in the flame graph
A faster car
Optimising a narrow function
Leave earlier
Remove the real hot spot (cache, batch, index)
Time the trip again after a change
Measure again after each change
Checking every day, on every road
Continuous profiling in production

04Why Do We Need It?

๐ŸŽฏFind the real hot spot
Most of the time is in a few places. A profile points straight at them.
๐Ÿ’ธLower the bill
10% less CPU across a big fleet is a lot of servers saved.
๐ŸขCut tail latency
Lock waits and GC pauses show up in profiles, not in averages.
๐Ÿง Catch memory leaks
A heap profile shows what keeps growing.
๐Ÿ”ฌSettle arguments
Numbers replace opinions in design reviews.
๐Ÿ”Spot regressions
Compare todayโ€™s profile with last weekโ€™s after a release.
Metrics say the house is hot. A profile says which room is on fire.

05Where Do We Use It?

๐ŸŒWeb services
Find slow handlers, JSON parsing, template rendering or ORM overhead.
๐Ÿ—„๏ธDatabases
Query plans and CPU profiles of the engine itself.
โ˜•Managed runtimes
JVM, Go and .NET services with garbage collection need allocation profiles.
๐ŸงฎData pipelines
Spark and batch jobs often have one slow stage or a skewed key.
๐Ÿ“ฑMobile and front end
Browser and phone profilers show slow frames and long tasks.
๐ŸงตConcurrent code
Lock contention and thread pool starvation hide in wait time.

06Types / Parts / How It Works

What you can profile

KindQuestion it answersTypical clue
CPUWhich code burns the CPU?A wide frame of pure computation
Wall-clock / off-CPUWhere does the program wait?Time in I/O, sleeps, locks
Heap / memoryWhat holds the memory?An object type that keeps growing
AllocationsWho creates the most objects?A hot loop that allocates, causing GC pressure
Lock contentionWhich locks make threads wait?Many threads blocked on one mutex
I/OWhich reads and writes are slow?Many small disk or network calls
GCHow long are the pauses?Latency spikes at regular intervals

Sampling vs instrumenting

SamplingInstrumenting
How it worksLooks at the stack many times a secondAdds timing code around functions
OverheadLow (often a few percent)Can be high
AccuracyStatistical: fine for hot spots, can miss tiny functionsExact counts, but may change behaviour
Use in productionYes, often continuouslyRarely

Tools you may hear of

๐ŸนpprofGo and others
โ˜•async-profilerJVM
๐ŸeBPF toolsLinux, whole system
๐Ÿ”ฅPyroscope / Parcacontinuous profiling
Language tool System-wide Always-on platform
VisualizerClick a hot spot, then speed it upClick different frames in the flame graph, then slide the improvement. Compare making the wide waitForDb frame 50% faster with making the narrow escapeHtml frame 100% faster.
Flame graph (top-down): width = time, children sit below their caller. Click a frame. Red and amber frames own the most time of their own.
Self time
44 ms
in the function itself
Total time
44 ms
including callees
Request
100 โ†’ 78.0 ms
before โ†’ after
Speedup
1.28ร—
whole request
waitForDb owns 44% of the request, so a 50% improvement here cuts 22.0% of the total time. This is where profiling says to look.

A made-up profile with fixed numbers. Amdahl's law: overall speedup = 1 รท (1 โˆ’ share ร— improvement), where share is the part you improve. A real profile has thousands of frames and many requests, but the lesson is the same.

07How to Use It / Steps / Implementation

A profiling session

  1. 1
    Start from a symptom
    A slow endpoint, high CPU, a growing memory chart, or a latency spike from your metrics and traces.
  2. 2
    Reproduce under realistic load
    A profile of an idle test says little. Use production-like data and traffic.
  3. 3
    Pick the right profile
    CPU for burning cores, wall-clock for waiting, heap for memory, contention for locks.
  4. 4
    Collect for long enough
    Sampling needs many samples. Thirty seconds under load is a typical start.
  5. 5
    Read the flame graph
    Find the widest plateaus, and read the code around them.
  6. 6
    Change one thing
    Fix the biggest hot spot. Cache a result, batch calls, add an index, avoid a copy.
  7. 7
    Measure again
    Compare before and after, with the same load. Keep a benchmark or a profile in the pull request.
  8. 8
    Make it continuous
    Run a low-overhead profiler in production so you can look back at yesterdayโ€™s spike.

Amdahl's law in one line

If a part takes a share s of the total time and you make it k times faster, the overall speedup is 1 รท ((1 โˆ’ s) + s รท k). Making a 5% part infinitely fast gives at most 1.05ร—. Making a 50% part twice as fast gives 1.33ร—.

โš ๏ธMicro-benchmark traps
A tiny benchmark can lie. Code may be faster only when warm (JIT, caches), the compiler may remove work whose result you never use, and real inputs differ from toy ones. Confirm with the real service profile.

08Key Terms to Know

TermMeaning in easy words
ProfilerA tool that records where a program spends time or memory
SamplingLooking at the call stack at regular moments and counting
InstrumentationAdding code to measure each function exactly
Flame graphA chart where width is time and stacked boxes are the call stack
Self timeTime in a function itself, not in the functions it calls
Total timeSelf time plus the time of everything it calls
Hot spotA small part of the code that uses a large part of the time
Wall-clock timeReal elapsed time, including waiting
CPU timeTime actually running on a processor
Heap profileA snapshot of what objects hold memory
Allocation profileWhich code creates objects, and how many
ContentionThreads waiting for each other, usually on a lock
Continuous profilingCollecting low-overhead profiles all the time in production
Amdahlโ€™s lawThe limit on overall speedup when you improve only part of a task

09Pros, Cons and Trade-offs

โœ… Pros
  • Points at the real bottleneck
  • Saves guessing and wasted effort
  • Sampling is cheap and production-safe
  • Finds leaks and GC problems
  • Makes performance work measurable
โš ๏ธ Cons
  • Needs skill to read well
  • Sampling can miss very short functions
  • Instrumenting adds overhead and distortion
  • A profile of the wrong workload misleads
  • Does not show cross-service delays (use tracing)

Trade-offs

ChoiceWe gainWe lose
Higher sample rateMore detailMore overhead
Always-on profilingHistory to look back atStorage and a little CPU
Profile in stagingSafe and easyMay not match production
Profile in productionReal behaviourNeeds care for overhead and privacy
Optimise earlyFast from the startComplex code for gains you may not need

10Common Problems and Mistakes

Common mistakes

  1. Optimising by guessing. The slow part is rarely where you expect.
  2. Optimising a narrow frame. Amdahl's law caps the gain at the size of that frame.
  3. Profiling the wrong thing. A CPU profile of a service that is waiting on a database shows almost nothing. Use a wall-clock profile.
  4. Reading the x-axis as time. A flame graph is sorted by name, not by when things happened.
  5. Averages only. The tail (p99) often has a different cause from the average.
  6. No second measurement. A change that feels faster may not be.
  7. Leaving an instrumenting profiler on. It slows the very thing you are measuring.

Things to watch

๐Ÿ”’Sensitive data
Heap dumps can contain passwords and personal data. Treat them like secrets.
๐Ÿ”ฅCold vs warm
The first requests are slower (class loading, JIT, empty caches). Profile when warm too.
๐Ÿ“ˆTail latency
Rare pauses (GC, lock waits) hurt p99 and may be invisible in an average profile.
๐ŸงชNoisy neighbours
A shared machine can distort results. Repeat the run.

11Real-World Examples

๐Ÿ”Google-wide profiling
Google has described always-on, fleet-wide profiling to find savings in shared libraries.
๐Ÿ”ฅFlame graphs
Invented by Brendan Gregg to read huge stack traces quickly. Now in nearly every profiler.
๐ŸนGo pprof
Built into the Go ecosystem, and many services expose a profiling endpoint.
โ˜•JVM tooling
Flight Recorder and async-profiler show CPU, allocation and lock profiles of running Java services.
๐ŸeBPF profilers
Profile every process on a Linux host with low overhead, without changing the code.
๐ŸงฑBrowser DevTools
The Performance tab is a profiler for front-end code.
Mini case: a slow page
๐Ÿ“ŠMetricsp99 doubled
โ†’โ†“which service?
๐ŸงญTracetime is in the orders service
โ†’โ†“which code?
๐Ÿ”ฅProfileformatDates is 20% of CPU
A trace points to one service. The profile points to one function in it.

12Related Topics to Read Next

Metrics and Instrumentationโ†’

Metrics tell you something is slow, a profile tells you why.

Distributed Tracingโ†’

Finds the slow service, then profiling finds the slow code.

Three Pillars of Observabilityโ†’

Where profiling fits beside logs, metrics and traces.

Capacity Planningโ†’

Profiles show how many requests a server can handle.

Latency vs Throughput vs Bandwidthโ†’

Tail latency and why averages hide it.

Incident Management and Postmortemsโ†’

Profiles are often the evidence in a performance incident.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”Profile: where does the time or memory go, per function.
  • โœ”Sampling: cheap, production-safe. Instrumenting: exact but heavy.
  • โœ”Flame graph: width = time, not a timeline. Look for wide plateaus.
  • โœ”Kinds: CPU, wall-clock, heap, allocations, locks, I/O, GC.
  • โœ”Amdahl: speedup = 1 รท ((1 โˆ’ s) + s รท k). Narrow frames give tiny gains.
  • โœ”Process: symptom, profile, change one thing, measure again.
  • โœ”With tracing: trace finds the service, profile finds the code.
  • โœ”One line: โ€œDo not guess where it is slow. Look, then fix the widest bar.โ€
โ† Previous
Incident Management and Postmortems
Next โ†’
Audit Logs