Session 3 — Load & Stress Testing
Session 3Load & Stress Testing · 3h

Putting the application to the test before customers do

Today you will simulate hundreds of users using your application at the same time, and find out how much it can take, where it breaks and why. You will learn to read percentiles, write tests with Gatling, JMeter and k6, tune Spring Boot and protect the application when the load goes over the limit.

  • Tell load, stress, spike and soak tests apart
  • Read percentiles and apply Little's Law
  • Write simulations in Gatling, JMeter and k6
  • Find the saturation point and tune Tomcat, Hikari and the JVM
  • Run performance tests in the CI pipeline
  • Protect the app with rate limiting and circuit breakers

Why test under load?

An application that responds in 50 ms with one user may take 8 seconds with a thousand. Or simply fall over. Normal tests (unit, integration) check whether the code is correct. Performance tests check whether it stays correct and fast when lots of people use it at the same time.

The new bridge

Before opening a bridge to the public, engineers fill it with loaded lorries and measure how much it bends. They don't wait for the first rush hour to find out. A load test is exactly that: simulated lorries on top of your application, in a controlled environment.

Black FridayPredictable peaksCampaigns, sales, the tax-return deadline. You know it's coming: test beforehand.
CapacityHow many servers?Knowing how many requests one instance can handle lets you plan costs and scale with numbers, not hunches.
RegressionsDid it get slower?An innocent change (a new N+1) can double the response time. An automated test catches it.

What you will see in this session

0:00–0:35Module 3.1 · Performance testing fundamentals
0:35–1:35Module 3.2 · Tools: Gatling, JMeter and k6 (+ lab)
1:35–1:45Break ☕
1:45–2:25Module 3.3 · Execution, analysis and tuning (+ lab)
2:25–2:50Module 3.4 · CI/CD and resilience
2:50–3:00Course wrap-up

The types of test: each one answers a question

They all use the same tools. What changes is the shape of the load over time and the question you want answered. Click on each type:

TypeQuestionTypical duration
LoadWith the expected normal load, do we meet the response-time goals?15–60 min
StressWhere does it break? And when it breaks, how does it break (gradually or suddenly)?Until it breaks
SpikeCan we handle a sudden jump? Do we recover by ourselves afterwards?10–20 min
Soak (endurance)After hours, are there memory leaks, lost connections, disks filling up?4–24 h
ScalabilityIf we double the instances, do we double the capacity?Several tests
Smoke test first

Before any big test, run a smoke test: 1 or 2 users for 1 minute. It only serves to confirm that the script works and the environment is up. It saves hours of invalid tests.

The metrics that matter (and why the average lies)

ThroughputRequests per second (RPS)How much work the application does.
LatencyResponse timeHow long each user waits. Measured in percentiles.
ErrorsFailure ratePercentage of 5xx responses, timeouts and refused connections.
ResourcesCPU, memory, poolsOn the server side: they explain why the other numbers are what they are.

Percentiles: what users really feel

The 95th percentile (p95) is the time below which 95% of requests fall. If the p95 is 400 ms, 95 out of every 100 users waited less than 400 ms, and 5 waited longer.

The average height with a giant in the room

If a room holds 9 people who are 1.70 m tall and someone 3 metres tall walks in, the average rises a little and describes nobody. With response times it's worse: the average hides the users who waited 10 seconds. And those are the ones who abandon the purchase.

Generate 1000 simulated requests. Increase the percentage of slow requests and notice how the average barely moves while the p99 shoots up.

PercentileMeaningWhat it is for
p50 (median)Half the requests are faster.The «typical» experience.
p95Only 5% are slower.The most common target in SLOs.
p99Only 1% is slower.The «tail». On a site with 1 million requests a day, that's 10,000 people.
maximumThe worst case.Useful for spotting timeouts and GC pauses.
Never average percentiles

The average of the p95s of 3 servers is not the p95 of the system. To combine percentiles you need the original data or histograms. That's why Micrometer uses percentiles-histogram: true and the calculation is done in Prometheus.

