xtest

Performance Testing

Load Testing and Scalability

This course teaches QA professionals and engineers how to plan, execute, and analyze load tests to understand how an application behaves under expected and peak traffic. You will learn the core vocabulary of performance testing, including throughput, latency, concurrency, and saturation, and how these concepts connect to real user experience. The course walks through designing realistic test scenarios, choosing appropriate tools such as k6, Apache JMeter, Gatling, and Locust, and running tests against staging or production-like environments safely. You will practice reading performance metrics, spotting bottlenecks in application and infrastructure layers, and translating findings into scaling decisions such as horizontal scaling, caching, and queueing. By the end of the course, you will be able to build a repeatable load testing process that fits into a team's release cycle and gives confidence that an application can handle growth.

Intermediate · By the Xtest team · About 34 minutes to read

Introduction

Every application works fine with one user in a browser. The real question is what happens with a thousand users, or ten thousand, hitting the same endpoints at once. Load testing and scalability is the discipline of answering that question before your users do. It sits apart from functional testing: instead of asking whether a feature works, it asks how a feature behaves under volume, and how gracefully a system degrades when it is pushed past its comfort zone. This course is built for QA engineers, developers, and anyone responsible for the reliability of a web application who wants a practical, tool-based path into performance testing. We will not dwell on theory for its own sake. Each concept is tied to a concrete tool and a concrete scenario: scripting a login flow in k6, ramping virtual users in JMeter, reading a latency percentile chart, and deciding whether a slow endpoint needs a database index or a caching layer. You will learn to distinguish load testing from stress testing and soak testing, to choose realistic traffic patterns instead of arbitrary numbers, and to avoid the common trap of testing in an environment so different from production that the results mean nothing. The course ends with hands-on exercises and a quiz so you can check your understanding before applying these techniques to your own systems. No prior performance testing experience is assumed, though familiarity with basic QA concepts and reading command-line output will help.

Foundations of Load Testing and Scalability

Before writing a single test script, it is worth being precise about what you are measuring and why. Load testing checks how a system behaves under an expected or anticipated level of concurrent usage, usually to confirm it meets agreed performance targets. Stress testing pushes traffic beyond that expected level to find the point where the system breaks or degrades badly, which tells you where your safety margin ends. Soak testing (sometimes called endurance testing) runs a moderate load for an extended period to catch problems that only appear over time, such as memory leaks or slowly filling connection pools. Spike testing throws a sudden burst of traffic at a system to see how it copes with an abrupt surge, such as a marketing campaign going live.

Scalability is the related but distinct question of whether a system can grow its capacity to meet rising demand, and at what cost. A system can pass a load test today and still be unscalable if the only way to serve more users is to buy proportionally more expensive hardware forever. Two broad strategies address this: vertical scaling, giving a single machine more CPU, memory, or disk, and horizontal scaling, adding more machines and distributing work across them, often behind a load balancer. Horizontal scaling usually requires the application to be stateless, or to externalize state (sessions, caches) to a shared store, so any instance can handle any request.

To talk about performance precisely, you need a small vocabulary. Throughput is the number of requests a system processes in a given time, often expressed as requests per second. Latency is the time a single request takes to complete, and it is almost always reported as percentiles rather than an average, because an average hides the slow outliers that frustrate real users. The 50th percentile (p50 or median) tells you the typical experience; the 95th or 99th percentile (p95, p99) tells you what your slowest users experience, and these tails matter because a system with an excellent average but a terrible p99 is still failing a meaningful share of requests. Concurrency is how many requests or users are active at once, and saturation is the point at which a resource, CPU, memory, database connections, or network bandwidth, is fully used and further load only adds queuing delay rather than more throughput.

A load test is only informative if it reflects something close to reality. That means testing against an environment with realistic data volumes, similar infrastructure sizing to production, and traffic patterns modeled on how real users actually behave, not a uniform hammering of a single endpoint. Get these foundations right and every later section, tool selection, scenario design, and result analysis, becomes much easier to reason about.

Load, Stress, Soak, and Spike Testing Compared

These four test types answer different questions, and conflating them leads to wasted effort or false confidence. A load test uses a traffic volume you expect in normal or peak operation, for example the number of concurrent users your analytics show during a typical lunchtime rush, and checks that response times and error rates stay within acceptable bounds. A stress test deliberately exceeds that volume, often ramping steadily upward, to find the breaking point: the number of concurrent users at which response times blow up or errors start appearing. Knowing this ceiling matters even if you never expect to reach it, because it tells you how much headroom you have and what your first bottleneck will be.

