A database performance test usually fails long before anyone reads the numbers. The dataset fits in RAM when production does not, the first run hits a cold cache and the second a warm one, two settings change between runs, and the report gives one average TPS figure with no p99 and no error count. The result looks precise and answers nothing. This guide covers the method: define the question, pick the test type, size the data against memory, warm the cache, choose the workload, and capture p95 and p99 latency, errors, resource use and wait events, with pgbench and sysbench commands and a report template. For a catalogue of the tools themselves, read database load testing tools compared; this post is about how to use any of them.
- Write the question and the pass criterion before the first run, for example "p99 under 50 ms at 1,200 TPS on the new instance class".
- Size the dataset against memory the way production is sized. A dataset that fits in the buffer pool tests the CPU and the cache, not the disks.
- Warm the cache, then measure for several checkpoint intervals. Repeat each run at least three times and compare medians.
- Record per-interval p95 and p99 latency, the error count, OS metrics and database wait events for the same window. One average TPS figure is not a result.
- Change one variable per run, and keep the commands, settings and raw logs with the report so anyone can re-run it.
Scope and review date: November 2026. This guide covers pgbench as documented for PostgreSQL 19, pg_stat_statements, pgreplay 1.5, sysbench 1.0.20 against MySQL 8.4, and the MySQL 8.4 Performance Schema. Commands and defaults were checked against the vendor documentation and source on 25 November 2026. They were not run in a lab, so the sample output in this post is illustrative, and you should rehearse each command on a test server first.
What question should a database performance test answer?
Every useful test starts with a sentence you can mark true or false. "Benchmark the new server" is not a question. "Can the r7g.2xlarge replacement serve the current peak write mix at a p99 under 50 ms?" is. Most database performance testing falls into four questions, and each one decides the test type, the workload and the pass criterion.
| Question | Typical trigger | What you compare | Pass criterion shape |
|---|---|---|---|
| Capacity: how much load can it take? | Growth forecast, launch, sale event | Throughput and latency as concurrency rises | Highest load where p99 stays under target with no errors |
| Regression: did a release make it slower? | Application release, schema change, new index | Same workload, before and after | p95 and p99 within a stated tolerance of the baseline |
| Upgrade or migration validation | Major version upgrade, engine or cloud move | Old and new platform, same data and workload | No query family slower than the agreed tolerance; no new errors |
| Configuration change | Memory, checkpoint, connection or storage settings | One setting changed, everything else fixed | Measured difference larger than the run-to-run spread |
Write the target numbers down before the first run. If you decide what "good" means after seeing the results, the test only confirms whatever you hoped for.
Which test types do you need: baseline, load, stress, soak or spike?
The test types differ in the shape of the load over time, not in the tool. The same pgbench or sysbench binary runs all five; you change concurrency, rate and duration.
| Test type | Load shape | Answers |
|---|---|---|
| Baseline | Current production load, steady | What normal looks like, as the reference for every later run |
| Load | Expected peak, steady | Does it meet the latency target at peak? |
| Stress | Concurrency or rate raised in steps until it breaks | Where is the knee, and what fails first? |
| Soak | Normal or peak load, held | Does anything degrade with time: bloat, memory, log growth, autovacuum? |
| Spike | Sudden jump from normal to several times normal, then back | Does the connection pool, cache or queue recover? |
A stress test is a loop over concurrency levels. Run each step long enough to settle, and record each step to its own log so you can plot latency against load afterwards.
# Stress test: step client count, one log per step (PostgreSQL)
for c in 8 16 32 64 128; do
pgbench -h db-test -U bench -c "$c" -j 8 -T 600 -P 10 -M prepared \
bench > "stress_c${c}.log" 2>&1
sleep 60 # let checkpoints and autovacuum settle between steps
doneInterpretation: throughput normally rises with clients, flattens, and then falls while latency climbs. The step where p99 crosses your target is the usable capacity, which is usually well below the step with the highest TPS.
Most tools run a closed loop: each client sends its next transaction as soon as the last one returns, so a slow server quietly lowers the offered load. For latency targets, also run at a fixed rate. pgbench's -R option schedules transactions at a target rate, and the pgbench documentation notes that the reported latency then includes schedule lag, so a server that cannot keep up shows it in the numbers.
Closed-loop and fixed-rate runs compared
Switch modes to see what each one tells you about the same server
Closed loop
| Property | Closed loop (no rate limit) |
|---|---|
| pgbench option | -c 64 -T 600 |
| sysbench option | --threads=64 --rate=0 |
| Offered load | Falls when the server slows down |
| Latency figure | Service time only; queueing is hidden |
| Best for | Finding maximum throughput |
Fixed rate
| Property | Fixed rate |
|---|---|
| pgbench option | -c 64 -T 600 -R 1200 |
| sysbench option | --threads=64 --rate=1200 |
| Offered load | Stays at the target rate |
| Latency figure | Includes time spent waiting to be sent (schedule lag) |
| Best for | Checking a latency target at a known traffic level |
Rule: find the ceiling with a closed loop, then prove the latency target with a fixed-rate run at the traffic you expect.
How production-like does the test data need to be?
The ratio of data to memory decides what you are measuring. If the working set fits in shared_buffers or the InnoDB buffer pool, reads never touch storage and the test measures CPU and lock behaviour. If production reads from disk, your test must too. Match three things: total data size, the size of the hot working set, and the memory settings.
-- PostgreSQL: data size and memory on production and on the test server
SELECT pg_size_pretty(pg_database_size(current_database())) AS db_size,
current_setting('shared_buffers') AS shared_buffers,
current_setting('effective_cache_size') AS effective_cache_size;
-- Cache hit ratio over the stats window, per database
SELECT datname, blks_hit, blks_read,
round(100.0 * blks_hit / nullif(blks_hit + blks_read, 0), 2) AS hit_pct
FROM pg_stat_database
WHERE datname = current_database();Interpretation: if production runs at a 97 percent hit ratio and the test shows 100 percent, the test dataset is too small. Grow it, or shrink the test server's memory in proportion, until the hit ratios are close.
On MySQL, compare information_schema.tables sizes and innodb_buffer_pool_size the same way.
For synthetic tests, set the generator's size explicitly. In pgbench, scale 1 creates 100,000 rows in pgbench_accounts, and the documentation advises a scale at least as large as the largest client count, or you mostly measure contention on the pgbench_branches rows. In sysbench, the OLTP scripts take --tables and --table-size (the source sets defaults of 1 table and 10,000 rows, which fit in memory on any server). Check the size after loading rather than estimating it.
# pgbench: 10,000,000 account rows, then check the real size
pgbench -i -s 100 -h db-test -U bench bench
psql -h db-test -U bench -d bench -c \
"SELECT pg_size_pretty(pg_database_size('bench'));"
# sysbench: 16 tables of 10,000,000 rows each on MySQL
sysbench oltp_read_write --db-driver=mysql \
--mysql-host=db-test --mysql-user=bench --mysql-password="$PW" \
--mysql-db=sbtest --tables=16 --table-size=10000000 --threads=16 prepareInterpretation: pick the scale from the measured size, not from a rule of thumb. If the synthetic data is still far from production in shape (row width, index count, skew), treat the results as hardware and configuration numbers only, and use a restored production copy for anything about your queries.
How do you warm the cache before measuring?
A database that has just restarted reads almost everything from disk, so the first minutes of any run measure cache filling. Unless the question is about restart behaviour, warm the cache first and keep warm-up time out of the measured window.
-- PostgreSQL: load a hot table and its primary key into shared_buffers
CREATE EXTENSION IF NOT EXISTS pg_prewarm;
SELECT pg_prewarm('orders'); -- default mode 'buffer'
SELECT pg_prewarm('orders_pkey');
-- MySQL 8.4: reload the saved buffer pool page list and check progress
SET GLOBAL innodb_buffer_pool_load_now = ON;
SHOW STATUS LIKE 'Innodb_buffer_pool_load_status';Interpretation: pg_prewarm returns the number of blocks it read. On MySQL, the buffer pool dump and load is on by default at shutdown and startup and covers 25 percent of the most recently used pages; the status variable reports a "Finished at" timestamp when the load is complete.
The simplest warm-up is a run of the same workload that you throw away. sysbench has --warmup-time, which executes events with statistics disabled before the measured run. pgbench has no warm-up option, so run a short unmeasured pass first, or drop the first intervals from the -P output.
If per-interval latency is still falling at the end of the warm-up, the warm-up was too short. Extend it until the curve is flat.
Synthetic or replayed production traffic: which workload should you run?
Synthetic workloads (pgbench's built-in TPC-B-like script, sysbench oltp_read_write) are repeatable and easy to scale, which makes them good for hardware and configuration questions. They do not run your queries, so they cannot answer a regression or upgrade question. For those, build the workload from production.
Build a weighted script from the production query mix
On PostgreSQL, pg_stat_statements gives the normalised statements, call counts and execution times. It must be in shared_preload_libraries, and by default it tracks 5,000 distinct statements.
-- Top statements by total time, with each one's share of calls
SELECT queryid,
left(query, 80) AS query,
calls,
round(100.0 * calls / sum(calls) OVER (), 1) AS pct_of_calls,
round(mean_exec_time::numeric, 2) AS mean_ms,
round(total_exec_time::numeric, 0) AS total_ms
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 20;Interpretation: the top 10 to 20 statements by total time usually cover most of the load. Turn each one into a pgbench script file with realistic parameter values, and use pct_of_calls as the weight.
# lookup_order.sql (one statement family from pg_stat_statements)
cat > lookup_order.sql <<'EOF'
\set id random(1, 20000000)
SELECT id, status, total FROM orders WHERE id = :id;
EOF
# Run three scripts weighted by their share of production calls
pgbench -h db-test -U bench -c 32 -j 8 -T 1800 -P 10 -M prepared -r \
-f lookup_order.sql@70 -f list_orders.sql@25 -f place_order.sql@5 appdbInterpretation: the @weight suffix sets how often each script is picked, and -r prints average latency per statement at the end, so you can see which statement family moved. Uniform random() keys spread reads evenly; if production traffic is skewed toward recent rows, choose keys to match, because skew changes the cache hit ratio.
On MySQL, the same data comes from events_statements_summary_by_digest, whose timer columns are in picoseconds, or from a slow query log captured with long_query_time = 0 and summarised with pt-query-digest.
-- MySQL 8.4: production statement mix with p95 and p99 per digest
SELECT LEFT(DIGEST_TEXT, 80) AS digest,
COUNT_STAR AS calls,
ROUND(AVG_TIMER_WAIT / 1e9, 2) AS avg_ms,
ROUND(QUANTILE_95 / 1e9, 2) AS p95_ms,
ROUND(QUANTILE_99 / 1e9, 2) AS p99_ms
FROM performance_schema.events_statements_summary_by_digest
WHERE SCHEMA_NAME = 'appdb'
ORDER BY SUM_TIMER_WAIT DESC
LIMIT 20;Replay captured traffic for upgrade and migration tests
Replay runs the real statements, in the real order per session, with the real think time between them. pgreplay reads a PostgreSQL log written with log_statement = 'all', connection and disconnection logging, and preferably csvlog, and replays it against a clone of the database taken immediately before the log starts.
# Parse a csvlog capture into a replay file, then replay it at normal speed
pgreplay -f -c -o peak_hour.replay postgresql-peak.csv
pgreplay -r -h db-test -p 5432 -s 1 peak_hour.replayInterpretation: -s is a speed factor; values above 1 fast-forward. The pgreplay manual warns that 500 users at double speed is not the same as 1,000 users at normal speed, so use speed-up as a rough stress signal, not a capacity number. pgreplay does not replay COPY data, and it cannot reproduce the exact ordering between sessions, so some lock waits in a replay are artefacts.
Capturing and replaying a production workload
The clone must match the moment the capture starts, or replayed statements hit missing or changed rows
Cost: log_statement = 'all' writes every statement to the log. Capture a bounded window, watch log volume and disk space, and switch it off afterwards.
What should you measure during the run?
Measure five things for the same time window, at the same interval (10 seconds works for most runs):
- Throughput: transactions or queries per second, per interval, not only the run total.
- Latency percentiles: p95 and p99 per interval. Averages hide the slow tail that users notice.
- Errors: failed transactions, deadlocks, serialization failures, connection errors. A run that got faster by failing more is not faster.
- Resource use: CPU, I/O wait, read and write IOPS, network, and the load generator's own CPU.
- Wait events: what sessions are waiting on, which tells you why the numbers are what they are.
Ask the load generator for interval reports and the right percentile. pgbench prints a progress line every -P seconds, and with -l --aggregate-interval it writes per-interval latency sums, minimums and maximums to a log file. sysbench reports the 95th percentile by default; set --percentile=99 for p99 and --histogram for the full latency distribution.
# pgbench: progress every 10 s plus a per-interval log for plotting
pgbench -h db-test -U bench -c 32 -j 8 -T 1800 -P 10 -M prepared \
-l --aggregate-interval=10 --log-prefix=run03 bench
# sysbench: p99 per 10 s interval, warm-up excluded, histogram at the end
sysbench oltp_read_write --db-driver=mysql \
--mysql-host=db-test --mysql-user=bench --mysql-password="$PW" \
--mysql-db=sbtest --tables=16 --table-size=10000000 \
--threads=32 --time=1800 --warmup-time=300 --report-interval=10 \
--percentile=99 --histogram --rand-type=uniform run | tee run03.logInterpretation: set --rand-type explicitly. The sysbench 1.0 README lists special as the default, while the current source uses uniform, so two builds can run different key distributions under the same command line. pgbench's progress line shows average latency and standard deviation, not percentiles; for p95 and p99, write a per-transaction log with -l (add --sampling-rate on long runs) and compute them from that file.
sysbench interval reports and final summary
Illustrative output in the sysbench 1.0 format, interval lines wrapped to fit; the numbers are not measured results
Read the intervals: the 30 s line shows a p99 jump with no errors, the usual sign of a checkpoint or background flush. The final p99 averages it away, so plot the interval lines.
Capture server-side metrics in parallel, on the database host and on the load generator, with timestamps you can line up with the interval reports.
# On the database host: OS metrics every 10 s for the whole run
vmstat -t 10 > vmstat_run03.log &
iostat -xmt 10 > iostat_run03.log &
# PostgreSQL: sample wait events of active sessions every 10 s
while sleep 10; do
psql -h db-test -U bench -d bench -Atc "
SELECT now()::time(0), coalesce(wait_event_type,'CPU'),
coalesce(wait_event,'-'), count(*)
FROM pg_stat_activity
WHERE state = 'active' AND pid <> pg_backend_pid()
GROUP BY 1, 2, 3 ORDER BY 4 DESC;"
done > waits_run03.log &
# MySQL: per-interval deltas of global status counters
mysqladmin -h db-test -u bench -p"$PW" -r -i 10 extended-status \
> mysql_status_run03.log &Interpretation: a session with no wait event is labelled "CPU". The wait types are listed in the PostgreSQL monitoring documentation; Lock points at row or table locks, LWLock at internal contention, and IO at storage. Also reset pg_stat_statements (or truncate the MySQL digest table) just before the measured window and save a snapshot just after it, so per-statement numbers cover the run and nothing else.
How long should each run be, and how many times should you repeat it?
A run must be long enough to include the periodic work that production does. On PostgreSQL, that means several checkpoint cycles (the checkpoint_timeout default is five minutes) and at least one autovacuum pass on the busy tables. On MySQL, it means enough time for InnoDB's background flushing to reach a steady state. A 60-second run catches none of this, so its numbers are better than production will ever see.
Repeat each configuration at least three times, restoring the same starting state each time. Report the median run and the spread between the best and worst. A difference smaller than that spread is noise. Restore the dataset between repeats: write-heavy runs grow and bloat tables.
Change one variable at a time
If you upgrade the engine version and change shared_buffers in the same run, a result can be explained by either change, or by both cancelling out. Keep a run sheet that lists every variable (instance type, storage, engine version, each changed setting, dataset, workload file, concurrency, rate) and change exactly one per comparison.
Save the non-default settings with every run (SELECT name, setting FROM pg_settings WHERE source NOT IN ('default', 'override') on PostgreSQL, SHOW GLOBAL VARIABLES on MySQL) and diff the files between runs. If the diff shows more than the one setting you meant to change, the comparison is not valid.
One repeatable test run, start to finish
Repeat steps 2 to 7 for every run; only the variable in step 1 changes between comparisons
-
Record the question and the single variable
Write the pass criterion and the one setting or version under test in the run sheet.
-
Restore the starting dataset
Same snapshot or same
pgbench -iscale every time, so bloat from the last run does not carry over.pgbench -i -s 100 -h db-test -U bench bench -
Save settings and versions
Dump non-default settings and the engine version next to the run's logs.
-
Warm the cache
Run the workload unmeasured, or prewarm, until per-interval latency is flat.
-
Start metric capture
vmstat, iostat, wait-event sampling and a statement-statistics reset, all with timestamps.
psql -h db-test -U bench -d bench \ -c "SELECT pg_stat_statements_reset();" -
Run the measured workload
Interval reports on, the right percentile set, raw logs kept.
pgbench -c 32 -j 8 -T 1800 -P 10 \ -l --aggregate-interval=10 bench -
Snapshot statement statistics and stop capture
Save
pg_stat_statementsor the MySQL digest table, then stop the background collectors.
Main risk: skipping step 2. Without the same starting state, repeats drift as tables bloat, and you end up comparing data growth instead of the change under test.
How do you read the results and decide pass or fail?
Read the results in this order, and stop at the first check that fails:
- Was the run valid? Errors near zero, the load generator's CPU below saturation, the cache hit ratio close to production, and the planned rate actually reached (pgbench reports late and skipped transactions under
-Rand--latency-limit). - Is the difference real? Compare medians across repeats. If the spread between repeats overlaps the difference between configurations, you have no result yet; run more repeats or longer runs.
- Does it meet the criterion? Check p95 and p99 against the target for every interval, not only the summary. A run that passes on the summary but fails for two minutes every checkpoint does not pass.
- Why? Line the latency spikes up with wait events and OS metrics. A p99 spike with
IOwaits and highawaitin iostat is storage; a spike withLockwaits is contention in the workload; flat latency with 100 percent CPU means more CPU or cheaper queries. - Which statements moved? Compare per-statement mean and total time from the two statement snapshots; one slower query family tells you more than a small change in overall TPS.
What goes in a database performance test report?
A good report lets someone who was not there trust the result and re-run it. Keep it to one page, and attach the raw logs and exact command lines.
[question]
statement = Can PostgreSQL 18 on the new instance class serve current peak at p99 < 50 ms?
pass_criterion = p99 < 50 ms in every 10 s interval at 1,200 TPS fixed rate; error rate 0
[environment]
database = engine, version, instance class, storage type and provisioned IOPS
settings = attached diff of non-default settings (settings_run*.txt)
[dataset]
source = masked production snapshot of 2026-11-20 / pgbench scale 100
size = measured database size; memory ratio to production
[workload]
type = baseline | load | stress | soak | spike
mix = script files and weights, or replay capture window
concurrency = clients, threads, fixed rate or closed loop
duration = measured seconds, warm-up seconds, repeats
[results]
throughput = median and range across repeats
latency = p95 and p99 median and range; worst interval
errors = count and type
waits = top wait events during the worst interval
[verdict]
pass_fail = pass | fail | inconclusive, against the stated criterion
explanation = what limited the result, with evidenceInterpretation: "inconclusive" is a valid verdict. It is better to report that the run-to-run spread was larger than the difference than to pick the better number and call it a win.
Frequently asked questions
What is database performance testing?
Database performance testing is running a controlled workload against a database to answer one measurable question, such as capacity, regression after a release, or validation of an upgrade or configuration change. It records throughput, latency percentiles, errors, resource use and wait events for the same window, and compares them against a pass criterion written before the test started.
What is the difference between load testing and stress testing a database?
A load test holds the expected peak traffic steady and checks whether latency and errors stay within target. A stress test raises concurrency or rate in steps until the database stops meeting the target, to find where the knee is and what fails first. Run the load test to sign off a release and the stress test to plan capacity.
How long should a database benchmark run?
Long enough to include the background work production does: on PostgreSQL several checkpoint cycles and at least one autovacuum pass on busy tables, on MySQL a steady state of InnoDB flushing. That is usually tens of minutes after warm-up, not seconds. Soak tests run for hours. Repeat each configuration at least three times and compare medians.
Should I test with synthetic data or a copy of production?
Use synthetic pgbench or sysbench data for hardware and configuration questions, because it is repeatable and easy to scale. Use a masked production copy with a workload built from pg_stat_statements, the MySQL digest table or a replayed log for regression, upgrade and migration questions. Either way, match the data-to-memory ratio of production.
Key takeaways
- Start from a question with a written pass criterion; the question picks the test type, the dataset and the workload.
- Match production's data-to-memory ratio and warm the cache, or the test measures the wrong layer.
- Use synthetic workloads for hardware and settings, and production-derived or replayed workloads for regressions, upgrades and migrations.
- Capture per-interval p95 and p99, errors, OS metrics and wait events together, then explain results with waits, not guesses.
- Change one variable per comparison, repeat at least three times from the same starting state, and attach raw logs and commands to the report.
Database performance testing with JusDB
JusDB's database performance optimization team can help you plan a performance test around a specific decision, such as an instance change, a major version upgrade or a migration: define the question and pass criterion, build a workload from your production statement statistics, and set up the metric capture.
The team can also review results you already have, line up latency spikes with wait events and resource data, and turn the findings into a ranked list of query, index and configuration changes to test next.
Related reading
- Database load testing tools compared: the tool catalogue that pairs with this method.
- pgbench: PostgreSQL benchmarking for configuration validation
- sysbench MySQL benchmarking: OLTP workloads and performance baselines
- pgbench documentation (PostgreSQL)