Performance Engineering and Load Testing

Measurable performance objectives, latency percentiles, five kinds of test, testing the real business workflow with integrity checks, and finding the bottleneck first.

  • Advanced
  • About 23 minutes
  • Includes an exercise and a knowledge check

The concept "It works" is not a performance requirement

Finance says a transaction search takes seven seconds; engineering says the API returns successfully. Both are true, and the experience is poor. Define performance with measurable objectives, agreed with Apex:

OperationExample target (to agree)
Payment ingestion APIp95 under 500 ms
Transaction searchp95 under 1 second
Exception detailsp95 under 1 second
Settlement processing95% of standard batches completed within 15 minutes
Dashboard availability99.9% monthly, within the agreed scope
On the left, a historical photo of an aircraft model in a NACA wind tunnel. On the right, 1,000 example requests, 940 at 100 ms and 60 at 5 seconds: the average is 394 ms, p50 is 100 ms, and p95 and p99 are both 5,000 ms, showing one request in twenty waits five seconds. Five kinds of test: load, stress, spike, soak and capacity. A test that is fast but loses or duplicates a payment has failed.
Test it in the wind tunnel first, and read the percentiles, not the average.

The average of that example is 394 ms, which sounds fine; p95 is 5 seconds. p50 is the median, p95 the time within which 95% of requests finish, p99 within which 99% finish. Track them per endpoint and operation, never as one application-wide number.

Say exactly how the numbers were measured. Use a steady window, such as 30 minutes after a 10-minute warm-up, and leave out the ramp-up and ramp-down. Compute each percentile from every individual request in that window, sorted by duration: with the nearest-rank method, p95 is the request at position 95% × n, rounded up (the 950th of 1,000). Never average percentiles across minutes or servers, because the average of two p95 values is not a p95. Report the integrity checks in the same table as the timings: a run that loses or duplicates a payment has failed, however fast it was.

Test what matters Load test the business workflow

  1. Payment event ingestion, including duplicate deliveries.
  2. Settlement file ingestion.
  3. Reconciliation processing and exception creation.
  4. Transaction search, exception investigation and audit history.

Check correctness as well as speed: count payments in and out, look for duplicates, and compare reconciliation results with the expected outcome. A system that handles 10,000 events a second but silently loses one has failed. Then find the bottleneck with evidence (indexes, slow queries, connections, locks, serialization, thread pools, consumer limits, large files, chatty frontend calls) before buying more infrastructure.

Here is what that looks like as a script. It drives the payment notification API at the module's planning rates: 11 events a second (the average), 56 (the peak) and 112 (a burst at twice the peak). It signs every request the way the frozen contract requires, mixes in exact repeats, and counts every answer the contract does not allow.

javascriptpayment-load-test.js (k6)

// Load test for the payment notification API (fictional Apex Auto Finance), for k6.
// Normal, peak and burst, with exact repeats mixed in. Run against a test environment only:
//   k6 run -e BASE_URL=https://test.example -e PROVIDER_A_TEST_KEY=... -e RUN_ID=r42 --out json=r42.json payment-load-test.js
import http from 'k6/http';
import { check } from 'k6';
import crypto from 'k6/crypto';
import exec from 'k6/execution';
import { Counter } from 'k6/metrics';

const BASE_URL = __ENV.BASE_URL; // a test environment, never production
const KEY = __ENV.PROVIDER_A_TEST_KEY; // the test signing key, from the secret store
const RUN = __ENV.RUN_ID; // every transaction ID in this run starts with LT-<RUN>-

const acceptedNew = new Counter('accepted_new'); // 202: a new payment was stored
const repeatsOk = new Counter('repeats_ok'); // 200 with the same ingestionId
const wrongAnswers = new Counter('wrong_answers'); // anything the contract does not allow

export const options = {
  scenarios: {
    normal: { executor: 'constant-arrival-rate', rate: 11, timeUnit: '1s', duration: '10m',
      preAllocatedVUs: 20, maxVUs: 100 },
    peak: { executor: 'constant-arrival-rate', rate: 56, timeUnit: '1s', duration: '40m', startTime: '10m',
      preAllocatedVUs: 80, maxVUs: 300 },
    burst: { executor: 'constant-arrival-rate', rate: 112, timeUnit: '1s', duration: '5m', startTime: '50m',
      preAllocatedVUs: 150, maxVUs: 500 },
  },
  thresholds: {
    'http_req_duration{scenario:peak}': ['p(95)<500'], // a quick gate; the report uses the steady window
    wrong_answers: ['count==0'],
  },
};

let last = null; // this virtual user's last accepted payment, for exact repeats