A soak test runs at a sustained, moderate load for hours, sometimes a full day, looking for problems that short tests cannot reveal: a memory leak that only matters after several hours, a log file that fills a disk, a connection pool that slowly exhausts because connections are not released properly. A spike test is short but sharp: it jumps from near-zero traffic to a high level almost instantly, modeling events like a ticket sale opening or a push notification going out to a large audience, and checks whether the system's autoscaling or queuing can absorb the surge without dropping requests.

In practice, a mature testing process uses all four at different points: load tests on every significant release, stress tests before a known high-traffic event, soak tests on a schedule such as before major holidays, and spike tests when launching a feature expected to go viral or be announced publicly. Each requires slightly different scripting: a soak test needs a scenario that loops indefinitely at steady concurrency, while a spike test needs one that jumps virtual users sharply within seconds rather than ramping gradually.

Key Metrics: Throughput, Latency Percentiles, and Error Rate

Three numbers form the backbone of almost every load test report: throughput, latency, and error rate. Throughput, typically requests per second, tells you how much work the system is getting through. Rising throughput as you add virtual users is healthy; throughput that flattens or drops while you keep adding users is a sign you have found a bottleneck, often called the saturation point.

Latency must be read as a distribution, not a single number. Reporting only the average latency can be deeply misleading: imagine 95 requests complete in 50 milliseconds and 5 complete in 5 seconds. The average looks fine, but 5 percent of your users just had a terrible experience. This is why performance reports use percentiles: p50 (median) for the typical case, p90 or p95 for the experience of most users, and p99 for the tail that reveals rare but real problems, such as a garbage collection pause or a lock contention issue. A good target might be "p95 latency under 400 milliseconds at 200 concurrent users," which is far more actionable than "average latency is fast."

Error rate is the percentage of requests that fail, whether through HTTP error codes, timeouts, or connection resets. A load test that reports excellent latency but a climbing error rate is not actually passing; it may mean the system is shedding load by rejecting requests rather than slowing them down, which keeps latency numbers low but still represents a real failure for the rejected users. Always look at throughput, latency percentiles, and error rate together, since each can tell a misleading story in isolation and only make sense as a combined picture of system health under load.

import http from 'k6/http';
import { check, sleep } from 'k6';

export const options = {
  stages: [
    { duration: '1m', target: 50 },   // ramp up to 50 virtual users
    { duration: '3m', target: 50 },   // hold steady at 50 users
    { duration: '1m', target: 0 },    // ramp down
  ],
  thresholds: {
    http_req_duration: ['p(95)<400'], // 95% of requests must finish under 400ms
    http_req_failed: ['rate<0.01'],   // error rate must stay under 1%
  },
};

export default function () {
  const res = http.get('https://example-staging.test/api/products');
  check(res, {
    'status is 200': (r) => r.status === 200,
    'has product list': (r) => r.json('products') !== undefined,
  });
  sleep(1); // pause to mimic real user think time
}

A basic k6 load test script that ramps virtual users up to 50, holds steady, then ramps down, while checking that 95th percentile response time stays under 400ms and the error rate stays under 1 percent.

Tips

  • Always define pass or fail thresholds (like p95 latency or error rate) before running a test, so results are judged objectively rather than by gut feeling afterward.
  • Include realistic think time (a short pause between requests) in your scripts; a test with zero delay between requests often produces unrealistically extreme concurrency.
  • Run a short smoke-level load test (a handful of virtual users) before a full-scale test to confirm your script and environment work correctly.

Common pitfalls

  • Reporting only average latency: a single average can hide a painful tail experience for a meaningful share of users. Always report percentiles like p95 and p99 alongside or instead of the average.
  • Testing against a vastly undersized environment and extrapolating results to production: a test run against a small staging box tells you little about how a full production cluster will behave. Match the test environment's scale to production as closely as budget allows, or clearly caveat the results.
  • Confusing stress testing with load testing: running a test that already exceeds expected traffic and calling any failure a 'performance bug' misses the point. Be clear about which test type you are running and what question it answers.

Choosing and Configuring Load Testing Tools

Picking a load testing tool is less about finding the "best" option and more about matching a tool's scripting model, protocol support, and reporting style to your team's skills and your system's architecture. The four tools most teams evaluate are k6, Apache JMeter, Gatling, and Locust, and each takes a different approach to describing load.

k6 uses JavaScript to define virtual user behavior, runs efficiently in Go under the hood, and produces clean metrics out of the box, making it a strong fit for teams already comfortable with JavaScript-based testing or CI pipelines. Apache JMeter is a mature, GUI-driven tool with broad protocol support (HTTP, JDBC, JMS, FTP, and more) and a huge plugin ecosystem, but its XML-based test plans can become unwieldy at scale. Gatling uses a Scala DSL that reads almost like plain English, and it is well regarded for its detailed HTML reports and efficient resource usage under high concurrency. Locust lets you write load tests as plain Python, which appeals to teams that want full programmatic control over user behavior and distributed execution across multiple worker processes.

