Skip to content

API Performance Testing: A Step-by-Step Guide

Run API performance testing in nine steps: set SLOs, weight endpoints, choose a workload model, script it in k6, read percentiles and find the bottleneck.

A numbered nine-step checklist from objectives to CI gate on the left, and a p95 latency versus request rate chart on the right where the curve crosses a dashed SLO line at the highest rate

API performance testing sends realistic request traffic to an API under controlled load and measures how fast and how reliably it answers. You record latency percentiles, throughput, error rate and the saturation of the service and its dependencies, then compare them with objectives you set before the run. This guide walks through the full method in nine steps.

Prerequisites

You need these before step 1:

  • A test environment sized close to production, with data you reset between runs.
  • Permission to send load to that environment, and a window agreed with its owners.
  • Access to server metrics and logs for the API and its dependencies.
  • A load tool such as k6 installed locally, or a MaxoPerf account.
  • A day of access logs or gateway metrics to read the real endpoint mix.

What you measure

Four groups of measurements describe an API under load.

  • Latency percentiles. p50 is the typical request, p95 is what one in twenty requests exceeds, and p99 is the slow edge. Report them per endpoint. The mean hides the tail. The latency histogram guide shows why.
  • Throughput. Requests per second the API completed, not the rate you asked for. The two diverge when the system or the load generator falls behind.
  • Error rate. Split by status class: 4xx from a bad script or bad data, 5xx from the server, and timeouts or connection resets that never produce a status.
  • Saturation. CPU, memory, connection pool usage, queue depth, thread pool use and the latency of each downstream dependency such as the database, cache or a third-party API.

The first three are measured at the client. Saturation comes from the service itself and is what turns a slow result into an explanation.

Test types for APIs

You rarely run only one shape. Each type answers a different question.

TypeLoad shapeQuestion it answers
Smoke1 to 5 users or a trickle of requests for a minuteDoes the script work and does the API respond at all?
LoadExpected peak, held steadyDoes the API meet its objectives at normal peak?
StressStepped ramp past expected peakWhere does latency or error rate break, and how does it fail?
SpikeSudden jump to a high rate, then backDoes it survive a burst and recover afterward?
SoakModerate load for hoursDo leaks, growth or slow drift appear over time?

The API performance test page in the academy covers how these apply to HTTP APIs in more detail.

The nine steps

1. Set objectives from SLOs or product needs

Write the pass criteria before you write the script. If the team has service level objectives, use them: “95% of GET /search requests complete in under 400 ms with an error rate under 1%”. If there are no SLOs, take them from a product need, such as the latency at which a mobile screen feels slow, or from the current production numbers plus an agreed tolerance.

Also write the load target: the request rate you expect at peak and the rate you want headroom for. Without a number, a test only says “it ran”.

2. Pick and weight endpoints from production traffic

Testing every endpoint equally gives a workload nobody has. Pull a day of access logs or gateway metrics and rank endpoints by request share. Keep the top ones that cover most of the traffic, plus any endpoint that is rare but expensive, such as a report export or a bulk write.

Turn the shares into weights. If search is 60% of calls, product detail 30% and checkout 10%, the script should send them in that ratio. Label every request so results come back per endpoint. If you already have a Postman collection, it supplies the request list. The weights still come from production traffic. See turning a Postman collection into a load test.

3. Choose the workload model

A closed model runs a fixed number of virtual users who each wait for a response before the next request. An open model starts requests at a set arrival rate whether or not earlier ones have finished. Public APIs behave like the open model, because clients do not wait for each other. A closed model hides overload: when the API slows, the virtual users slow too and the offered load falls.

For most API tests, drive the load by arrival rate and cap the number of in-flight requests with a pool of virtual users. Arrival rate vs concurrency explains the difference, and virtual users vs requests per second helps convert between the two when you need to.

4. Prepare data and auth

Data is where API tests most often go wrong.

  • Unique identities. If every virtual user logs in as the same account, you test a hot row and one cache entry. Use a pool of test users and tokens, large enough that no single one carries a share of traffic production would never see.
  • Token handling. Obtain tokens before the load phase, or refresh them at a realistic interval. Hammering the login endpoint on every iteration tests your identity provider, not your API.
  • Correlation. Values from one response often feed the next request: an order id, a cursor, a CSRF token. Extract them per user. A shared value makes every user act as one person.
  • Idempotency for writes. Repeated POSTs create real records. Use idempotency keys or unique payloads, run against a test environment you reset between runs, and plan cleanup. Never aim write-heavy tests at production data without an agreed cleanup path.

