Appearance
Benchmark & Performance Validation Framework
pgbench Index Benchmarking
Order matters: baseline first, change second. Each -f file is one script; -f file@weight mixes them. Variables must be defined with \set (:scale is the scaling factor: with only -f scripts pgbench reports it as 1 unless you pass -s N, so pass the same -s as in pgbench -i -s).
bash
# Step 1: data. Scale 100 = 10M rows in pgbench_accounts (about 1.5 GB)
pgbench -i -s 100 mydb
# Step 2: workload files, 70% read / 20% update / 10% insert
cat > select.sql <<'SQL'
\set aid random(1, 100000 * :scale)
SELECT abalance FROM pgbench_accounts WHERE aid = :aid;
SQL
cat > update.sql <<'SQL'
\set aid random(1, 100000 * :scale)
\set delta random(-5000, 5000)
UPDATE pgbench_accounts SET abalance = abalance + :delta WHERE aid = :aid;
SQL
cat > history.sql <<'SQL'
\set aid random(1, 100000 * :scale)
\set bid random(1, 1 * :scale)
\set tid random(1, 10 * :scale)
\set delta random(-5000, 5000)
INSERT INTO pgbench_history (tid, bid, aid, delta, mtime) VALUES (:tid, :bid, :aid, :delta, CURRENT_TIMESTAMP);
SQL
# Step 3: baseline (run once to warm the cache, then keep the following runs)
pgbench -s 100 -c 10 -j 2 -T 60 -M prepared -r --random-seed=7 \
-f select.sql@70 -f update.sql@20 -f history.sql@10 mydb
# Step 4: apply the change (run it off-peak; CONCURRENTLY avoids blocking writers)
psql -d mydb -c "CREATE INDEX CONCURRENTLY idx_accounts_abalance ON pgbench_accounts(abalance)"
psql -d mydb -c "ANALYZE pgbench_accounts"
# Step 5: repeat Step 3 unchanged, then compare (see the next section for significance)update.sql modifies abalance, so an index on abalance prevents HOT updates: expect the 20% write share to get slower. That is exactly what a mixed workload is for.
Latency, not just throughput. -r prints per-statement average latency; the summary has average and standard deviation only, no percentiles. For p99 write a per-transaction log (-l) and compute it:
bash
pgbench -s 100 -c 20 -j 4 -T 60 -r -l --log-prefix=pgb -f select.sql@70 -f update.sql@20 -f history.sql@10 mydb
cat pgb.* | awk '{print $3 / 1000}' | sort -n | awk '{a[NR] = $1} END {print "p99 ms:", a[int(NR * 0.99)]}'Measured with the exact scripts above (PostgreSQL 18 in Docker, scale 100, -c 20 -j 4 -T 60 -r -l, 0 failed transactions): 24 300 TPS, 1 459 023 logged transactions, p50 0.2 ms, p99 3.894 ms (from the awk above), max 236.5 ms; per script average latency select 0.175 ms, update 2.316 ms, history insert 2.215 ms. pgbench -i -s 100 took 12.7 s and the database was 1503 MB. In the log, column 3 is the latency in microseconds, so $3 / 1000 is correct.
Output sample from a real run (scale 1, 4 clients, 5 s, Docker on a dev machine; do not compare with your hardware):
text
SQL script 2: /tmp/u.sql
- weight: 20 (targets 20.0% of total)
- 28389 transactions (19.9% of total)
- latency average = 0.316 ms
- latency stddev = 0.119 ms
- statement latencies in milliseconds and failures:
0.316 0 UPDATE pgbench_accounts SET abalance = abalance + :delta WHERE aid = :aid;Statistical Significance Testing
Why a small improvement can be noise: the numbers below are an illustration, not a measurement.
text
Baseline run 1: 10000 TPS Index run 1: 10100 TPS (+1%)
Baseline run 2: 9950 TPS Index run 2: 10150 TPS
Run-to-run spread of the baseline: about 50 TPS (0.5%); effect (mean of 2 runs): about 150 TPS (1.5%) -> ratio 3, not conclusiveApproach: run baseline n times and the changed system n times (n >= 5), then use Welch's t statistic t = (mean2 - mean1) / sqrt(s1^2/n1 + s2^2/n2) with sample standard deviations (divide by n-1). With 5 runs per side |t| must exceed about 2.3 (df 8, equal variances) up to 2.8 (df 4, very unequal variances) for p < 0.05 (two-sided); beyond that also ask whether the effect size matters. Fix everything else between the two series (same data, same cache state, same --random-seed, no other load).
bash
#!/bin/bash
# Requires: a database with pgbench -i data (see the previous section); psql and pgbench on PATH.
set -euo pipefail
DB=${DB:-mydb}; N=5; T=30
cat > q.sql <<'SQL'
\set v random(-5000, 5000)
SELECT count(*) FROM pgbench_accounts WHERE abalance = :v;
SQL
psql -d "$DB" -qc "DROP INDEX IF EXISTS idx_accounts_abalance" -c "ANALYZE pgbench_accounts"
run() { for i in $(seq "$N"); do pgbench -c 4 -j 2 -T "$T" -n -f q.sql "$DB" | awk '/^tps/ {print $3}'; done; }
run > baseline.txt
psql -d "$DB" -qc "CREATE INDEX idx_accounts_abalance ON pgbench_accounts(abalance)" -c "ANALYZE pgbench_accounts"
run > indexed.txt
awk 'NR == FNR {a[NR] = $1; na = NR; next} {b[FNR] = $1; nb = FNR}
END {
for (i = 1; i <= na; i++) ma += a[i]; ma /= na
for (i = 1; i <= nb; i++) mb += b[i]; mb /= nb
for (i = 1; i <= na; i++) va += (a[i] - ma)^2; va /= (na - 1)
for (i = 1; i <= nb; i++) vb += (b[i] - mb)^2; vb /= (nb - 1)
t = (mb - ma) / sqrt(va / na + vb / nb)
printf "baseline %.0f +/- %.0f tps | indexed %.0f +/- %.0f tps | change %+.1f%% | Welch t = %.1f\n", ma, sqrt(va), mb, sqrt(vb), (mb - ma) / ma * 100, t
}' baseline.txt indexed.txtMeasured with the script above unchanged, T=30, N=5, scale 100 (10M rows), 4 clients, abalance = :v on pgbench_accounts: baseline (sequential scan) 3.44 4.77 4.90 2.80 1.59 TPS, indexed 5786 6209 7355 7056 8533 TPS; the script printed baseline 4 +/- 1 tps | indexed 6988 +/- 1070 tps | Welch t = 14.6. The awk, the psql -d calls and the file layout all run as written; the huge change is the sequential scan of 10M rows versus an index lookup, not a typical result.
Sample output (scale 1, T=3 s, Docker on a dev machine; the read-only query benefits hugely, a real mixed workload would not):
text
baseline 1061 +/- 49 tps | indexed 43381 +/- 1244 tps | change +3988.7% | Welch t = 76.0Why a custom query file: the default pgbench script never touches an index you add on another column, so it would measure nothing.
Warm Cache vs Cold Cache
Cold and warm runs measure different things, so report both. Real percentages depend entirely on your hardware and data size; the figures below are one measurement on a dev machine, not a rule.
bash
# COLD run (test server only, never on production)
sudo systemctl restart postgresql # empties shared_buffers
sync && echo 3 | sudo tee /proc/sys/vm/drop_caches # Linux: also empties the OS page cache
pgbench -c 5 -T 30 mydb # first run after the restart = cold
# WARM run
pgbench -c 5 -T 30 mydb # repeat until the TPS stops climbing, then recordtext
Measured (PostgreSQL 18 in Docker Desktop, scale 100 = 1503 MB, shared_buffers 128MB, `pgbench -S -c 4 -T 10`): first run after `docker restart` 12 313 TPS (OS cache warm), after `docker restart` plus `sync; echo 3 > /proc/sys/vm/drop_caches` 14 993 TPS (the command returned 0 inside a `--privileged` container on Docker Desktop), warm repeats 29 000 to 37 000 TPS. Cold is about 2 to 3 times slower here (ratio changes with hardware), not 10 times: the dev VM storage is fast, so the ratio is hardware-specific.
Random read: typically tens of microseconds to about 1 ms on SSD vs. several ms or more on HDD (varies by hardware; measure with fio or pg_test_timing), which is why cold runs can differ by an order of magnitude- Gain only when warm: the index helps steady state, not the first minutes after a restart or failover.
- Gain only when cold: the index saves I/O but the data fits in RAM in production, so the effect may disappear. Check
pg_prewarmorshared_bufferssizing before drawing conclusions. - A fixed
sleepafterpg_ctl restart(for example 5 s) is not a reliable wait for the server to accept connections: usepg_isreadyin a loop.
Lab vs Production Differences
Why a 20x win in the lab can shrink in production: cache residency, concurrency, storage, selectivity and the write ratio all differ. The table below is a checklist, not measured data.
| Typical lab | Typical production | |
|---|---|---|
| Data vs RAM | table fits in shared_buffers / page cache | table far larger than RAM, cache misses |
| Concurrency | one session | many sessions, lock and WAL contention |
| Storage | local NVMe | network storage, shared IOPS |
| Predicate | very selective (a few rows) | often matches many rows (random heap I/O dominates) |
| Writes | none | every extra index costs insert/update time |
Note: a selective equality lookup stays fast with an index at any table size; what shrinks the benefit is low selectivity, cold cache and write overhead, not index size.
sql
-- PostgreSQL 18 (psql): runnable as is; raise the row count to match your RAM
CREATE TABLE test_data (id BIGINT, value INT, data TEXT);
INSERT INTO test_data
SELECT g, (random() * 10000)::INT, repeat('x', 100) FROM generate_series(1, 1000000) g;
ANALYZE test_data;
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM test_data WHERE value = 5000; -- Seq Scan
CREATE INDEX idx_value ON test_data(value);
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM test_data WHERE value = 5000; -- Bitmap/Index ScanMake the lab look like production: restore a masked copy of production data (never raw PII), use the real RAM size and concurrency.
bash
# TOO SMALL: pgbench -i -s 1 creates about 15 MB (100k accounts rows)
pgbench -i -s 1 db
# CLOSER TO PRODUCTION: scale 1000 creates about 15 GB (100M accounts rows)
# Measured: pgbench -i -s 1000 -q gave a 15 GB database (pgbench_accounts 13 GB), about 2-3 minutes on a laptop-class Docker VM; check free disk first (the data directory also grows with WAL).
pgbench -i -s 1000 db
# Or restore a masked dump of real data
pg_dump -Fc prod_db > prod.dump # run on a replica, mask/anonymise PII before sharing
pg_restore -d test_db prod.dumpAnti-Patterns in Benchmarking
1. Measuring a single query. EXPLAIN ANALYZE SELECT * FROM orders WHERE id = 1; taking 0.1 ms looks fast, but at 100k executions per second a 10% gain is 100k x 0.01 ms = 1 CPU-second per second. Measure TPS and latency under load (pgbench, or pg_stat_statements before/after), not one query.
2. Not controlling the cache between runs. Run 1 (cold) 100 ms, run 2 (warm) 95 ms does not mean a 5% improvement; the cache state changed, not the system. Compare like with like: warm vs warm after the same number of warm-up runs, or cold vs cold (see the previous section).
bash
# Cold start on a TEST server only (empties shared_buffers and the Linux page cache)
sudo systemctl restart postgresql
sync && echo 3 | sudo tee /proc/sys/vm/drop_caches3. Unrealistic data distribution. Uniform random values hide skew: production usually has a hot value (one status covering most rows), and the planner chooses different plans for it.
sql
-- PostgreSQL 18 (psql): 80% pending / 15% active / 5% completed, runnable as is
CREATE TABLE orders_dist AS
SELECT g AS id,
CASE WHEN r < 0.80 THEN 'pending'
WHEN r < 0.95 THEN 'active'
ELSE 'completed' END AS status
FROM (SELECT generate_series(1, 1000000) AS g, random() AS r) x;
SELECT status, round(count(*) * 100.0 / 1000000, 1) AS pct FROM orders_dist GROUP BY status ORDER BY pct DESC;
-- pending 80.0, active 15.0, completed 5.0 (measured)Draw random() once per row. The tempting form CASE WHEN random() < 0.8 ... WHEN random() < 0.95 ... draws a second independent number and yields about 80 / 19 / 1 (measured), not 80 / 15 / 5.
4. Ignoring maintenance cost. A new index speeds SELECT but slows INSERT/UPDATE/DELETE and can block HOT updates. Benchmark a mix that matches your real read/write ratio (measure it in pg_stat_database: tup_returned + tup_fetched vs tup_inserted + tup_updated + tup_deleted).
5. Single-session benchmarking. One user can show a 50% gain that becomes much smaller under lock and WAL contention. Always test at your real concurrency, for example pgbench -c 20 -j 4 (20 clients, 4 worker threads).
Phải nhớ
- Baseline first, change second; same data, same cache state, same
--random-seed, at least 5 runs per side and a Welch t statistic, not one run. - Read
pgbenchoutput astps = ... (without initial connection time); extract it withawk '/^tps/ {print $3}', and use a custom-fworkload so the change you test is actually exercised. - Lab numbers do not transfer: label them with hardware and data size, report warm and cold, and include the write cost.