Beyond scripting language, consider protocol coverage (not every tool handles WebSockets, gRPC, or MQTT equally well), the learning curve for non-specialist testers, how results integrate with your existing dashboards, and whether the tool can scale horizontally across multiple load generators for large-scale tests. A tool that's technically powerful but ignored because nobody on the team can read its scripts delivers no value.

Comparing Scripting Models and Protocol Support

The scripting model is usually the deciding factor for adoption. If your developers already write JavaScript or TypeScript, k6 scripts will feel natural and can live alongside application code in the same repository. If your organization has Python expertise, particularly among QA engineers who are not full-time developers, Locust's plain Python classes lower the barrier to entry significantly. Gatling's Scala DSL has a steeper learning curve for teams unfamiliar with Scala, but its expressive syntax pays off in readability once mastered. JMeter's GUI is approachable for beginners building simple HTTP tests, but complex scenarios with conditional logic, correlation, and data-driven iterations become harder to maintain as XML test plans grow.

Protocol support varies meaningfully. JMeter remains the broadest, with built-in samplers for JDBC, JMS, FTP, SOAP, and more, which matters if you are testing legacy enterprise systems. k6 and Gatling both support HTTP/1.1, HTTP/2, and WebSockets well, with gRPC support available through extensions or plugins. Locust is primarily HTTP-focused by default, though custom clients can be written in Python to simulate other protocols.

When protocol needs are narrow (mostly REST or GraphQL APIs over HTTP), the scripting language and developer experience should usually outweigh protocol breadth as the deciding factor.

Reporting, CI Integration, and Scaling Load Generation

Reporting quality differs sharply between tools. Gatling generates polished, self-contained HTML reports with response time percentiles, requests-per-second graphs, and error breakdowns, with no extra configuration needed. k6 outputs structured JSON or can stream metrics to external systems like InfluxDB or Prometheus for live dashboards, which suits teams running load tests as part of continuous delivery. JMeter's native reporting is functional but basic, often requiring the Backend Listener plugin or a separate reporting tool (such as Grafana) to get dashboard-quality visuals. Locust provides a real-time web UI showing requests per second and response times during a run, plus CSV export for post-run analysis.

For CI/CD integration, k6 and Gatling both offer first-class command-line interfaces designed to fail a pipeline based on thresholds, which makes them easier to wire into automated gates than JMeter's GUI-first design (though JMeter does support headless/non-GUI mode for CI use).

Scaling load generation beyond a single machine is another differentiator: k6 and Gatling support distributed execution through paid enterprise offerings or cloud services, while Locust's distributed mode (one master, many workers) is open source and simple to configure for teams that need to generate high volumes of traffic across multiple machines without licensing costs. JMeter supports distributed testing too, via its remote testing (master-slave) setup, though coordination can be more manual.

import http from 'k6/http';
import { check, sleep } from 'k6';

export const options = {
  vus: 50,            // 50 virtual users
  duration: '2m',     // run for 2 minutes
  thresholds: {
    http_req_duration: ['p(95)<500'], // 95% of requests under 500ms
    http_req_failed: ['rate<0.01'],   // error rate under 1%
  },
};

export default function () {
  const res = http.get('https://example.com/api/products');
  check(res, {
    'status is 200': (r) => r.status === 200,
  });
  sleep(1);
}

A k6 load test that ramps 50 virtual users against an API endpoint for two minutes, asserting that 95% of responses stay under 500ms and the error rate stays below 1%. The thresholds cause k6 to exit with a failing status code if violated, which makes it easy to fail a CI build on performance regressions.

from locust import HttpUser, task, between

class ApiUser(HttpUser):
    wait_time = between(1, 3)

    @task(3)
    def browse_products(self):
        self.client.get('/api/products')

    @task(1)
    def checkout(self):
        self.client.post('/api/checkout', json={'item_id': 42, 'qty': 1})

A Locust test file defining a user that browses products three times as often as it checks out, with a random wait of 1 to 3 seconds between tasks. Run with `locust -f locustfile.py --users 100 --spawn-rate 10` to simulate 100 concurrent users ramping up at 10 per second.

Tips

  • Start with a small, representative script and validate it against a staging environment before scaling up virtual users, so you catch scripting errors before they distort your results.
  • Match think-time and pacing (wait_time, sleep) to real user behavior rather than hammering endpoints back-to-back, or your results will overstate the load a real system would see.
  • Version-control your load test scripts alongside application code so they stay in sync with API changes and can be reviewed like any other code.

Common pitfalls

  • Running the load generator on underpowered hardware and mistaking its own CPU or network saturation for the system under test's limits; monitor the load generator's resource usage, not just the target's.
  • Ignoring correlation and dynamic values (session tokens, CSRF tokens) in scripts, which causes every virtual user to replay the same stale token and produces artificially high error rates that don't reflect real traffic.