5. Script it

k6 is a good starting point because scripts are plain JavaScript, thresholds are declared next to the load profile, and it has an arrival-rate executor. JMeter, Gatling and Locust do the same job. Pick the one your team already reviews and versions. The example below sends weighted traffic at a ramping arrival rate and fails the run on explicit thresholds.

import http from 'k6/http';
import { check } from 'k6';
import { SharedArray } from 'k6/data';
import exec from 'k6/execution';
const tokens = new SharedArray('tokens', () => JSON.parse(open('./tokens.json')));
const BASE = __ENV.BASE_URL;
export const options = {
scenarios: {
ramp: {
executor: 'ramping-arrival-rate',
startRate: 20,
timeUnit: '1s',
preAllocatedVUs: 200,
maxVUs: 1000,
stages: [
{ target: 100, duration: '3m' },
{ target: 200, duration: '3m' },
{ target: 300, duration: '3m' },
{ target: 400, duration: '3m' },
],
},
},
thresholds: {
http_req_failed: ['rate<0.01'],
'http_req_duration{endpoint:search}': ['p(95)<400'],
'http_req_duration{endpoint:product}': ['p(95)<300'],
dropped_iterations: ['count==0'],
},
};
export default function () {
const token = tokens[exec.scenario.iterationInTest % tokens.length];
const params = { headers: { Authorization: `Bearer ${token}` } };
const pick = Math.random();
let res;
if (pick < 0.6) {
res = http.get(`${BASE}/search?q=shoes`, { ...params, tags: { endpoint: 'search' } });
} else {
res = http.get(`${BASE}/products/42`, { ...params, tags: { endpoint: 'product' } });
}
check(res, { 'status is 200': (r) => r.status === 200 });
}

The dropped_iterations threshold matters. When k6 fails to start requests at the requested rate because it ran out of virtual users, it drops iterations. A test that drops iterations did not deliver the load it claims.

6. Run a smoke check, then a stepped ramp

Run the script at one or two requests per second for a minute first. Check that status codes are right, that tokens work, that correlated values flow, and that your labels appear in the results. Fix the script here, where mistakes are cheap.

Then run the stepped ramp. Hold each step long enough for latency to settle, often 3 to 5 minutes, and keep the steps even so a change in the curve points to a rate. A ramp finds the knee in one run: the rate where p95 starts to climb faster than the load.

7. Read the results

Read in this order.

  1. Validity. Did the generator deliver the requested rate? Compare achieved with requested requests per second and check for dropped iterations. Check generator CPU and network use as well. A saturated load generator produces slow numbers that belong to the generator.
  2. Errors. Look at count and class. A 4xx wave often means a data or auth problem in the script. 5xx and timeouts point at the API.
  3. Percentiles per endpoint. Compare p95 and p99 against the objectives from step 1, one step at a time. Look at the tail, not the average. A p99 several times the p50 means a slow cohort worth chasing.
  4. Shape across steps. Latency that is flat and then rises sharply means a resource ran out. Latency that rises slowly from the start suggests work that grows with load, such as a growing queue or an unbounded query.

8. Find the bottleneck with server telemetry

Client numbers tell you something is slow. Server telemetry tells you what. Line up the run’s time window with metrics from the service and its dependencies:

  • CPU, memory and garbage collection pauses on the API instances.
  • Connection pool wait time and active connections.
  • Database slow query logs, lock waits and CPU.
  • Cache hit rate and downstream call latency.
  • Queue depth and thread pool saturation.

Find the first resource that saturates as the rate climbs. That is usually the limit, and everything after it is a consequence. Change one thing, rerun the same ramp, and compare. Distributed traces help when a slow endpoint spans several services.

9. Gate it in CI and compare runs

A test that runs once ages quickly. Keep a baseline run, rerun the same profile on release candidates, and fail the build when a criterion is breached. Compare the new run with the baseline for latency, throughput and error rate per endpoint, and confirm the test conditions matched before blaming the code. The API performance testing as a release gate post covers how to size those checks, and performance test thresholds covers how to pick the numbers.

A worked example

The numbers below are hypothetical and exist to show how the reading works. Assume a product API with two objectives: p95 of GET /search under 400 ms, and an error rate under 1%. Expected peak is 300 requests per second. The team runs the stepped ramp from step 5.

Step (requested rate)Achieved rateSearch p95Search p99Error rate
100 req/s100120 ms210 ms0.0%
200 req/s200150 ms260 ms0.1%
300 req/s299210 ms420 ms0.3%
400 req/s342780 ms2,900 ms4.2%

