← Blog
A cream mechanical tally counter with an orange wheel and a plum lever on a lavender background.
Published on
2026-11-30

Benchmark PostgreSQL on a CPU VM with pgbench

How many clients can your PostgreSQL instance serve before a customer’s order history feels slow? A transactions-per-second figure answers half the question. The other half is how long each database request takes when several arrive together.

We used pgbench to compare one client with four on two reads: PostgreSQL’s built-in account balance lookup and a query that returns a customer’s ten most recent orders. The same procedure works on a CPU VM. The figures below come from a local PostgreSQL 18.6 instance, with the load generator on the same Windows machine.

PostgreSQL includes pgbench to measure database performance under concurrent client sessions. A pgbench transaction is one execution of a benchmark script. With the built-in read-only script, that means one balance lookup. When you compare transactions per second across tests, keep the script and dataset fixed so the unit of work stays the same.

PostgreSQL performance with one and four pgbench clients

WorkloadClientsTransactions/sMean latency (ms)P95 (ms)
Account balance116,6060.0600.117
Account balance453,8560.0740.121
Order history113,8150.0720.143
Order history444,9920.0890.143

For order history, four clients processed about 3.26 times as many transactions per second as one. Mean latency rose from 0.072 to 0.089 ms. The sampled p95 rounded to 0.143 ms in both cases. Four active sessions let the database complete more work at once, even though the average request took longer.

Each figure is the median of three ten-second trials. P95 is the latency at or below which 95% of sampled successful transactions finished. We calculated it separately for each trial using a 10% log sample. All twelve timed trials had zero failed transactions. These short runs illustrate how to read the measurements. For a sizing decision, use trials lasting at least several minutes and check variation between runs.

Create a disposable database and check the transaction count

Use PostgreSQL 18 client tools and a dedicated test server. The commands below use Bash. Set PGHOST, PGPORT and PGUSER for that server and configure authentication before you start. Create a new database for initialization because pgbench -i recreates its benchmark tables. PostgreSQL’s pgbench reference.

createdb bench_fixture && pgbench -i -s 1 bench_fixture

Scale 1 creates 100,000 account rows. The built-in select-only script, -S, retrieves a randomly chosen account’s balance. First, hold the amount of work fixed. The -t option counts transactions per client, so one client doing 80 and four clients doing 20 each both request 80 transactions.

pgbench -n -M prepared -j 1 -S -c 1 -t 80 bench_fixture
pgbench -n -M prepared -j 1 -S -c 4 -t 20 bench_fixture

Both checks completed 80 of 80 transactions. Keep the query protocol and generator threads fixed when varying clients: these commands use prepared statements, one generator thread and persistent connections. The subsequent timed runs let faster configurations finish more work during the same interval.

Add a query with the shape of your application

An account lookup by primary key is cheap. An order-history page asks a different question. Save this as orders.sql and run psql -X -v ON_ERROR_STOP=1 -d bench_fixture -f orders.sql. The fixture creates 100,000 orders spread evenly over 1,000 customers. Its index lets PostgreSQL find one customer’s latest rows in order.

CREATE TABLE orders (
    order_id integer PRIMARY KEY,
    customer_id integer NOT NULL,
    total_cents integer NOT NULL
);
INSERT INTO orders
SELECT n, 1 + (n - 1) % 1000, 100 + n % 9900
FROM generate_series(1, 100000) AS g(n);

CREATE INDEX orders_customer_recent ON orders (customer_id, order_id DESC);
ANALYZE orders;

Save the following as recent-orders.sql. The first line is a pgbench command. It picks a customer for each transaction so every request does not hit the same ten rows.

\set customer random(1, 1000)
SELECT order_id, total_cents
FROM orders
WHERE customer_id = :customer
ORDER BY order_id DESC
LIMIT 10;

Warm up, then repeat both workloads

Save this Bash script as measure.sh. It warms each client count for three seconds before the measured runs and reverses the order in the middle trial. The client requests another transaction as soon as its previous one finishes. That makes the test useful for comparing concurrent database sessions. An application with bursts or idle time needs its own traffic pattern.

set -eu
workload=("$@")
# Pass -S for the balance lookup or -f recent-orders.sql for order history.
for clients in 1 4; do
  pgbench -n -M prepared -j 1 -c "$clients" "${workload[@]}" -T 3 bench_fixture
done
for trial in 1 2 3; do
  order=(1 4)
  if [ "$trial" = 2 ]; then order=(4 1); fi
  for clients in "${order[@]}"; do
    pgbench -n -M prepared -j 1 -c "$clients" "${workload[@]}" \
      -T "${SECONDS_PER_TRIAL:-10}" -l --sampling-rate=0.1 \
      --log-prefix="trial-$trial-$clients" bench_fixture
  done
done

Use fresh log directories for each workload so samples from different runs stay separate. -l writes transaction logs, and --sampling-rate=0.1 samples roughly one transaction in ten. On a candidate VM, set SECONDS_PER_TRIAL=180 in the environment for three-minute trials.

mkdir balance-logs orders-logs
(cd balance-logs && bash ../measure.sh -S)
(cd orders-logs && bash ../measure.sh -f ../recent-orders.sql)

The local test used an AMD Ryzen 7 7840HS with eight cores and 16 logical processors, about 62 GiB of usable RAM and a local NVMe SSD. The database occupied approximately 32 MiB and PostgreSQL reported 128 MB of shared buffers. The test reused the same data after warm-up, with no cache reset. This setup favors cached reads. It gives little information about disk-bound reads or the cost of committing writes.

Use latency to decide whether more throughput helps

Read the failed-transaction count before interpreting TPS. Then compare the average latency printed by pgbench with the slow end of the distribution. In the standard per-transaction log, the third field is elapsed time in microseconds. Save this as p95.py to calculate the nearest-rank p95 in milliseconds for one trial.

"""Calculate nearest-rank p95 in ms from successful transactions in standard pgbench logs."""
from math import ceil
from pathlib import Path
import sys

def latency_sample(paths):
    values = []
    for path in paths:
        with path.open(encoding="utf-8") as stream:
            for line in stream:
                columns = line.split()
                if len(columns) >= 6 and columns[2].isdigit():
                    values.append(int(columns[2]))
    if not values:
        raise ValueError("No successful transactions found in these pgbench logs")
    values.sort()
    return len(values), values[ceil(0.95 * len(values)) - 1] / 1000

if __name__ == "__main__":
    paths = [Path(p) for p in sys.argv[1:]]
    count, p95 = latency_sample(paths)
    print(f"{count} sampled transactions, p95 {p95:.3f} ms")
python p95.py orders-logs/trial-1-4.*

Before comparing VM sizes, set a budget for the database part of a real request. For example, if order history needs a database p95 under 20 ms, check whether each size meets that budget at the expected concurrency and throughput. Use the same dataset, parameters, storage class and client location on both. A slow query at one client is a reason to inspect its execution plan before adding cores.

To evaluate CPU instances on Compute with Hivenet, take a representative query and dataset to the instance you are considering. Place the load generator where the application will run, repeat the trials, and compare the results with the budget. If managing the database itself is still an open question, the PostgreSQL hosting guide covers that choice.

Your next workload belongs on Hivenet.

Pick one AI, compute, or storage workload and see the difference for yourself. Spin it up in minutes, or let our team map your fastest path to production.