Designing Realistic Load Test Scenarios

A load test is only as useful as the scenario behind it. Hammering a single endpoint with identical requests tells you how that endpoint behaves in isolation, but production traffic rarely looks like that. Real users browse, search, add items to a cart, abandon flows halfway, and retry failed actions. A realistic load test models these journeys as weighted mixes of actions, not a single repeated call.

Building a traffic profile starts with understanding what your users actually do. Analytics data (page views, funnel completion rates, peak hours) tells you which journeys matter and in what proportion. If checkout represents a small fraction of traffic but search represents most of it, your virtual users should reflect that ratio rather than treating every journey as equally likely.

Parameterization matters just as much as journey modeling. If every virtual user searches for the same product or logs in with the same account, caches, connection pools, and database indexes behave unrealistically well. Varying test data, usernames, search terms, product IDs, forces the system to do the work it would do under real, varied traffic.

Finally, the shape of the test over time matters. A flat spike of full load from second one stresses different things than a gradual ramp. Structuring tests into ramp-up, steady-state, and ramp-down phases lets you separate "can the system absorb growing load" from "can it sustain load" from "does it recover cleanly." This section covers all three concerns in depth: journey modeling, data parameterization, and phase structuring.

Modeling User Journeys and Traffic Mix

Start by listing the distinct journeys your application supports: browsing, searching, logging in, checking out, uploading a file, and so on. For each journey, assign a realistic weight based on how often it actually happens, drawn from analytics or server logs rather than guesswork. A content site might run 70% read-only browsing, 20% search, and 10% account actions; an e-commerce checkout flow might be a small percentage of total traffic but disproportionately important to protect because failures there cost revenue directly.

Within a journey, add realistic pacing. Real users pause to read a page, think before submitting a form, or get distracted mid-flow. A test with zero think time between requests produces request rates no real audience generates and can make a perfectly healthy system look broken, or hide problems that only appear when connections linger open longer.

Also model failure and abandonment. Not every cart becomes an order; not every search leads to a click. Including a percentage of users who browse and leave, alongside users who complete the full journey, gives a more honest picture of concurrent load, since abandoned sessions still hold open connections, cached data, and partially written state.

A common mistake is testing only the happy path. Include journeys that exercise error handling too: invalid form submissions, expired sessions, out-of-stock items. These paths often carry hidden cost (extra database lookups, retries, logging) that a happy-path-only test will never surface.

Parameterizing Data and Structuring Load Phases

Caching, whether at the CDN, application, or database layer, can make a load test lie to you if every virtual user requests the same resource. The first request is slow, every subsequent one is served from cache, and your results look far better than reality. Parameterize test data: pull from a list of real or realistic usernames, product SKUs, search terms, or file sizes, and distribute them across virtual users so the system does the lookup and computation work it would do in production.

Be equally careful with write operations. If every virtual user tries to register the same email address or update the same record, you will hit artificial unique-constraint errors or lock contention that has nothing to do with real-world scalability. Generate unique identifiers per virtual user, often by combining a run ID with an iteration counter.

Structure the test timeline deliberately. A ramp-up phase that increases virtual users gradually (for example, over 5 minutes) reveals how the system behaves as load builds, and whether autoscaling or connection pools keep up. A steady-state phase at target load, held for a meaningful duration, shows whether performance degrades over time (memory leaks, connection exhaustion, log disk filling up). A ramp-down phase confirms the system releases resources cleanly rather than leaving them stuck.

Different test types need different phase shapes: a soak test holds steady-state for hours to catch slow leaks, while a spike test skips the gentle ramp entirely to see how the system handles a sudden surge.

import http from 'k6/http';
import { sleep, check } from 'k6';
import { randomItem } from 'https://jslib.k6.io/k6-utils/1.2.0/index.js';

export const options = {
  scenarios: {
    browsing: {
      executor: 'ramping-vus',
      exec: 'browse',
      startVUs: 0,
      stages: [
        { duration: '2m', target: 50 },  // ramp-up
        { duration: '5m', target: 50 },  // steady-state
        { duration: '1m', target: 0 },   // ramp-down
      ],
    },
    checkout: {
      executor: 'ramping-vus',
      exec: 'checkout',
      startVUs: 0,
      stages: [
        { duration: '2m', target: 10 },
        { duration: '5m', target: 10 },
        { duration: '1m', target: 0 },
      ],
    },
  },
};

const searchTerms = ['boots', 'jacket', 'tent', 'gloves', 'lantern'];

export function browse() {
  const term = randomItem(searchTerms);
  const res = http.get(`https://shop.example.com/search?q=${term}`);
  check(res, { 'status is 200': (r) => r.status === 200 });
  sleep(Math.random() * 3 + 1); // think time, 1-4s
}

