Performance Profiling
When to Use
- Establishing performance baselines before optimization
- Diagnosing slow response times, high CPU, or memory issues
- Identifying bottlenecks in application, database, or infrastructure
- Planning capacity for expected load increases
- Validating performance improvements after optimization
- Creating performance budgets for new features
Core Methodology
The Golden Rule: Measure First
Never optimize based on assumptions. Follow this order:
- Measure - Establish baseline metrics
- Identify - Find the actual bottleneck
- Hypothesize - Form a theory about the cause
- Fix - Implement targeted optimization
- Validate - Measure again to confirm improvement
- Document - Record findings and decisions
Profiling Hierarchy
Profile at the right level to find the actual bottleneck:
Application Level
|-- Request/Response timing
|-- Function/Method profiling
|-- Memory allocation tracking
|
System Level
|-- CPU utilization per process
|-- Memory usage patterns
|-- I/O wait times
|-- Network latency
|
Infrastructure Level
|-- Database query performance
|-- Cache hit rates
|-- External service latency
|-- Resource saturation
Profiling Patterns
CPU Profiling
Identify what code consumes CPU time:
- Sampling profilers - Low overhead, statistical accuracy
- Instrumentation profilers - Exact counts, higher overhead
- Flame graphs - Visual representation of call stacks
Key metrics:
- Self time (time in function itself)
- Total time (self time + time in called functions)
- Call count and frequency
Memory Profiling
Track allocation patterns and detect leaks:
- Heap snapshots - Point-in-time memory state
- Allocation tracking - What allocates memory and when
- Garbage collection analysis - GC frequency and duration
Key metrics:
- Heap size over time
- Object retention
- Allocation rate
- GC pause times
I/O Profiling
Measure disk and network operations:
- Disk I/O - Read/write latency, throughput, IOPS
- Network I/O - Latency, bandwidth, connection count
- Database I/O - Query time, connection pool usage
Key metrics:
- Latency percentiles (p50, p95, p99)
- Throughput (ops/sec, MB/sec)
- Queue depth and wait times
Bottleneck Identification
The USE Method
For each resource, check:
- Utilization - Percentage of time resource is busy
- Saturation - Degree of queued work
- Errors - Error count for the resource
The RED Method
For services, measure:
- Rate - Requests per second
- Errors - Failed requests per second
- Duration - Distribution of request latencies
Common Bottleneck Patterns
| Pattern |
Symptoms |
Typical Causes |
| CPU-bound |
High CPU, low I/O wait |
Inefficient algorithms, tight loops |
| Memory-bound |
High memory, GC pressure |
Memory leaks, large allocations |
| I/O-bound |
Low CPU, high I/O wait |
Slow queries, network latency |
| Lock contention |
Low CPU, high wait time |
Synchronization, connection pools |
| N+1 queries |
Many small DB queries |
Missing joins, lazy loading |
Amdahl's Law
Optimization impact is limited by the fraction of time affected:
If 90% of time is in function A and 10% in function B:
- Optimizing A by 50% = 45% total improvement
- Optimizing B by 50% = 5% total improvement
Focus on the biggest contributors first.
Capacity Planning
Baseline Establishment
Measure current capacity under production load:
- Peak load metrics - Maximum concurrent users, requests/sec
- Resource headroom - How close to limits at peak
- Scaling patterns - Linear, sub-linear, or super-linear
Load Testing Approach
- Establish baseline - Current performance at normal load
- Ramp testing - Gradually increase load to find limits
- Stress testing - Push beyond limits to understand failure modes
- Soak testing - Sustained load to find memory leaks, degradation
Capacity Metrics
| Metric |
What It Tells You |
| Throughput at saturation |
Maximum system capacity |
| Latency at 80% load |
Performance before degradation |
| Error rate under stress |
Failure patterns |
| Recovery time |
How quickly system returns to normal |
Growth Planning
Required Capacity = (Current Load x Growth Factor) + Safety Margin
Example:
- Current: 1000 req/sec
- Expected growth: 50% per year
- Safety margin: 30%
Year 1 need = (1000 x 1.5) x 1.3 = 1950 req/sec
Optimization Patterns
Quick Wins
- Enable caching - Application, CDN, database query cache
- Add indexes - For slow queries identified in profiling
- Compression - Gzip/Brotli for responses
- Connection pooling - Reduce connection overhead
- Batch operations - Reduce round-trips
Algorithmic Improvements
- Reduce complexity - O(n^2) to O(n log n)
- Lazy evaluation - Defer work until needed
- Memoization - Cache computed results
- Pagination - Limit data processed at once
Architectural Changes
- Horizontal scaling - Add more instances
- Async processing - Queue background work
- Read replicas - Distribute read load
- Caching layers - Redis, Memcached
- CDN - Edge caching for static content
Best Practices
- Profile in production-like environments; development can have different characteristics
- Use percentiles (p95, p99) not averages for latency
- Monitor continuously, not just during incidents
- Set performance budgets and enforce them in CI
- Document baseline metrics before making changes
- Keep profiling overhead low in production
- Correlate metrics across layers (application, database, infrastructure)
- Understand the difference between latency and throughput
Anti-Patterns
- Optimizing without measurement
- Using averages for latency metrics
- Profiling only in development
- Ignoring tail latencies (p99, p999)
- Premature optimization of non-bottleneck code
- Over-engineering for hypothetical scale
- Caching without invalidation strategy
References
- Profiling Tools Reference - Tools by language and platform
1---2name: performance-analysis3description: Measurement approaches, profiling tools, optimization patterns, and capacity planning. Use when diagnosing performance issues, establishing baselines, identifying bottlenecks, or planning for scale. Always measure before optimizing.4---5
6# Performance Profiling
7
8## When to Use
9
10- Establishing performance baselines before optimization
11- Diagnosing slow response times, high CPU, or memory issues
12- Identifying bottlenecks in application, database, or infrastructure
13- Planning capacity for expected load increases
14- Validating performance improvements after optimization
15- Creating performance budgets for new features
16
17## Core Methodology
18
19### The Golden Rule: Measure First
20
21Never optimize based on assumptions. Follow this order:
22
231. **Measure** - Establish baseline metrics
242. **Identify** - Find the actual bottleneck
253. **Hypothesize** - Form a theory about the cause
264. **Fix** - Implement targeted optimization
275. **Validate** - Measure again to confirm improvement
286. **Document** - Record findings and decisions
29
30### Profiling Hierarchy
31
32Profile at the right level to find the actual bottleneck:
33
34```
35Application Level
36 |-- Request/Response timing
37 |-- Function/Method profiling
38 |-- Memory allocation tracking
39 |
40System Level
41 |-- CPU utilization per process
42 |-- Memory usage patterns
43 |-- I/O wait times
44 |-- Network latency
45 |
46Infrastructure Level
47 |-- Database query performance
48 |-- Cache hit rates
49 |-- External service latency
50 |-- Resource saturation
51```
52
53## Profiling Patterns
54
55### CPU Profiling
56
57Identify what code consumes CPU time:
58
591. **Sampling profilers** - Low overhead, statistical accuracy
602. **Instrumentation profilers** - Exact counts, higher overhead
613. **Flame graphs** - Visual representation of call stacks
62
63Key metrics:
64- Self time (time in function itself)
65- Total time (self time + time in called functions)
66- Call count and frequency
67
68### Memory Profiling
69
70Track allocation patterns and detect leaks:
71
721. **Heap snapshots** - Point-in-time memory state
732. **Allocation tracking** - What allocates memory and when
743. **Garbage collection analysis** - GC frequency and duration
75
76Key metrics:
77- Heap size over time
78- Object retention
79- Allocation rate
80- GC pause times
81
82### I/O Profiling
83
84Measure disk and network operations:
85
861. **Disk I/O** - Read/write latency, throughput, IOPS
872. **Network I/O** - Latency, bandwidth, connection count
883. **Database I/O** - Query time, connection pool usage
89
90Key metrics:
91- Latency percentiles (p50, p95, p99)
92- Throughput (ops/sec, MB/sec)
93- Queue depth and wait times
94
95## Bottleneck Identification
96
97### The USE Method
98
99For each resource, check:
100- **U**tilization - Percentage of time resource is busy
101- **S**aturation - Degree of queued work
102- **E**rrors - Error count for the resource
103
104### The RED Method
105
106For services, measure:
107- **R**ate - Requests per second
108- **E**rrors - Failed requests per second
109- **D**uration - Distribution of request latencies
110
111### Common Bottleneck Patterns
112
113| Pattern | Symptoms | Typical Causes |
114|---------|----------|----------------|
115| CPU-bound | High CPU, low I/O wait | Inefficient algorithms, tight loops |
116| Memory-bound | High memory, GC pressure | Memory leaks, large allocations |
117| I/O-bound | Low CPU, high I/O wait | Slow queries, network latency |
118| Lock contention | Low CPU, high wait time | Synchronization, connection pools |
119| N+1 queries | Many small DB queries | Missing joins, lazy loading |
120
121### Amdahl's Law
122
123Optimization impact is limited by the fraction of time affected:
124
125```
126If 90% of time is in function A and 10% in function B:
127- Optimizing A by 50% = 45% total improvement
128- Optimizing B by 50% = 5% total improvement
129```
130
131Focus on the biggest contributors first.
132
133## Capacity Planning
134
135### Baseline Establishment
136
137Measure current capacity under production load:
138
1391. **Peak load metrics** - Maximum concurrent users, requests/sec
1402. **Resource headroom** - How close to limits at peak
1413. **Scaling patterns** - Linear, sub-linear, or super-linear
142
143### Load Testing Approach
144
1451. **Establish baseline** - Current performance at normal load
1462. **Ramp testing** - Gradually increase load to find limits
1473. **Stress testing** - Push beyond limits to understand failure modes
1484. **Soak testing** - Sustained load to find memory leaks, degradation
149
150### Capacity Metrics
151
152| Metric | What It Tells You |
153|--------|-------------------|
154| Throughput at saturation | Maximum system capacity |
155| Latency at 80% load | Performance before degradation |
156| Error rate under stress | Failure patterns |
157| Recovery time | How quickly system returns to normal |
158
159### Growth Planning
160
161```
162Required Capacity = (Current Load x Growth Factor) + Safety Margin
163
164Example:
165- Current: 1000 req/sec
166- Expected growth: 50% per year
167- Safety margin: 30%
168
169Year 1 need = (1000 x 1.5) x 1.3 = 1950 req/sec
170```
171
172## Optimization Patterns
173
174### Quick Wins
175
1761. **Enable caching** - Application, CDN, database query cache
1772. **Add indexes** - For slow queries identified in profiling
1783. **Compression** - Gzip/Brotli for responses
1794. **Connection pooling** - Reduce connection overhead
1805. **Batch operations** - Reduce round-trips
181
182### Algorithmic Improvements
183
1841. **Reduce complexity** - O(n^2) to O(n log n)
1852. **Lazy evaluation** - Defer work until needed
1863. **Memoization** - Cache computed results
1874. **Pagination** - Limit data processed at once
188
189### Architectural Changes
190
1911. **Horizontal scaling** - Add more instances
1922. **Async processing** - Queue background work
1933. **Read replicas** - Distribute read load
1944. **Caching layers** - Redis, Memcached
1955. **CDN** - Edge caching for static content
196
197## Best Practices
198
199- Profile in production-like environments; development can have different characteristics
200- Use percentiles (p95, p99) not averages for latency
201- Monitor continuously, not just during incidents
202- Set performance budgets and enforce them in CI
203- Document baseline metrics before making changes
204- Keep profiling overhead low in production
205- Correlate metrics across layers (application, database, infrastructure)
206- Understand the difference between latency and throughput
207
208## Anti-Patterns
209
210- Optimizing without measurement
211- Using averages for latency metrics
212- Profiling only in development
213- Ignoring tail latencies (p99, p999)
214- Premature optimization of non-bottleneck code
215- Over-engineering for hypothetical scale
216- Caching without invalidation strategy
217
218## References
219
220- [Profiling Tools Reference](references/profiling-tools.md) - Tools by language and platform