Performance Testing
Performance testing evaluates how quickly, reliably and efficiently an application behaves under defined conditions.
Create a realistic workload
|
v
Measure user and system behavior
|
v
Find the limiting resource or slow path
|
v
Improve and test again
One-line idea: Performance testing replaces "the app feels slow" with a repeatable workload, measurable targets and evidence showing where time and resources are spent.
Core Concepts
What Performance Testing Measures
Performance is not one number. A useful test considers:
- how quickly users see useful content
- how quickly the interface responds to input
- how stable the page remains while loading
- how long APIs take at normal and peak traffic
- how much traffic the system completes
- how often requests fail
- how CPU, memory, network and storage behave
- whether performance degrades over time
- how the system recovers after pressure is removed
Performance vs Functional Correctness
Functional testing asks whether the result is correct.
Does checkout create an order? -> functional correctness
Performance testing asks whether the correct result arrives within acceptable limits under a defined workload.
Can checkout create orders within the latency target
while 2,000 users are active? -> performance behavior
Both are required. A fast incorrect response and a correct unusably slow response are both failures.
Performance Is End-to-End
The delay users experience can come from many layers:
Browser work
|
Network and CDN
|
Load balancer and API
|
Application services
|
Cache and database
|
External dependencies
Optimizing one layer may not improve the complete journey if another layer remains the bottleneck.
Types of Performance Testing
Load Testing
Load testing checks behavior under expected normal and peak traffic.
Expected peak: 1,000 requests per second
Test: hold approximately that load for a planned duration
Observe: latency, throughput, errors and resource usage
Use it to confirm that capacity and service-level targets are met.
Stress Testing
Stress testing increases pressure beyond expected capacity to find the breaking point and observe failure behavior.
Increase load
|
v
Target is met
|
v
Performance degrades
|
v
Errors or saturation appear
A good stress test also verifies recovery after load returns to normal.
Spike Testing
Spike testing applies a sudden traffic increase or decrease.
It helps evaluate:
- autoscaling delay
- queue growth
- cache misses
- connection exhaustion
- rate limiting
- recovery from a burst
Examples include ticket sales, flash promotions and breaking-news traffic.
Soak or Endurance Testing
Soak testing holds a realistic workload for a long period.
It can reveal:
- memory leaks
- unreleased connections
- growing queues
- log or disk accumulation
- cache behavior changes
- scheduled-job interference
A system may pass a ten-minute load test but degrade after several hours.
Scalability Testing
Scalability testing measures how performance changes as traffic and resources change.
Double service instances
|
v
Does useful throughput increase?
Does latency remain stable?
Does another dependency become the bottleneck?
Scaling is efficient only while additional resources produce useful capacity.
Volume Testing
Volume testing focuses on large amounts of stored or transferred data.
Examples:
- search over millions of records
- reports over years of history
- very large uploads
- tables with deep pagination
- databases near expected production size
Frontend Performance Testing
Frontend performance testing measures loading, rendering, interaction and visual stability in the browser.
It uses tools such as Chrome DevTools, Lighthouse, PageSpeed Insights and WebPageTest alongside real-user monitoring.
Performance Metrics
Latency
Latency is the time required to complete an operation.
An average alone can hide slow users. Report percentiles:
| Percentile | Meaning |
|---|---|
| p50 | Half of observations are at or below this value |
| p95 | 95% of observations are at or below this value |
| p99 | 99% of observations are at or below this value |
Example:
Average: 180 ms
p50: 120 ms
p95: 450 ms
p99: 1,200 ms
The average looks acceptable, but the tail shows that some users wait much longer.
Throughput
Throughput is the amount of completed work per unit of time.
Examples:
- requests per second
- orders per minute
- messages consumed per second
- megabytes transferred per second
Count successful useful work, not only attempted requests.
Error Rate
Error rate = failed operations / total operations
Separate error categories where possible:
- timeouts
- connection failures
- rate-limit responses
- server errors
- validation or expected client errors
An apparently fast test can be misleading if the system rejected much of the work.
Saturation
Saturation shows how close a resource is to its practical limit.
Monitor:
- CPU utilization and runnable tasks
- memory and garbage collection
- disk and network throughput
- database connections
- thread or worker pools
- queues and consumer lag
- file descriptors and sockets
High utilization is not automatically bad. The question is whether the resource is limiting throughput, increasing latency or causing errors.
Concurrency and Arrival Rate
Concurrency is the number of operations active at the same time. Arrival rate is how frequently new work enters the system.
They are related but not interchangeable. A slower system can accumulate more concurrent requests even when arrival rate stays constant.
Define which model the test tool uses so the workload matches real traffic.
Frontend User-Experience Metrics
Largest Contentful Paint
LCP measures when the largest relevant content element becomes visible in the viewport during loading.
A high LCP can be caused by:
- slow server response
- render-blocking resources
- large unoptimized images
- delayed client rendering
- slow fonts or styles
Interaction to Next Paint
INP measures responsiveness across user interactions by observing the delay until the browser can present the next visual update.
Common causes of poor responsiveness include:
- long JavaScript tasks
- expensive event handlers
- large synchronous renders
- repeated layout work
- overloaded third-party scripts
Cumulative Layout Shift
CLS measures unexpected visual movement.
Common causes include:
- images without reserved dimensions
- content inserted above existing content
- font swaps that change layout
- ads or embeds without stable containers
First Contentful Paint
FCP measures when the browser first renders visible content such as text, an image or canvas content.
FCP describes the beginning of visible rendering, while LCP focuses on the main loading experience.
Total Blocking Time
TBT is a lab metric that estimates how much main-thread blocking occurs between FCP and the point when the page becomes reliably interactive in the test.
TBT is useful for diagnosing JavaScript work in controlled runs. INP uses interaction observations and is the user-experience responsiveness metric to monitor in field data.
Speed Index
Speed Index estimates how quickly the visible page becomes visually complete during a recorded load.
Use it as supporting evidence rather than treating one score as the complete user experience.
Lab Data and Field Data
Lab Testing
Lab testing runs under controlled conditions.
Examples:
- Lighthouse
- a DevTools performance recording
- WebPageTest with a selected browser and network profile
- a load test in a staging environment
Strengths:
- repeatable
- detailed diagnostics
- useful before release
- easy to compare after a code change
Limitations:
- one device and network profile cannot represent every user
- test data and caches may differ from production
- synthetic flows may miss real behavior
Field Testing
Field data measures real user sessions across real devices, networks and locations.
Strengths:
- represents actual user conditions
- reveals device and regional differences
- shows long-term distributions
Limitations:
- slower feedback
- less controlled
- affected by release mix and traffic composition
- requires careful privacy and sampling design
Use both:
Lab data -> reproduce and diagnose
Field data -> validate real-user impact
Chrome DevTools Performance Panel
The Performance panel records browser activity while a page loads or a user interacts with it.
What It Captures
Depending on the recording and browser version, a trace can show:
- network activity
- JavaScript tasks and call stacks
- rendering and style calculation
- layout
- painting and compositing
- screenshots across the timeline
- memory behavior
- user timings and framework tracks
Timeline Overview
The overview shows activity over time. Dense or long blocks can indicate heavy work, but a spike alone is not a diagnosis.
Select the relevant time range and inspect what caused it.
Main Thread
The main thread performs much of the browser's JavaScript, style, layout and painting coordination.
Long synchronous task
|
v
Main thread cannot handle input promptly
|
v
Interaction feels delayed or frozen
A task longer than about 50 ms is commonly marked as a long task because it can block timely interaction work. The required fix depends on the task's actual call stack and user impact.
Bottom-Up and Call Tree Views
Use these views to find:
- functions consuming the most total time
- expensive call paths
- repeated work
- third-party code
- scripting, rendering and painting costs
Do not optimize a function only because it appears in the trace. Confirm that it contributes meaningfully to the user-facing delay.
Recording Workflow
- Open a clean browser profile or disable unrelated extensions.
- Select realistic CPU and network conditions if needed.
- Record a page load or interaction.
- reproduce the slow behavior.
- Stop recording and select the affected time range.
- Inspect long tasks, call stacks, rendering and network activity.
- form a bottleneck hypothesis.
- make one focused improvement.
- record again under the same conditions.
Consistent conditions make before-and-after comparisons meaningful.
Lighthouse
Lighthouse runs audits for areas such as performance, accessibility, best practices and SEO.
What the Report Provides
The performance report includes:
- measured lab metrics
- a performance score derived from selected metrics
- diagnostics
- opportunities for improvement
- a visual loading timeline
The score is useful as a summary, but it is not the product requirement by itself. Investigate the underlying metrics and user journeys.
Reliable Lighthouse Runs
Results can vary because of:
- CPU activity on the machine
- browser extensions
- stored data and caches
- network variability
- background processes
- page personalization
- test location
For useful comparisons:
- use a clean browser environment
- keep device and network settings consistent
- run several samples
- compare the median rather than one unusually good run
- document the page and application version
- separate cold-cache and warm-cache scenarios
Interpreting a Report
High TBT
-> inspect long JavaScript tasks and main-thread work
High LCP
-> inspect server response, resource priority and the LCP element
High CLS
-> inspect elements that move and reserve their space
Recommendations are starting points. Measure the effect after applying a change.
PageSpeed Insights and WebPageTest
PageSpeed Insights
PageSpeed Insights can combine available real-user field data with a Lighthouse lab analysis.
Keep these result types separate:
Field data -> aggregated real-user experience over time
Lab data -> one controlled diagnostic run
A page can pass one view and struggle in the other because they use different populations, time windows and conditions.
WebPageTest
WebPageTest supports detailed synthetic testing with selected locations, devices, connection profiles, repeat views and visual timelines.
It is useful for:
- waterfall analysis
- first-view versus repeat-view comparison
- filmstrips and visual progress
- regional testing
- connection and device simulation
Designing a Backend Load Test
1. Define the Goal
Write a specific question:
Can the checkout API sustain 300 completed orders per minute
for 30 minutes while p95 latency remains below the agreed target
and server-error rate remains within the error budget?
2. Model Real Traffic
Use production evidence to estimate:
- endpoint or journey mix
- request arrival pattern
- user think time
- payload sizes
- authentication behavior
- cache hit ratios
- read and write ratio
- geographic distribution
Sending one endpoint in a tight loop rarely represents the full application.
3. Prepare the Environment
The environment should be understood well enough to interpret results.
Document:
- service versions and configuration
- instance counts and resource limits
- database size and indexes
- cache state
- test data
- external-service behavior
- network topology
A smaller staging environment can still provide useful evidence, but its results must not be presented as direct production capacity without a scaling model.
4. Warm Up
Allow connections, runtime optimization, caches and autoscaling to reach the intended starting state when the scenario requires it.
Cold-start performance should be a separate explicit scenario rather than accidental noise.
5. Ramp Load Gradually
Warm-up -> ramp-up -> steady state -> ramp-down -> recovery
Gradual stages reveal when latency, errors or resource saturation begin to change.
6. Observe Every Layer
Collect test-generator metrics and server telemetry on the same timeline.
Load generator
- requests, latency, errors
Application
- traces, service latency, exceptions
Infrastructure
- CPU, memory, network, containers
Dependencies
- database, cache, queue, external APIs
7. Verify Recovery
After the workload ends, confirm that:
- latency returns to normal
- queues drain
- autoscaled resources settle safely
- memory is released where expected
- error rates recover
- no corrupted or duplicate business data remains
Example Load Test
This k6 example applies a staged load to an API and checks both correctness and timing.
import http from "k6/http";
import { check, sleep } from "k6";
export const options = {
stages: [
{ duration: "1m", target: 20 },
{ duration: "5m", target: 20 },
{ duration: "1m", target: 0 },
],
thresholds: {
http_req_failed: ["rate<0.01"],
http_req_duration: ["p(95)<500"],
},
};
export default function () {
const response = http.get(`${__ENV.BASE_URL}/api/products`);
check(response, {
"returns 200": (result) => result.status === 200,
"returns products": (result) => result.json("items.length") > 0,
});
sleep(1);
}
The numbers are examples, not universal targets. Set stages and thresholds from the system's requirements and expected traffic.
Never run an unapproved high-load test against production. It can look like an attack, affect real users and create real costs or data.
Finding the Bottleneck
A bottleneck is the limiting part of the system under the tested workload.
CPU Saturation
Symptoms can include:
- high CPU and runnable work
- longer request queues
- increasing latency
- expensive JavaScript, serialization or computation
Possible actions include profiling hot code, reducing work, caching results or scaling compute after verifying the application can benefit.
Memory Pressure
Look for:
- continuously growing memory
- frequent or long garbage collection
- swapping or out-of-memory restarts
- retained browser objects
- unbounded caches
Use allocation or heap profiles to identify retained objects rather than guessing.
Database Limit
Look for:
- slow queries
- missing or ineffective indexes
- lock contention
- exhausted connections
- replication lag
- large scans
Application latency often rises before database CPU reaches 100% because locks, I/O or connection queues can be the real limit.
Network or External Dependency
Look for:
- DNS or connection delay
- TLS handshake cost
- large payloads
- packet loss or retransmission
- regional latency
- slow third-party APIs
Apply timeouts, caching, connection reuse, circuit breakers or asynchronous workflows according to the dependency.
Main-Thread Bottleneck
For frontend applications, reduce unnecessary browser work through:
- smaller initial JavaScript
- code splitting and lazy loading
- breaking long tasks
- efficient rendering and state updates
- image and font optimization
- limiting third-party scripts
- moving suitable computation off the main thread
Measure again after each meaningful change.
Third-Party Scripts
Analytics, advertisements, tag managers, support widgets and experiments can consume network, CPU and main-thread time.
Review:
- business owner and purpose
- bytes transferred
- execution time
- loading priority
- privacy implications
- failure behavior
Load noncritical scripts later where appropriate and remove tools that no longer provide enough value.
Performance Budgets
A performance budget turns expectations into release checks.
Budgets can cover:
- JavaScript and image size
- LCP, INP or CLS targets
- API p95 latency
- error rate
- request count
- third-party script cost
- maximum database query count
Change exceeds budget
|
v
CI warning or failure
|
v
Investigate, optimize or approve a documented exception
Budgets should reflect real user and business needs. Review them as the product and traffic evolve.
Performance Testing in CI
Full load tests are often too expensive for every commit. Use layers:
Every pull request
- bundle-size check
- focused Lighthouse or component benchmark
Main branch or pre-release
- stable synthetic journeys
- API performance smoke tests
Scheduled or release test
- broader load, stress or soak scenario
Production
- real-user monitoring and service telemetry
Compare only sufficiently stable tests. Noisy environments can create false regressions and train teams to ignore warnings.
Analysis Workflow
Use a repeatable loop:
- define the user or system symptom
- reproduce it under known conditions
- record browser and server evidence
- identify the limiting path or resource
- form one optimization hypothesis
- make a focused change
- repeat the same test
- compare distributions and resource behavior
- verify real-user impact after release
Measure -> Explain -> Improve -> Re-measure
Avoid changing several layers at once when you need to know which change produced the improvement.
Common Mistakes
| Mistake | Better approach |
|---|---|
| Reporting only an average | Include p50, p95, p99 and the distribution |
| Measuring latency without errors | Report latency, throughput and error rate together |
| Generating unrealistic traffic | Model real journeys, arrival patterns, data and think time |
| Testing a tiny empty database | Use representative data volume and indexes |
| Running one Lighthouse audit | Run controlled repeated samples and inspect metrics |
| Treating a Lighthouse score as the requirement | Define user-centered budgets and inspect root causes |
| Comparing different environments | Keep conditions consistent or document differences |
| Ignoring browser extensions and stored state | Use a clean profile and explicit cache scenarios |
| Blaming JavaScript without profiling | Use traces and call stacks to find actual expensive work |
| Running load from an underpowered generator | Monitor the generator so it is not the bottleneck |
| Testing only the happy path | Include failures, timeouts, retries and recovery |
| Stopping at the breaking point | Verify graceful degradation and recovery afterward |
| Applying unapproved load to production | Use authorization, safeguards and a controlled plan |
| Optimizing without re-testing | Repeat the same measurements and compare results |
Summary
Performance testing measures user experience and system behavior under controlled, realistic conditions.
Define the workload and performance target
|
v
Measure latency, throughput, errors and saturation
|
v
Use browser traces, lab tools and field data
|
v
Locate the limiting layer or resource
|
v
Make one evidence-based improvement
|
v
Repeat the test under the same conditions
|
v
Protect the result with budgets and production monitoring
A useful performance test does more than produce a score. It explains which users or systems are slow, under what workload, why the slowdown occurs and whether a change produces a measurable improvement.