export function checkout() {
  const userId = `${__VU}-${__ITER}`;
  const res = http.post('https://shop.example.com/api/orders', JSON.stringify({
    user: `loadtest-${userId}@example.com`,
    item: randomItem(searchTerms),
  }), { headers: { 'Content-Type': 'application/json' } });
  check(res, { 'order created': (r) => r.status === 201 });
  sleep(Math.random() * 2 + 0.5);
}

A k6 script defining two separate traffic scenarios with their own ramp-up, steady-state, and ramp-down stages: lightweight browsing with parameterized search terms and random think time, and a lower-volume checkout flow with per-user unique identifiers to avoid write conflicts.

Tips

  • Base journey weights and pacing on real analytics or server logs, not assumptions about how you think users behave.
  • Always include think time between requests; zero-delay loops create request rates that do not resemble real traffic.
  • Generate unique identifiers per virtual user for writes (orders, registrations) to avoid artificial constraint errors or lock contention.
  • Run steady-state long enough to catch slow degradation like memory growth or connection exhaustion, not just a brief burst.

Common pitfalls

  • Testing only the happy path: error handling, invalid input, and expired-session flows often carry hidden cost and should be included in the journey mix.
  • Reusing identical test data across virtual users: this lets caching mask real performance and can trigger false uniqueness conflicts on writes that would not occur with varied data.

Analyzing Results and Finding Bottlenecks

Running a load test is only half the job. The real value comes from reading the results correctly and turning raw numbers into an actionable diagnosis of where your system breaks down. A load test report typically gives you throughput (requests per second), response time percentiles (p50, p95, p99), error rates, and sometimes a timeline graph showing how these metrics evolved as load increased. Reading these in isolation tells you that something degraded, but not why.

To find the actual bottleneck, you need to overlay your load test timeline with application and infrastructure monitoring: CPU utilization, memory usage, garbage collection pauses, database query times, connection pool saturation, disk I/O, and network throughput. When latency rises, the goal is to find which resource hit a ceiling first, because that is almost always the root cause.

This section covers how to correlate load test output with system metrics, how to tell apart application-level bottlenecks (slow code, inefficient queries, lock contention) from infrastructure limits (CPU, memory, network, disk), and how to avoid common misreadings of the data. By the end, you should be able to look at a spike in p99 latency and know within minutes whether to look at your database, your application code, or your server capacity.

A disciplined approach treats every load test as an experiment: form a hypothesis about the bottleneck, gather evidence from logs and metrics, and confirm or reject it before changing anything. Guessing and tuning blindly wastes time and can mask the real problem.

Correlating Latency with Resource Saturation

The first step in root-causing a performance problem is lining up your load test's time axis with your monitoring dashboards' time axis. If response times start climbing at the 5-minute mark of a test, check what CPU, memory, and database metrics were doing at that exact moment.

A few patterns are common. If CPU utilization on the application servers climbs toward 100% right as latency rises, you likely have a CPU-bound bottleneck, often caused by inefficient computation, serialization overhead, or excessive logging. If memory usage grows steadily and garbage collection pauses lengthen, you may be looking at a memory leak or oversized object allocation per request. If database query latency rises while application CPU stays flat, the bottleneck has moved downstream: look at slow queries, missing indexes, or lock contention. If throughput plateaus while CPU, memory, and database all look healthy, the limit may be a fixed-size connection pool or thread pool capping concurrency before any physical resource is exhausted.

Network saturation is easy to miss because it rarely shows up as an obvious percentage like CPU does. Watch for rising TCP retransmits, growing socket queues, or bandwidth approaching the link's rated capacity. A practical habit is to tag every load test run with a unique identifier and label all dashboards, logs, and traces with that same identifier, so that correlating a test run to its exact metrics window is a matter of filtering by tag rather than eyeballing timestamps.

Distinguishing Application Bottlenecks from Infrastructure Limits

Not every slowdown means you need bigger servers. A large share of performance problems are application-level and get worse, not better, with more hardware. Learning to tell the two apart saves money and fixes the actual problem.

Application-level bottlenecks usually show a pattern where adding more CPU or memory to the host barely moves the needle, because the limiting factor is a single slow code path, a lock, a sequential loop, or an N+1 query pattern that does not parallelize. Profiling the application under load, using a language-appropriate profiler or distributed tracing, will usually point to a specific function or query that dominates response time regardless of available resources.

Infrastructure limits, by contrast, scale roughly linearly with hardware: add more CPU cores and throughput improves proportionally, or add database read replicas and query latency drops. If you double the instance size and performance doubles too, you were infrastructure-bound. If performance barely changes, go back to the code.