Little's Law: the formula that ties everything together

A single formula, valid for any stable system (a restaurant, a supermarket queue, a server):

L = λ × WConcurrency = throughput × timeL: requests in progress at the same time. λ: requests per second. W: average time of each one, in seconds.

Example: 200 requests/s × 0.25 s = 50 requests in progress at any instant. You need at least 50 threads (or virtual threads) and whatever database connections those requests use.

The same law applies to tests. In a closed model (N virtual users who wait for the response and then «think» for Z seconds), the maximum throughput is N / (W + Z). If the application gets slow, the virtual users send fewer requests and the test hides the problem. In an open model (X users arrive per second, no matter what), the queue grows just as in real life. For public sites, prefer the open model.

Plan before you fire

SLI, SLO and SLA

SLI
Service Level Indicator: what you measure. E.g. «p95 of the response time of POST /checkout».
SLO
Service Level Objective: the internal goal. E.g. «p95 < 500 ms and errors < 0.1%, at 300 requests/s».
SLA
Service Level Agreement: the contractual commitment to the customer, with penalties. Usually less demanding than the SLO, to leave a margin.

Without an SLO, a load test produces numbers but no answers. «Is 400 ms good?» It depends on the goal.

Modelling realistic scenarios

Real users don't all press the same button. Look at the production logs or Google Analytics and reproduce the mix:

Journey% of usersSteps
Browse70%Home page → search → view 3 products
Buy20%Search → product → cart → checkout → pay
Account10%Login → view orders → detail of one order
Think timeA pause between steps, like a real person reading the page (2–8 s, with random variation). Without it, 100 virtual users look like 2000.
Varied dataUse many different products and customers (CSV files). If everyone asks for product 1, you are only testing the cache.
Warm-upThe JVM optimises the code as it runs (the JIT compiler). The first few minutes are slower: discard them or add a warm-up phase.

The environment

  • As close to production as possible: same machine sizes, same database version, realistic data volume. A database with 100 rows will never reveal a missing index.
  • The load generator on another machine. If it runs on the same server, it steals CPU and skews everything.
  • Simulated external services (WireMock) with realistic latencies. Don't load-test against the real bank or carrier!
  • Never in production without explicit authorisation, an agreed window and an abort plan.

Gatling: load tests written in Java

Gatling describes tests as code (in Java, Kotlin or Scala), which lets you keep them in Git, review them and run them in the pipeline. It uses a very efficient asynchronous model: an ordinary machine simulates thousands of users. At the end it generates an HTML report with charts.

Installing it in the Maven project

The first simulation

PieceWhat it is
HttpProtocolBuilderShared configuration: base URL, headers.
ScenarioBuilderThe journey of a virtual user, step by step.
feed(...)Reads data from a CSV to vary the requests. #{id} inserts the value.
check(...)Validates the response. Without checks, a 500 would count as a success!
injectOpen / injectClosedOpen model (arrivals per second) or closed model (a fixed number of concurrent users).
assertionsPass criteria. If they fail, the build fails.

The most common injection profiles

Run the simulation and look at the summary that appears in the terminal. Change the load and the server's capacity.

The HTML report

At the end, Gatling writes target/gatling/purchase-…/index.html. The most useful charts: «Response Time Percentiles over Time» (to see whether the p95 rises during the test) and «Number of Requests per Second» compared with «Active Users».

JMeter and k6: the alternatives

JMeter is the veteran (since 1998), with a graphical interface and a huge community. It supports HTTP, JDBC, JMS, FTP and much more. Tests are XML files (.jmx) built in the interface.

ElementWhat it is for
Thread GroupA group of virtual users: how many, how quickly they start (ramp-up), how many iterations.
SamplerA request (e.g. HTTP Request).
Config ElementShared configuration: HTTP Request Defaults, CSV Data Set Config.
TimerThink time (Uniform Random Timer).
AssertionValidates responses (status, JSON).
ListenerShows results. Turn them off during the real test: they use a huge amount of memory.

