Performance Testing
Performance Testing Types
Load Testing
Purpose: Verify system performance under expected load
- Simulates expected user traffic and data volume
- Identifies performance bottlenecks under normal conditions
- Establishes performance baselines
- Validates SLA compliance
Key Metrics:
- Response time (average, median, p95, p99)
- Throughput (requests per second, transactions per second)
- Error rate
- Resource utilization (CPU, memory, disk, network)
Stress Testing
Purpose: Identify system breaking points
- Exceeds expected load to find limits
- Tests system recovery after failure
- Identifies failure modes and error handling
- Validates graceful degradation
Key Metrics:
- Maximum concurrent users before failure
- Maximum throughput before failure
- Time to recover after load reduction
- Error patterns and failure modes
Spike Testing
Purpose: Handle sudden traffic increases
- Simulates sudden traffic spikes (e.g., flash sales, viral content)
- Tests system elasticity and auto-scaling
- Validates queuing and throttling mechanisms
- Identifies race conditions under load
Key Metrics:
- Response time during spike
- Error rate during spike
- Time to stabilize after spike
- Queue depth and processing time
Soak Testing
Purpose: Verify stability over extended periods
- Runs sustained load for hours or days
- Identifies memory leaks and resource exhaustion
- Tests database connection pool stability
- Validates garbage collection efficiency
Key Metrics:
- Memory usage over time
- Response time trends
- Error rate over time
- Resource utilization trends
Volume Testing
Purpose: Test with large data volumes
- Tests performance with realistic data sizes
- Identifies database query performance issues
- Tests file system and storage performance
- Validates data migration performance
Key Metrics:
- Query execution time with large datasets
- Index usage and effectiveness
- Storage I/O performance
- Data processing throughput
Performance Testing Tools
JMeter
Best for: Load and stress testing
- Open source, Java-based
- Supports multiple protocols (HTTP, JDBC, JMS, etc.)
- Distributed testing support
- Extensive plugin ecosystem
- GUI and CLI modes
<!-- JMeter Test Plan Example -->
<?xml version="1.0" encoding="UTF-8"?>
<jmeterTestPlan>
<hashTree>
<TestPlan guiclass="TestPlanGui">
<stringProp name="TestPlan.comments">Load Test</stringProp>
</TestPlan>
<hashTree>
<ThreadGroup guiclass="ThreadGroupGui">
<stringProp name="ThreadGroup.num_threads">100</stringProp>
<stringProp name="ThreadGroup.ramp_time">10</stringProp>
<stringProp name="ThreadGroup.duration">60</stringProp>
</ThreadGroup>
<hashTree>
<HTTPSamplerProxy guiclass="HttpTestSampleGui">
<stringProp name="HTTPSampler.domain">example.com</stringProp>
<stringProp name="HTTPSampler.path">/api/users</stringProp>
</HTTPSamplerProxy>
</hashTree>
</hashTree>
</hashTree>
</jmeterTestPlan>
Gatling
Best for: High-performance load testing
- Scala-based, DSL for test scenarios
- High performance, low resource usage
- Real-time metrics and reporting
- Good for continuous integration
- Supports HTTP, WebSocket, JMS
// Gatling Example
import io.gatling.core.Predef._
import io.gatling.http.Predef._
class LoadTest extends Simulation {
val httpProtocol = http.baseUrl("https://example.com")
val scn = scenario("User Journey")
.exec(http("Get Users").get("/api/users"))
.pause(1)
.exec(http("Get User").get("/api/users/1"))
setUp(
scn.inject(
rampUsers(100).during(10.seconds),
constantUsersPerSec(50).during(60.seconds)
)
).protocols(httpProtocol)
}
k6
Best for: Developer-friendly performance testing
- JavaScript-based, easy to learn
- Modern CLI and cloud integration
- Good for CI/CD pipelines
- Supports HTTP/1.1, HTTP/2, WebSocket
- Grafana integration for visualization
// k6 Example
import http from 'k6/http';
import { check, sleep } from 'k6';
export let options = {
stages: [
{ duration: '10s', target: 100 },
{ duration: '60s', target: 100 },
{ duration: '10s', target: 0 },
],
};
export default function () {
let res = http.get('https://example.com/api/users');
check(res, {
'status was 200': (r) => r.status == 200,
'response time < 500ms': (r) => r.timings.duration < 500,
});
sleep(1);
}
Locust
Best for: Python-based load testing
- Python-based, easy to write tests
- Web UI for real-time monitoring
- Distributed testing support
- Good for complex user scenarios
- Event-based architecture
# Locust Example
from locust import HttpUser, task, between
class WebsiteUser(HttpUser):
wait_time = between(1, 3)
@task
def get_users(self):
self.client.get("/api/users")
@task(2)
def get_user(self):
self.client.get("/api/users/1")
Key Performance Metrics
Response Time
- Average: Mean response time across all requests
- Median: Middle value, less affected by outliers
- p95: 95th percentile, 95% of requests complete within this time
- p99: 99th percentile, 99% of requests complete within this time
- Min/Max: Fastest and slowest response times
Throughput
- Requests Per Second (RPS): Number of requests handled per second
- Transactions Per Second (TPS): Number of business transactions per second
- Concurrent Users: Number of simultaneous users
- Hits Per Second: Number of HTTP requests per second
Error Rate
- HTTP Error Rate: Percentage of HTTP errors (4xx, 5xx)
- Application Error Rate: Percentage of application-level errors
- Timeout Rate: Percentage of requests that timed out
- Connection Error Rate: Percentage of connection failures
Resource Utilization
- CPU Usage: Processor utilization percentage
- Memory Usage: RAM consumption and availability
- Disk I/O: Read/write operations and latency
- Network I/O: Bandwidth utilization and latency
- Database Connections: Active and idle connection counts
Performance Profiling
Application Profiling
- CPU Profiling: Identify CPU-intensive methods
- Memory Profiling: Detect memory leaks and allocation patterns
- Thread Profiling: Identify thread contention and deadlocks
- Database Profiling: Analyze query performance and execution plans
Tools
- Java: JProfiler, VisualVM, YourKit
- Node.js: Node.js Profiler, Clinic.js
- Python: cProfile, Py-Spy
- Go: pprof
- .NET: dotTrace, Visual Studio Profiler
Bottleneck Identification
- Database: Slow queries, missing indexes, N+1 queries
- Network: Latency, bandwidth limitations, connection pooling
- Application: Inefficient algorithms, excessive object creation
- External Services: Third-party API latency, rate limiting
- Caching: Cache misses, stale data, cache stampede
Performance Baselines and SLAs
Establishing Baselines
- Run tests in production-like environment
- Collect metrics over multiple runs
- Account for normal variability
- Document test conditions and data
- Store baselines in version control
SLA Definitions
- Response Time SLAs: Maximum acceptable response times
- Availability SLAs: Minimum uptime requirements (e.g., 99.9%)
- Throughput SLAs: Minimum requests per second
- Error Rate SLAs: Maximum acceptable error rate
Example SLAs
API Response Times:
- p50 < 200ms
- p95 < 500ms
- p99 < 1000ms
Availability: 99.9% (8.76 hours downtime/year)
Error Rate: < 0.1%
Throughput: 1000 RPS
Cloud-Based Performance Testing
Cloud Testing Benefits
- Scalable infrastructure on demand
- Geographic distribution
- Realistic load simulation
- Pay-as-you-go pricing
- Integration with cloud services
Cloud Testing Platforms
- AWS: EC2, Lambda, Fargate for distributed testing
- Google Cloud: Compute Engine, Cloud Functions
- Azure: Virtual Machines, Azure Functions
- Managed Services: BlazeMeter, LoadRunner Cloud, k6 Cloud
Cloud Testing Best Practices
- Use multiple regions for geographic testing
- Leverage auto-scaling for flexible load
- Monitor cloud costs during testing
- Clean up resources after testing
- Use cloud-native monitoring and logging
Performance Test Planning
Test Scenarios
- Define realistic user journeys
- Identify critical paths
- Include happy path and edge cases
- Account for different user types
- Consider peak and off-peak patterns
Load Models
- Constant Load: Steady user count over time
- Ramp-up Load: Gradually increase users
- Spike Load: Sudden increase in users
- Step Load: Incremental increases with plateaus
- Random Load: Variable user patterns
Test Data
- Use realistic data volumes
- Include edge cases and boundary values
- Account for data distribution
- Refresh data between test runs
- Consider data privacy and security
Environment Setup
- Mirror production configuration
- Use production-like data
- Monitor system resources
- Isolate test environment
- Document environment differences
1---2name: performance-testing3description: Performance testing methodologies, tools, and metrics4---5
6# Performance Testing
7
8## Performance Testing Types
9
10### Load Testing
11**Purpose**: Verify system performance under expected load
12- Simulates expected user traffic and data volume
13- Identifies performance bottlenecks under normal conditions
14- Establishes performance baselines
15- Validates SLA compliance
16
17**Key Metrics**:
18- Response time (average, median, p95, p99)
19- Throughput (requests per second, transactions per second)
20- Error rate
21- Resource utilization (CPU, memory, disk, network)
22
23### Stress Testing
24**Purpose**: Identify system breaking points
25- Exceeds expected load to find limits
26- Tests system recovery after failure
27- Identifies failure modes and error handling
28- Validates graceful degradation
29
30**Key Metrics**:
31- Maximum concurrent users before failure
32- Maximum throughput before failure
33- Time to recover after load reduction
34- Error patterns and failure modes
35
36### Spike Testing
37**Purpose**: Handle sudden traffic increases
38- Simulates sudden traffic spikes (e.g., flash sales, viral content)
39- Tests system elasticity and auto-scaling
40- Validates queuing and throttling mechanisms
41- Identifies race conditions under load
42
43**Key Metrics**:
44- Response time during spike
45- Error rate during spike
46- Time to stabilize after spike
47- Queue depth and processing time
48
49### Soak Testing
50**Purpose**: Verify stability over extended periods
51- Runs sustained load for hours or days
52- Identifies memory leaks and resource exhaustion
53- Tests database connection pool stability
54- Validates garbage collection efficiency
55
56**Key Metrics**:
57- Memory usage over time
58- Response time trends
59- Error rate over time
60- Resource utilization trends
61
62### Volume Testing
63**Purpose**: Test with large data volumes
64- Tests performance with realistic data sizes
65- Identifies database query performance issues
66- Tests file system and storage performance
67- Validates data migration performance
68
69**Key Metrics**:
70- Query execution time with large datasets
71- Index usage and effectiveness
72- Storage I/O performance
73- Data processing throughput
74
75## Performance Testing Tools
76
77### JMeter
78**Best for**: Load and stress testing
79- Open source, Java-based
80- Supports multiple protocols (HTTP, JDBC, JMS, etc.)
81- Distributed testing support
82- Extensive plugin ecosystem
83- GUI and CLI modes
84
85```xml
86<!-- JMeter Test Plan Example -->
87<?xml version="1.0" encoding="UTF-8"?>
88<jmeterTestPlan>
89 <hashTree>
90 <TestPlan guiclass="TestPlanGui">
91 <stringProp name="TestPlan.comments">Load Test</stringProp>
92 </TestPlan>
93 <hashTree>
94 <ThreadGroup guiclass="ThreadGroupGui">
95 <stringProp name="ThreadGroup.num_threads">100</stringProp>
96 <stringProp name="ThreadGroup.ramp_time">10</stringProp>
97 <stringProp name="ThreadGroup.duration">60</stringProp>
98 </ThreadGroup>
99 <hashTree>
100 <HTTPSamplerProxy guiclass="HttpTestSampleGui">
101 <stringProp name="HTTPSampler.domain">example.com</stringProp>
102 <stringProp name="HTTPSampler.path">/api/users</stringProp>
103 </HTTPSamplerProxy>
104 </hashTree>
105 </hashTree>
106 </hashTree>
107</jmeterTestPlan>
108```
109
110### Gatling
111**Best for**: High-performance load testing
112- Scala-based, DSL for test scenarios
113- High performance, low resource usage
114- Real-time metrics and reporting
115- Good for continuous integration
116- Supports HTTP, WebSocket, JMS
117
118```scala
119// Gatling Example
120import io.gatling.core.Predef._
121import io.gatling.http.Predef._
122
123class LoadTest extends Simulation {
124 val httpProtocol = http.baseUrl("https://example.com")
125
126 val scn = scenario("User Journey")
127 .exec(http("Get Users").get("/api/users"))
128 .pause(1)
129 .exec(http("Get User").get("/api/users/1"))
130
131 setUp(
132 scn.inject(
133 rampUsers(100).during(10.seconds),
134 constantUsersPerSec(50).during(60.seconds)
135 )
136 ).protocols(httpProtocol)
137}
138```
139
140### k6
141**Best for**: Developer-friendly performance testing
142- JavaScript-based, easy to learn
143- Modern CLI and cloud integration
144- Good for CI/CD pipelines
145- Supports HTTP/1.1, HTTP/2, WebSocket
146- Grafana integration for visualization
147
148```javascript
149// k6 Example
150import http from 'k6/http';
151import { check, sleep } from 'k6';
152
153export let options = {
154 stages: [
155 { duration: '10s', target: 100 },
156 { duration: '60s', target: 100 },
157 { duration: '10s', target: 0 },
158 ],
159};
160
161export default function () {
162 let res = http.get('https://example.com/api/users');
163 check(res, {
164 'status was 200': (r) => r.status == 200,
165 'response time < 500ms': (r) => r.timings.duration < 500,
166 });
167 sleep(1);
168}
169```
170
171### Locust
172**Best for**: Python-based load testing
173- Python-based, easy to write tests
174- Web UI for real-time monitoring
175- Distributed testing support
176- Good for complex user scenarios
177- Event-based architecture
178
179```python
180# Locust Example
181from locust import HttpUser, task, between
182
183class WebsiteUser(HttpUser):
184 wait_time = between(1, 3)
185
186 @task
187 def get_users(self):
188 self.client.get("/api/users")
189
190 @task(2)
191 def get_user(self):
192 self.client.get("/api/users/1")
193```
194
195## Key Performance Metrics
196
197### Response Time
198- **Average**: Mean response time across all requests
199- **Median**: Middle value, less affected by outliers
200- **p95**: 95th percentile, 95% of requests complete within this time
201- **p99**: 99th percentile, 99% of requests complete within this time
202- **Min/Max**: Fastest and slowest response times
203
204### Throughput
205- **Requests Per Second (RPS)**: Number of requests handled per second
206- **Transactions Per Second (TPS)**: Number of business transactions per second
207- **Concurrent Users**: Number of simultaneous users
208- **Hits Per Second**: Number of HTTP requests per second
209
210### Error Rate
211- **HTTP Error Rate**: Percentage of HTTP errors (4xx, 5xx)
212- **Application Error Rate**: Percentage of application-level errors
213- **Timeout Rate**: Percentage of requests that timed out
214- **Connection Error Rate**: Percentage of connection failures
215
216### Resource Utilization
217- **CPU Usage**: Processor utilization percentage
218- **Memory Usage**: RAM consumption and availability
219- **Disk I/O**: Read/write operations and latency
220- **Network I/O**: Bandwidth utilization and latency
221- **Database Connections**: Active and idle connection counts
222
223## Performance Profiling
224
225### Application Profiling
226- **CPU Profiling**: Identify CPU-intensive methods
227- **Memory Profiling**: Detect memory leaks and allocation patterns
228- **Thread Profiling**: Identify thread contention and deadlocks
229- **Database Profiling**: Analyze query performance and execution plans
230
231### Tools
232- **Java**: JProfiler, VisualVM, YourKit
233- **Node.js**: Node.js Profiler, Clinic.js
234- **Python**: cProfile, Py-Spy
235- **Go**: pprof
236- **.NET**: dotTrace, Visual Studio Profiler
237
238### Bottleneck Identification
2391. **Database**: Slow queries, missing indexes, N+1 queries
2402. **Network**: Latency, bandwidth limitations, connection pooling
2413. **Application**: Inefficient algorithms, excessive object creation
2424. **External Services**: Third-party API latency, rate limiting
2435. **Caching**: Cache misses, stale data, cache stampede
244
245## Performance Baselines and SLAs
246
247### Establishing Baselines
248- Run tests in production-like environment
249- Collect metrics over multiple runs
250- Account for normal variability
251- Document test conditions and data
252- Store baselines in version control
253
254### SLA Definitions
255- **Response Time SLAs**: Maximum acceptable response times
256- **Availability SLAs**: Minimum uptime requirements (e.g., 99.9%)
257- **Throughput SLAs**: Minimum requests per second
258- **Error Rate SLAs**: Maximum acceptable error rate
259
260### Example SLAs
261```
262API Response Times:
263- p50 < 200ms
264- p95 < 500ms
265- p99 < 1000ms
266
267Availability: 99.9% (8.76 hours downtime/year)
268
269Error Rate: < 0.1%
270
271Throughput: 1000 RPS
272```
273
274## Cloud-Based Performance Testing
275
276### Cloud Testing Benefits
277- Scalable infrastructure on demand
278- Geographic distribution
279- Realistic load simulation
280- Pay-as-you-go pricing
281- Integration with cloud services
282
283### Cloud Testing Platforms
284- **AWS**: EC2, Lambda, Fargate for distributed testing
285- **Google Cloud**: Compute Engine, Cloud Functions
286- **Azure**: Virtual Machines, Azure Functions
287- **Managed Services**: BlazeMeter, LoadRunner Cloud, k6 Cloud
288
289### Cloud Testing Best Practices
290- Use multiple regions for geographic testing
291- Leverage auto-scaling for flexible load
292- Monitor cloud costs during testing
293- Clean up resources after testing
294- Use cloud-native monitoring and logging
295
296## Performance Test Planning
297
298### Test Scenarios
299- Define realistic user journeys
300- Identify critical paths
301- Include happy path and edge cases
302- Account for different user types
303- Consider peak and off-peak patterns
304
305### Load Models
306- **Constant Load**: Steady user count over time
307- **Ramp-up Load**: Gradually increase users
308- **Spike Load**: Sudden increase in users
309- **Step Load**: Incremental increases with plateaus
310- **Random Load**: Variable user patterns
311
312### Test Data
313- Use realistic data volumes
314- Include edge cases and boundary values
315- Account for data distribution
316- Refresh data between test runs
317- Consider data privacy and security
318
319### Environment Setup
320- Mirror production configuration
321- Use production-like data
322- Monitor system resources
323- Isolate test environment
324- Document environment differences