A clean way to separate the two is to run the same load test against a scaled-up environment and against the original environment with a code fix but no extra hardware. Whichever change moves the metrics tells you where the real bottleneck lived. Distributed tracing is especially useful here: a trace that shows 90% of request time inside a single downstream call to the database, regardless of load, points squarely at the application's query pattern, not at server capacity.

import http from 'k6/http';
import { check } from 'k6';
import { Trend } from 'k6/metrics';

const dbCallDuration = new Trend('checkout_latency_ms');

export const options = {
  stages: [
    { duration: '2m', target: 50 },
    { duration: '5m', target: 50 },
    { duration: '2m', target: 0 },
  ],
  thresholds: {
    'checkout_latency_ms': ['p(95)<800'],
    'http_req_failed': ['rate<0.01'],
  },
};

export default function () {
  const res = http.post('https://staging.example.com/api/checkout', JSON.stringify({ item: 'sku-123' }), {
    headers: { 'Content-Type': 'application/json' },
    tags: { run_id: 'loadtest-2024-05-01-01' },
  });
  dbCallDuration.add(res.timings.duration);
  check(res, { 'status is 200': (r) => r.status === 200 });
}

A k6 script that tags every request with a run_id and records a custom latency trend, making it easy to filter dashboards and logs to the exact window of this test run when correlating with CPU, memory, or database metrics.

# Query Prometheus for CPU and DB query latency during the test window
curl -s 'http://prometheus:9090/api/v1/query_range' \
  --data-urlencode 'query=rate(process_cpu_seconds_total{job="checkout-service"}[1m])' \
  --data-urlencode 'start=2024-05-01T10:00:00Z' \
  --data-urlencode 'end=2024-05-01T10:10:00Z' \
  --data-urlencode 'step=15s' | jq '.data.result'

A PromQL query run over the exact time range of a load test to pull CPU utilization for the service under test, which can then be plotted alongside the k6 latency trend to see whether rising latency lines up with CPU saturation.

Tips

  • Tag every load test run with a unique run ID and apply it to logs, traces, and metrics so correlating a performance dip to its cause does not depend on matching timestamps by eye.
  • Watch percentiles, not just averages: a healthy average can hide a p99 that is already unacceptable for a meaningful slice of users.
  • Re-run the same test after each fix with everything else unchanged, so you can confirm which change actually moved the metric instead of guessing.

Common pitfalls

  • Scaling up hardware before confirming the bottleneck is infrastructure-bound: if profiling shows one slow code path or query dominating response time, more CPU or memory often changes nothing.
  • Looking only at average response time: averages smooth over the slow outliers that matter most, so always check p95 and p99 alongside error rate and throughput.

Scaling Strategies and Continuous Performance Testing

A system that survives a load test once can still fail in production if the underlying scaling strategy is wrong or if nobody keeps testing it as the code changes. This section covers how applications absorb growing traffic, the infrastructure patterns that make scaling possible, and how to wire performance checks into a CI/CD pipeline so regressions are caught before they reach users.

Horizontal vs Vertical Scaling

Vertical scaling means giving a single instance more CPU, memory or faster disks. It is simple to apply but has a hard ceiling and usually requires downtime to resize. Horizontal scaling means running more instances behind a load balancer. It has no practical ceiling and can tolerate instance failure, but it demands that the application be stateless, or that state be externalized to a shared store such as a database or cache. Most modern systems favor horizontal scaling for the application tier and reserve vertical scaling for stateful components like a primary database, at least until read replicas or sharding are introduced.

Caching, Connection Pooling, Queueing and Backpressure

A cache in front of a slow or expensive resource (database query, external API, computed report) turns many requests into one. Connection pooling avoids the cost of establishing a new database or HTTP connection per request, which under load becomes a bottleneck of its own. When demand briefly exceeds capacity, a queue smooths the spike by holding requests until a worker is free. Backpressure is the discipline of refusing or slowing new work once a queue or pool is full, rather than accepting everything and collapsing under the weight. Without backpressure, a traffic spike that would have degraded gracefully instead causes a full outage.

Together these patterns, plus autoscaling driven by real metrics, let a system absorb variable load without being permanently over-provisioned, and continuous performance testing in CI/CD ensures that a code change does not quietly erase that capacity.

Autoscaling Configuration

Autoscaling adds or removes instances automatically based on observed load, so capacity tracks demand instead of being fixed at a guess. The two common triggers are resource-based (CPU or memory crossing a threshold) and request-based (queue depth, requests per second, or a custom application metric like active sessions). Resource-based triggers are easy to set up but react late: by the time CPU is at 80 percent, requests may already be queuing. Request-based or queue-depth triggers react earlier and map more directly to user experience, but need the application to expose that metric.