-n = no GUI; -t = test plan; -l = results file; -e -o = generate the HTML dashboard; -J = pass properties (read in the plan with ${__P(users)}).

k6 (by Grafana Labs) uses JavaScript scripts, is lightweight, fast and very CI-friendly. Its thresholds play the same role as Gatling's assertions.

Which one to choose?

GatlingJMeterk6
Test languageJava / Kotlin / ScalaXML via GUIJavaScript
Generator efficiencyVery highMedium (1 thread per user)Very high
Tests as code / GitExcellentPoor (XML is hard to review)Excellent
ProtocolsHTTP, WebSocket, JMS, gRPC…The widest rangeHTTP, WebSocket, gRPC, browser
ReportRich HTML includedHTML dashboard includedTerminal summary; charts via Grafana
Ideal forJava teams, integration with Maven/GradleQA teams without programming, exotic protocolsPolyglot teams, CI, the Grafana ecosystem

Lab 4: a Gatling simulation for the shop

Goal lab · 25 min

Create ShopSimulation with two journeys (70% browse, 30% buy) against the course application, with an SLO of p95 < 300 ms and fewer than 1% errors.

  1. Create src/test/resources/products.csv with 200 real ids from your database.
  2. Write the two scenarios, with a check on every request and think time.
  3. Run a smoke test: 1 user/s for 30 s. Fix things until you have 0% errors.
  4. Run a load test: ramp from 1 to 30 users/s in 1 minute and hold for 3 minutes.
  5. Open the HTML report and note: maximum RPS, p50, p95, p99 and errors.
Show solution

Each scenario has its own arrival rate: 21 + 9 = 30 users/s, in a 70/30 ratio. Alternative: a single scenario with randomSwitch().on(percent(70.0).then(…), percent(30.0).then(…)).

Running the test and finding the saturation point

During a test, watch two screens at the same time: the load generator's report (what the user feels) and the Grafana dashboard from session 2 (what the server feels). The explanation is always in the link between the two.

Load generatorRPS, p95, errors
⇄
Grafana / PrometheusCPU, heap, GC, Tomcat threads, Hikari pending
⇄
JFR / tracesWhich method? Which query?
In the generator you see…On the server look for…
p95 rising with stable RPShikaricp.connections.pending > 0, all Tomcat threads busy: there's a queue.
Periodic latency spikesjvm.gc.pause: long GC pauses.
Sudden 500 errorsLogs with CannotGetJdbcConnectionException, timeouts from external services.
Connection refused errorsTomcat's accept-count full, open files (ulimit) exhausted.
CPU at 100% and RPS not risingRecord a JFR: the flame graph tells you who is burning CPU.

Stress test simulator

This simulator ramps the load from 0 to the maximum in 2 minutes (with 1 s of think time) and shows what happens. Try it: start with the default values, find the point where the p95 shoots up, and then tune the configuration to push it to the right.

Reading the curve