export default function () {
  const repeat = last !== null && Math.random() < 0.05;
  const body = repeat
    ? last.body
    : JSON.stringify({
        providerTransactionId: `LT-${RUN}-${exec.vu.idInTest}-${exec.vu.iterationInInstance}`,
        loanAccountId: `LN-${10000 + (exec.vu.idInTest % 5000)}`,
        amount: '425.50',
        currency: 'USD',
        paymentStatus: 'SUCCESS',
        transactionTimestamp: new Date().toISOString(),
      });
  const ts = new Date().toISOString(); // every attempt, including a repeat, is signed again
  const res = http.post(`${BASE_URL}/api/v1/payment-notifications/provider-a`, body, {
    headers: {
      'Content-Type': 'application/json',
      'X-Apex-Timestamp': ts,
      'X-Apex-Signature': crypto.hmac('sha256', KEY, `${ts}.${body}`, 'hex'),
    },
    tags: { name: 'notify' },
  });

  if (repeat) {
    const same = check(res, {
      'repeat: 200 with the same ingestionId': (r) => r.status === 200 && r.json('ingestionId') === last.ingestionId,
    });
    if (same) repeatsOk.add(1);
    else if (res.status !== 429 && res.status !== 503) wrongAnswers.add(1);
  } else if (res.status === 202) {
    acceptedNew.add(1);
    last = { body, ingestionId: res.json('ingestionId') };
  } else if (res.status !== 429 && res.status !== 503) {
    wrongAnswers.add(1); // 429 and 503 are allowed under burst; the provider would retry
  }
}

A starting script, not a result: no output is shown because it runs in Apex's test environment, never in production. Syntax checked on November 22, 2026 (tools/fde/m08/payment-load-test.js).

sqlintegrity.sql: run it after the load test

-- After the load test: did every accepted payment arrive exactly once, with exactly one event?
-- Tables as built in Module 07. Replace r42 with the run ID, then compare stored_payments
-- with the accepted_new counter from the run.
SELECT
    COUNT(*)                                           AS stored_payments,
    COUNT(*) - COUNT(DISTINCT provider_transaction_id) AS duplicate_rows,
    (SELECT COUNT(*)
       FROM outbox_event AS o
       JOIN payment_transaction AS q ON q.id = o.aggregate_id
      WHERE q.provider_id = 'PROVIDER_A'
        AND q.provider_transaction_id LIKE 'LT-r42-%'
        AND o.event_type = 'PaymentReceived')          AS payment_events
FROM payment_transaction
WHERE provider_id = 'PROVIDER_A'
  AND provider_transaction_id LIKE 'LT-r42-%';

Uses the Module 07 tables. Checked on a small fictional sample in SQLite 3.54 (tools/fde/m08/integrity.sql).

The run passes only if all of these hold: p95 for ingestion under 500 ms in the steady peak window, computed from the raw results rather than the threshold line; no wrong answers; stored_payments equal to accepted_new; duplicate_rows equal to 0; and payment_events equal to stored_payments. Responses of 429 and 503 during the burst are allowed, because the provider would retry them, but report how many there were.

Worksheet

Load-test report

A script is a plan; this report is the result. Fill a row only with something you measured, and name the evidence: the k6 summary file, the dashboard, the query. A row you could not measure stays empty and says why. Answers stay in this browser; Download CSV saves them.

ItemMeasured resultEvidence
Environment and its size
Build and version tested
Test data (synthetic, how much)
Workload: rates and durations run
Steady window used for percentiles
Ingestion p50, p95, p99
Error rate; 429 and 503 count
accepted_new from the run
stored_payments and duplicate_rows
payment_events
Bottleneck found, with its evidence
Verdict against the agreed targets
Your answers stay in this browser

Practice Run three experiments

Practical exercise

Exercise 06: the performance report

Run normal load, peak load, and a burst followed by recovery.

  1. Record throughput, p50, p95 and p99, and error rate.
  2. Record CPU, memory, database connections and latency.
  3. Record queue depth, oldest message age and processing completion time.
  4. Run the data integrity checks and write up the bottleneck and recommendations.
Show a sample finding
  • Burst: p95 for search rose to 3.8 s while settlement processed. Cause: a full scan on received_timestamp ranges. Fix: a composite index; p95 back to 420 ms in the rerun.
  • Integrity: 400,000 sent, 400,000 stored, 0 duplicates, reconciliation counts equal to the expected file.

2 questions

Check your understanding

1. Why report p95 rather than the average?
2. Which test runs for hours to find leaks?
Answer every question to submit.

What you can do now

  • Define percentile-based targets.
  • Design load tests around the business workflow.
  • Find bottlenecks with evidence.