A good autoscaling policy sets both a minimum and a maximum instance count. The minimum avoids a cold start under a sudden spike; the maximum caps cost and protects downstream dependencies (a database can be scaled out in application servers but still choke if every new instance opens dozens of new connections to it). Scale-up should be fast and scale-down should be slow, to avoid oscillating instances up and down on noisy metrics, a pattern often called flapping.

Autoscaling must be load tested deliberately, not assumed to work from the dashboard. Run a load test that ramps traffic up over several minutes, confirm new instances actually register as healthy and start serving traffic before the queue backs up, then ramp down and confirm the scale-in does not drop in-flight requests. A policy that scales on CPU but takes three minutes to provision a new instance will not save a service from a spike that arrives in thirty seconds; the fix is either a faster-booting image, a lower threshold that scales earlier, or a buffer of warm standby instances.

Integrating Load Tests into CI/CD

Performance regressions are far cheaper to catch in a pipeline than after a release, but a load test cannot run the same way a unit test does: it takes minutes, needs a realistic environment, and its pass or fail criteria have to be a budget, not a single number. The usual pattern is to run a short, representative load test against a staging environment on every merge to the main branch, and a longer, fuller test on a schedule or before a major release.

Define the budget up front: a 95th percentile response time under a given number of virtual users, and an error rate ceiling. The pipeline step runs the test, parses the summary, and fails the build if the budget is breached, exactly like any other quality gate. Keep the test data and target environment stable between runs, otherwise a failure might reflect environment drift rather than a real regression, and a flaky pipeline erodes trust in the gate quickly.

Store each run's results so performance trends over time are visible, not just the last pass or fail. A gradual climb in response time across several merges is often more informative than any single threshold breach, since it can reveal a slow leak (an index that stopped being used, a cache that stopped hitting) well before it crosses the budget and blocks a release.

import http from 'k6/http';
import { check, sleep } from 'k6';

export const options = {
  stages: [
    { duration: '2m', target: 50 },   // ramp up
    { duration: '5m', target: 50 },   // hold steady load
    { duration: '2m', target: 0 },    // ramp down
  ],
  thresholds: {
    http_req_duration: ['p(95)<400'], // 95th percentile under 400ms
    http_req_failed: ['rate<0.01'],   // error rate under 1%
  },
};

export default function () {
  const res = http.get('https://staging.example.com/api/products');
  check(res, { 'status is 200': (r) => r.status === 200 });
  sleep(1);
}

A k6 script that ramps virtual users up and down while asserting response-time and error-rate budgets, suitable for running as a CI/CD pipeline step.

#!/usr/bin/env bash
set -e

k6 run --summary-export=summary.json load-test.js

P95=$(jq '.metrics.http_req_duration.values["p(95)"]' summary.json)
FAIL_RATE=$(jq '.metrics.http_req_failed.values.rate' summary.json)

echo "p95=${P95}ms fail_rate=${FAIL_RATE}"

if (( $(echo "$P95 > 400" | bc -l) )) || (( $(echo "$FAIL_RATE > 0.01" | bc -l) )); then
  echo "Performance budget breached"
  exit 1
fi

A CI pipeline step that runs the k6 test, extracts the key metrics with jq, and fails the build if either budget is exceeded.

Tips

  • Set autoscaling thresholds against the metric closest to user experience (queue depth or request latency) rather than CPU alone, since CPU often lags behind the real bottleneck.
  • Always define a minimum instance count so a scale-to-zero policy does not reintroduce a cold-start penalty on the next burst of traffic.
  • Run the same load test profile after every significant release so a gradual climb in response time is visible before it ever breaches the hard budget.

Common pitfalls

  • Scaling the application tier horizontally while leaving a single database instance as the only backend: every new instance opens its own connection pool, and the database becomes the real bottleneck under load.
  • Treating a load test's pass or fail as a single average response time: an average can hide a long tail of slow requests, so always gate on a percentile like p95 or p99 alongside the error rate.

Exercises

Exercise 1: Write and Run Your First k6 Load Test

In this exercise you will install k6 and write a load test script against a public demo API or a simple staging application you control. The goal is to practice defining stages (ramp-up, steady load, ramp-down), adding checks for correctness, and setting thresholds for latency and error rate. You will then run the test, read the summary output, and interpret whether it passed or failed against your thresholds. This exercise builds the muscle memory needed before tackling more complex, multi-step user journeys in later sections. Take your time to experiment with different virtual user counts and durations to see how throughput and latency change as load increases, and note the point at which latency starts climbing noticeably, since that is a hint at where saturation begins.

  1. Install k6 following its official documentation for your operating system.
  2. Pick a test target: either a public demo API endpoint that allows load testing, or a simple application you run locally or on a staging server you control.
  3. Write a k6 script with a stages configuration that ramps from 0 to 20 virtual users over 30 seconds, holds for 2 minutes, then ramps down.
  4. Add at least two check() assertions verifying the response status and a piece of expected content.
  5. Add thresholds for p95 latency (for example under 500ms) and error rate (for example under 1%).
  6. Run the script with the k6 command-line tool and capture the summary output.
  7. Re-run the test with double the virtual users and compare the latency percentiles and throughput between the two runs.