1. Linear zoneMore users → more RPS, stable latency. The server has headroom.
2. KneeRPS stops rising. This is the saturation point: some resource has hit 100%. Latency starts to rise.
3. SaturationThe extra requests just queue up. Latency grows in a straight line (Little's Law) and timeouts arrive.
4. CollapseSometimes RPS even drops: the server spends time on requests that have already expired, retries, GC. This is what resilience mechanisms prevent.
Usable capacity is not the peak

Plan to operate at around 60–70% of the saturation point. The margin absorbs peaks, deployments, an instance being down and next quarter's growth.

Degradation and recovery

In a spike test, the most important question is: after the peak, does the application go back to normal by itself? If latency stays high minutes afterwards, something got «clogged»: full internal queues, lost connections, a cache that was emptied, a circuit breaker stuck open. Always measure the 5 minutes after the peak.

Tuning a Spring Boot application

Golden rule: change one thing at a time, repeat the same test and compare. If you change three parameters and it improves, you don't know which one helped (or whether one of them made things worse).

Web server (Tomcat)

Database (HikariCP)

The JVM in containers

ParameterSymptom that it's wrongDirection
tomcat.threads.maxAll threads busy and low CPU.Raise it, or use virtual threads. But first confirm the queue isn't in the DB.
hikari.maximum-pool-sizepending > 0 and the DB has spare CPU.Raise it gradually. If the DB is already at 100%, raising it makes things worse.
-Xmx / MaxRAMPercentageVery frequent GC, Full GCs.More heap, or fewer allocations (JFR → Allocations).
GCp99 spikes that coincide with pauses.ZGC for short pauses.

Revisiting sessions 1 and 2 under load

This is where you see the real value of the earlier techniques. Repeat the test with and without each improvement:

CacheWith a 90% hit ratio, the DB receives 10 times fewer queries: the knee moves a long way out. But watch the test data: if it's all the same, the cache looks miraculous and lies.
ParallelismReduces the latency of each request, but may increase pressure on shared resources (more simultaneous connections).
N+1 fixedFewer trips to the DB = connections returned sooner = more requests per connection.

Lab 5: stress, tuning and comparison lab · 20 min

  1. Run a step stress test (20, 40, 60… users/s, 1 minute each) and note the level at which the p95 goes past 300 ms.
  2. In Grafana, identify the resource that saturated first (CPU, threads, Hikari, GC).
  3. Change one parameter related to that resource and repeat.
  4. Fill in the table: configuration · RPS at the knee · p95 · p99 · errors. Compare with the numbers you kept from session 1.

Performance tests in the pipeline

A load test that is run once a year doesn't catch regressions. The idea is to have a short, stable test that runs automatically (for example every night or before each release) and fails the build if performance gets worse.

Ephemeral environments with Testcontainers

Testcontainers starts databases, Redis or any Docker image from your tests, and shuts everything down at the end. That way every run gets a clean, identical environment.

Example with GitHub Actions

Detecting regressions

  • Absolute assertions: p95 < 300 ms. Simple, but they only fail when it's already too late.
  • Comparison with a baseline: keep the results of the last good version and fail if the p95 gets more than 15% worse. Gatling Enterprise and k6 Cloud do this; it can also be done with a script that reads the report's stats.json.
  • Noise: shared CI runners vary a lot. Use dedicated machines for performance tests, repeat 3 times and compare the median, and tolerate some variation.

Resilience: failing gracefully

However well you tune, there will always be a day with more load than capacity, or an external service that gets slow. A resilient application doesn't fall over: it degrades gracefully, serving part of the requests well instead of all of them badly.

The circuit breaker at home

When there is a short circuit, the breaker cuts the power to protect the installation. It doesn't keep trying non-stop. Later you switch it back on to see if the problem has gone. A circuit breaker does the same with calls to services that are failing.

⏱ TimeoutNever wait forever. A call with no timeout holds a thread and a connection indefinitely.
🔌 Circuit breakerIf a service fails a lot, stop calling it for a while and answer immediately with a plan B.
🚦 Rate limiterLimits how many requests per second are accepted (per user or in total). The excess gets 429 Too Many Requests.
🚢 BulkheadLimits how many simultaneous calls go to each dependency, so that a slow one doesn't consume all the threads.
🔁 RetryRetries temporary failures, with increasing waits. Careful: unlimited retries multiply the load on a service that is already struggling.

Resilience4j in Spring Boot

The three states of the circuit breaker

CLOSED 🟢Normal. Calls go through and the failure rate is counted.
→failures ≥ limit
OPEN 🔴Doesn't call the service. Answers immediately with the fallback. Saves threads and gives the service time to recover.
→after waiting
HALF_OPEN 🟡Lets a few test calls through. If they go well, it closes; if they fail, it opens again.

Try it: make a few payments, turn on the bank failures, keep paying and watch the circuit open. Then turn off the failures and wait for it to recover.

Protecting the entrance: rate limiting

Where to put rate limiting

Resilience4j limits per instance. For global or per-client limits (per API key), it's usually done at the entrance: in an API gateway (Spring Cloud Gateway with Redis), in Nginx or in the cloud load balancer.

Graceful degradation and graceful shutdown

  • Graceful degradation: under pressure, switch off the non-essentials. Personalised recommendations can be replaced by a fixed list; checkout, never.
  • Graceful shutdown: with server.shutdown=graceful, during a deployment Spring stops accepting new requests, finishes the ones in progress and only then shuts down. Combined with the Actuator's readiness probe, deployments stop producing 502 errors.

Wrap-up: the complete cycle

Over the three sessions you have built a method, not just a set of tricks. It is a cycle that repeats:

1. MeasureLoad test + metrics. Session 3.
→
2. AnalyseTraces, JFR, dumps. Find THE bottleneck. Session 2.
→
3. OptimiseCache, parallelism, queries, tuning. Sessions 1 and 3.
→
4. ValidateRepeat the same test. Did it improve? Did nothing get worse?
↺

Stop when the SLO is met with a margin. Optimisation without a goal never ends.

Recommended resources

TopicWhere to go deeper
ConcurrencyBook «Java Concurrency in Practice» (Goetz) · JEP 444 (Virtual Threads)
JVM performanceBook «Optimizing Cloud Native Java» (Evans, Gough) · Aleksey Shipilёv's blog
SpringSpring Boot documentation: «Production-ready Features», «Caching», «Task Execution»
HibernateVlad Mihalcea's blog and book «High-Performance Java Persistence»
Load testingdocs.gatling.io · grafana.com/docs/k6 · «Site Reliability Engineering» (Google), chapters on SLOs

Exercises

1. Reading a result easy

A test gives: average 120 ms, p50 80 ms, p95 310 ms, p99 4200 ms, errors 0.2%. The SLO is p95 < 400 ms and p99 < 1000 ms. Does it pass? What do you investigate first?

Show solution

It fails on the p99 (4200 ms > 1000 ms), although it passes on the p95. 1% of requests are very slow. Such a long tail with a normal p95 suggests something sporadic: GC pauses (check jvm.gc.pause), waiting for pool connections at peak moments, timeouts from an external service or one specific slow endpoint. Start by splitting the p99 by endpoint in the report.

2. Little's Law medium

You want to serve 500 requests/s with an average time of 80 ms. Each request uses the database for 15 ms. What is the minimum number of threads and connections you need?

Show solution

Threads: 500 × 0.080 = 40 requests in progress. Connections: 500 × 0.015 = 7.5 connections busy on average. Since requests don't arrive evenly, leave a margin: for example 15–20 connections, and Tomcat's default pool (200) is more than enough.

3. Spike test in k6 medium

Write the stages of a spike: 2 minutes at 20 users, a jump to 500 in 10 seconds, 1 minute at 500, back to 20 and hold for 5 minutes to observe the recovery.

Show solution

Session summary

The essentials in 10 points

  • Load, stress, spike, soak and scalability tests answer different questions. Always start with a smoke test.
  • Use percentiles (p95, p99), never just the average. Don't average percentiles.
  • Little's Law: requests in progress = requests/s × average time.
  • Define SLOs before testing; without a goal there is no conclusion.
  • Realistic scenarios: a mix of journeys, think time, varied data, warm-up.
  • Gatling (Java), JMeter (GUI, protocols) and k6 (JavaScript): all with pass criteria.
  • The saturation point is where RPS stops rising and latency shoots up. Operate at 60–70% of it.
  • Change one parameter at a time: Tomcat, Hikari, heap, GC.
  • Short, stable tests in the pipeline catch regressions.
  • Timeouts, circuit breakers, bulkheads and rate limiting prevent collapse.

Glossary

RPS
Requests per second: a measure of throughput.
Percentile
The value below which a given percentage of the measurements fall.
SLO
Service level objective, e.g. p95 < 500 ms.
Think time
A simulated pause between a user's actions.
Open model
Load defined by arrivals per second, independent of the response.
Saturation point
The load beyond which throughput stops growing.
Circuit breaker
A mechanism that cuts off calls to a failing service for a while.
Bulkhead
Isolating resources per dependency.
Rate limiting
A limit on requests accepted per unit of time.