At 300 requests per second the API meets both objectives, so the load target passes. At 400, three signals agree that the API is past its limit: p95 is almost double the objective, the achieved rate sits below the requested rate, and errors cross 4%.

The achieved rate matters here. The generator was healthy, so the gap between 400 and 342 is the API refusing or timing out requests, not a client limit. The team opens the dashboards for the same window and sees the database connection pool at its maximum from the 400 step on, with requests waiting for a connection. The fix is a pool and query change, and the proof is the same ramp run again with the p95 and error rate back inside the objectives. Headroom above the 300 target is now measured instead of assumed.

REST, GraphQL and gRPC

The method is the same for each protocol. The details change.

REST gives you many endpoints with distinct costs, so per-endpoint labels and weights matter most. GraphQL usually has one URL, so you have to label by operation name, vary query shapes and watch for deep or expensive queries. See GraphQL load testing. gRPC uses long-lived HTTP/2 connections and streaming, so connection reuse, deadlines and message sizes shape the result. See gRPC load testing.

Troubleshooting

  • Achieved rate stays below the requested rate. Check dropped_iterations and generator CPU. Raise preAllocatedVUs and maxVUs, or add generators. If the generator is idle, the API is the limit.
  • A wall of 401 or 403 responses. Tokens expired during the run or the pool is too small. Issue tokens with a lifetime longer than the test and refresh them at a realistic interval.
  • A wall of 4xx responses on writes. The payloads collide on unique fields. Generate unique values per iteration and use idempotency keys.
  • Latency is flat, then errors appear at once. A hard limit sits in the path, such as a rate limiter, a gateway quota or a connection cap. Read the 429 and 503 counts and raise the limit in the test environment.
  • Results vary widely between identical runs. Another workload shares the environment, caches start cold, or each step is too short to settle. Isolate the environment and lengthen the steps.
  • p95 passes but users still complain. You measured the wrong endpoint mix or only the average. Recheck the weights from step 2 and read p99.

Common mistakes

  • Reporting the average response time and calling it done.
  • Using a closed model for a public API, so overload quietly lowers the offered load.
  • Testing one endpoint, or all endpoints in equal share, instead of the production mix.
  • Sending every request with one token or one user id.
  • Ignoring dropped iterations and generator CPU, then blaming the API for generator limits.
  • Running a short test that never leaves the warm-up phase of caches and connection pools.
  • Testing a small environment and extrapolating linearly to production.
  • Skipping server telemetry, which leaves you with a symptom and no cause.
  • Running a test once and never keeping a baseline to compare against.

Run it in MaxoPerf

MaxoPerf runs the script from step 5 as written. You upload k6, JMeter and Taurus files and mark one entrypoint, or build requests in the console. Then you choose the load profile and locations. The same engine support covers Gatling and Locust scenarios through the performance test builder.

For the verdict, failure criteria such as p95 and error rate turn each run into a passed or failed result, and a breach stops the run early when the criterion’s action is stop. To trigger runs from a pipeline, see running tests from CI, and to compare a new run with a baseline, use the run comparison view, which shows deltas for latency percentiles, throughput and error rate per label. For a full CRUD scenario to adapt, start from the REST API CRUD load test recipe.

Questions this article answers

What is API performance testing?

API performance testing sends controlled, realistic request traffic to an API and measures latency percentiles, throughput, error rate and resource saturation. The goal is to learn whether the API meets its objectives under expected load and where it stops meeting them.

Which metrics matter most in API performance testing?

Latency percentiles (p50, p95, p99) per endpoint, achieved throughput in requests per second, and error rate split by status class. Pair them with server-side saturation signals such as CPU, connection pool use and queue depth, because the client numbers show a symptom and the server numbers show the cause.

How is API performance testing different from functional API testing?

Functional tests check that one request returns the right answer. Performance tests check how the API behaves when many requests arrive together, so they care about timing, volume, data variety and resource limits. A response that passes a functional check is still too slow if it takes 2 seconds at 300 requests per second.

Which tool should I use for API performance testing?

k6 is a common choice because tests are JavaScript, thresholds are built in and an arrival-rate executor is available. JMeter, Gatling and Locust cover the same ground. Pick the one your team reviews and versions, and confirm it models an open arrival rate.

How long should an API load test run?

A smoke check takes a minute or two. A stepped ramp usually needs 10 to 30 minutes, with each step long enough to settle, often 3 to 5 minutes. A soak test runs for hours so that leaks and slow drift show up.