Expected outcome: You will have a working k6 script that ramps load up and down, a summary report showing throughput, latency percentiles, and error rate, and a written comparison of how doubling virtual users affected p95 latency and throughput, with an observation about whether the system scaled linearly or showed early signs of saturation.

Exercise 2: Diagnose a Bottleneck Using Monitoring Alongside a Load Test

This exercise combines a load test with basic system monitoring to practice bottleneck diagnosis, a core skill in performance testing. You will run a load test against an application while simultaneously watching resource metrics such as CPU, memory, and (if applicable) database connection count. The aim is to connect a rise in latency or error rate in the load test output to a specific saturated resource, rather than guessing. This mirrors real-world performance investigations, where the load testing tool tells you something is wrong and your monitoring tells you where.

  1. Set up a simple application (or use an existing staging environment) along with a basic monitoring view, such as a terminal running top or htop, or a hosting provider's resource dashboard.
  2. Write or reuse a load test script that steadily increases virtual users over several stages, for example 10, then 50, then 100, then 200.
  3. Run the load test while watching the monitoring output, noting at which virtual user count CPU, memory, or another resource approaches its limit.
  4. Record the latency percentiles and error rate at each stage from the load test tool's output.
  5. Identify the virtual user count at which latency begins to rise sharply or errors begin to appear, and correlate it with the resource metric that was nearing its limit at that same point.
  6. Write a short summary describing the suspected bottleneck and one concrete change that might relieve it, such as adding a cache, increasing a connection pool size, or adding another application instance.

Expected outcome: A short written report pairing load test output (throughput, latency percentiles, error rate at each stage) with monitoring data, correctly identifying the resource that saturated first and proposing one realistic mitigation for the bottleneck found.

Quiz

1. A team wants to find the exact point at which their system's response times become unacceptable as traffic grows. Which type of test is most appropriate?

  1. Load test
  2. Stress test
  3. Soak test
  4. Spike test
Show answer

B. Stress test

A stress test deliberately increases traffic beyond expected levels to find the point where the system degrades or breaks, which is exactly what is needed to identify the exact threshold of unacceptable response times.

2. Why is average latency often a misleading metric on its own?

  1. It is too difficult to calculate accurately
  2. It can hide a slow tail experience affecting a meaningful share of users even when the overall average looks good
  3. It only works for GET requests, not POST requests
  4. It always equals the p99 value in well-designed systems
Show answer

B. It can hide a slow tail experience affecting a meaningful share of users even when the overall average looks good

An average can look healthy while a meaningful percentage of requests are actually very slow, which is why percentiles such as p95 and p99 are reported alongside or instead of the average to reveal the tail experience.

3. A load test shows stable, low latency even as virtual users increase, but the error rate climbs steadily. What does this most likely indicate?

  1. The system is handling the load perfectly and the error rate is irrelevant
  2. The test script has a bug and should be discarded
  3. The system may be shedding load by rejecting requests rather than slowing them down, which still represents real failures
  4. The latency measurement tool is broken
Show answer

C. The system may be shedding load by rejecting requests rather than slowing them down, which still represents real failures

Low latency alongside a rising error rate often means the system is rejecting or dropping requests to protect itself rather than queuing them, which keeps reported latency low but still fails real users; throughput, latency, and error rate must always be read together.

4. What is the key architectural requirement that typically must be met for an application to scale horizontally?

  1. The application must run on a single, very powerful machine
  2. The application must be stateless, or externalize state to a shared store, so any instance can serve any request
  3. The application must avoid using a load balancer
  4. The application must only support one concurrent user at a time
Show answer

B. The application must be stateless, or externalize state to a shared store, so any instance can serve any request

Horizontal scaling adds more machines behind a load balancer, which only works smoothly if the application does not rely on state stored on a single instance; session data or caches typically need to be externalized to a shared store.

5. In a k6 script, what is the purpose of including sleep() calls between requests in a scenario?

  1. To slow down the test tool so it uses less CPU on the test runner
  2. To mimic realistic user think time, since real users pause between actions rather than firing requests instantly back to back
  3. To satisfy a required syntax rule in every k6 script
  4. To reduce the number of virtual users needed for the test
Show answer

B. To mimic realistic user think time, since real users pause between actions rather than firing requests instantly back to back

Real users read pages, think, and type between actions; omitting pauses between requests produces unrealistically extreme concurrency that does not reflect genuine usage patterns, so sleep() calls are added to model think time.

Related docs

All courses