How pgbench benchmarking PostgreSQL answers the go-live question
pgbench is the PostgreSQL client that generates repeatable load and measures throughput and latency, so you can see how a new cluster or an upgraded one behaves before users depend on it. Its value depends on matching the test to the real workload: a benchmark that runs a different mix of reads, writes, transactions and connections than production answers a question nobody asked. Teams usually need this before go-live, before a major version upgrade, and after changes to hardware, storage, memory settings or connection pooling, because each of these changes the numbers that matter.
A benchmark can show whether the system meets a target under a specific, documented load, whether latency stays stable as concurrency rises, and whether a configuration change moved results in the expected direction. It cannot prove that production will behave the same way. Data volume, cache state, network path, background jobs such as autovacuum and backups, and application query patterns all shift the outcome. Before running anything, write down the target transaction rate, the concurrency you expect at peak, the read and write ratio, and the latency percentiles your service levels depend on. Confirm those numbers with the application owners and the historical metrics from your current system, not from memory. Then decide what a pass looks like, so the result cannot be reinterpreted after the fact.
Which pgbench settings to set and when each fits
This table compares the main pgbench options, from initialization scale to latency reporting, and shows what each one changes in the result. Read each row as a decision: choose the setting that matches the question your test must answer, then confirm the option names against the help output for your PostgreSQL major version.
| Option | When it fits | What it changes in the result |
|---|---|---|
| Scale for initialization (-i, -s) | Sizing the test data to match the working set you expect in production, so cache and disk behavior resemble go-live | Larger scale raises table size and I/O pressure; a scale that fits in memory measures CPU and locking, not storage |
| Clients (-c) | Stepping up concurrent sessions to find where throughput flattens or latency climbs | More clients add contention and queueing; compare results at several client counts rather than one |
| Threads (-j) | Spreading client work across CPU cores on the load generator when one thread becomes the bottleneck | Threads do not add database load; if the generator is saturated, results reflect the client host, not PostgreSQL |
| Duration (-T) | Time-based runs for steady-state measurement, long enough to pass warm-up and checkpoints | Gives comparable windows across runs; short runs can hide checkpoint and autovacuum effects |
| Transaction count (-t) | Fixed-work comparisons where each run must execute the same number of transactions | Run length varies with speed, so total elapsed time becomes the output to compare |
| Custom script (-f) | Replaying your own query mix, parameter distributions and transaction boundaries instead of the built-in TPC-B-like test | Results reflect your workload only if the script matches real statements; the built-in test is a generic baseline |
| Protocol mode (-M) | Matching how your driver talks to PostgreSQL, such as simple or prepared statements | Protocol choice changes parse and plan overhead, so differences between drivers can distort upgrade comparisons |
| Progress reporting (-P) | Watching a long run for stalls, errors or throughput collapse as it happens | Adds periodic output only; it does not change the measured throughput in a meaningful way |
| Per-statement latency (-r) | Finding which statement in a custom script causes latency spikes or uneven response times | Reports latency per statement, which helps locate slow queries; confirm how it interacts with your PostgreSQL major version |
What the built-in TPC-B-like test measures and where it misleads
The default pgbench workload is a TPC-B-like test of short transactions that touch a small set of tables. Each transaction picks a row at random, adjusts a balance in an accounts table, updates a matching teller and branch, and writes a history record. The pattern is simple and fixed, which is its value: when you run the same scale and the same client count against two servers, two configurations or two major versions, the differences you see come from the system underneath rather than from a changing workload. That makes the default test a reasonable instrument for comparing hardware, checking that a new shared_buffers value or storage layout moved throughput in the expected direction, and confirming that a planned upgrade did not regress basic write performance.
The same fixed pattern is why the results cannot be read as a forecast of your application. Your queries will rarely match four single-row statements per transaction. Your tables will have different row widths, more or fewer indexes, and foreign keys that change write cost. Real data is skewed: a few customers, products or tenants generate most of the reads and writes, which pgbench's uniform random selection does not reproduce. Real applications also hold connections differently, using long-lived pools, idle sessions, reporting queries and background jobs that compete for the same buffers and I/O. Before you trust a number, ask the team who owns the application to list its top ten statements by frequency and the table sizes they touch, then confirm with them whether the default test exercises any of those paths. If it does not, treat the default result as a hardware and configuration baseline, not as proof of capacity for your workload.
Use the default run to answer narrow questions, and record what it cannot answer. Keep the scale factor, client count, duration and PostgreSQL settings identical between runs, and write down the version and host details so a later comparison is valid. Plan for the test to be repeated on a custom script that reflects your workload, which the next section covers, before any go-live or major upgrade decision. Confirm the exact pgbench options for your PostgreSQL version against the PostgreSQL documentation for upgrade planning, and in the pgbench reference for your release, since the tool's flags and built-in scripts change between versions.
How to run a pgbench baseline before go-live
This sequence turns a one-off pgbench run into a repeatable baseline, with recorded settings, measured variation and results you can compare against after go-live or an upgrade.
Provision a matching test environment
The platform team builds a test environment whose CPU, memory, storage, operating system, network path and PostgreSQL configuration match production as closely as the budget allows. Record every difference that remains, such as a smaller disk or a different storage class, because each one limits how far the results apply. The step is done when the team can list those differences in writing and the client-side load generator sits on its own host, not the database server. Confirm the storage type and filesystem with the infrastructure owner before any run starts.
Record the version and baseline settings
Before loading any data, capture the exact PostgreSQL version, the output of the relevant settings from pg_settings, the operating system and kernel version, and the pgbench version used. Save the postgresql.conf and any overrides, including shared_buffers, work_mem, max_connections and the checkpoint and WAL settings. The step closes when this record is stored with the test plan, so a later run can be compared against exactly the same conditions.
Initialize data at a chosen scale
Run pgbench with the -i flag to create the standard tables and load them at a scale factor the team picks in advance, and record that scale factor. Choose a size that is larger than the memory available for caching so the test reflects disk reads as well as buffer hits, and check the result. Confirm the data size with a query on the pgbench tables and compare it with the expected size for the chosen scale. Run ANALYZE or VACUUM after loading so the planner statistics are current.
Check the host before measuring
Before any measured run, confirm that the database host is not swapping, that no other workload is competing for CPU, disk or network, and that the client machine has enough headroom not to become the bottleneck. Use operating system tools to sample memory, swap, load and disk utilization during a short idle period. The step is done when the readings are recorded and show a quiet host. If another job starts during a run, mark that run invalid rather than averaging it in.
Run a warm-up and timed runs
Start with a warm-up run whose results are discarded, so caches and connections settle. Then run timed tests at several client counts, using the -c and -j options to set clients and threads, and keep the duration and the built-in or custom script identical across counts. Log throughput and latency for each run, and use the --log or --progress options when you need per-transaction or per-interval detail. The step closes when each client count has a complete timed result with its settings recorded.
Repeat runs to measure variation
Repeat the timed runs for each client count several times, and compare the spread of results. A baseline built from one run cannot tell you whether a later difference is real or just noise. Note the range of throughput and the range of latency percentiles across repeats, and flag any run that departs sharply from the others for review. The step is done when the team can state how much a result varies between runs at each client count.
Store results with the configuration used
Save the raw pgbench output, the latency and throughput summaries, host metrics, the settings record and the exact commands together in version control or the team's document store. Label each result set with the PostgreSQL version, scale factor, client counts and date. The step closes when a second engineer can rerun the same commands and reproduce the setup, which is what makes the baseline useful for comparing go-live readiness or a later upgrade.
Repeat the same test for upgrades
For a major upgrade, run the same environment, data, scale factor, client counts and script on the old and the new major version, using the same hardware and the same data. PostgreSQL 18 changes I/O behavior with asynchronous I/O, so the new version's results on your storage and workload can differ from the old version's in either direction. Benchmark the new version rather than assuming it will be faster. Confirm that the settings on both sides are equivalent or that every difference is documented before comparing results.
Choosing client and thread counts for each test goal
A capacity test asks how much work the server can complete before it stops getting faster. To answer it, step the client count (-c) upward across a range and record throughput (transactions per second) and latency at each step. Thread count (-j) only needs to be high enough that pgbench's own worker threads do not limit the load, so it is usually set well below -c and spread across the client machine's cores. The useful output is a curve, and the point where throughput levels off is the knee. Past the knee, additional clients mostly wait in queues for CPU, locks or I/O, so latency climbs while throughput barely moves.
- Start low and step up: Run a sequence of client counts on a fixed schedule and keep the duration and scale factor identical across runs.
- Find the knee: Plot throughput and p95 latency against
-c. The ceiling is where throughput gains flatten while latency keeps rising. - Keep threads modest: Set
-jso that each pgbench thread drives several clients without saturating a core on the client host. - Watch the server, not just pgbench: Record CPU, disk wait and lock waits during each step so you can name the resource that caps throughput.
- Treat the ceiling as a comparison point: Production sizing should stay below it with headroom, so the ceiling tells you how much margin you have rather than what to run at.
Before relying on the result, confirm that the curve is repeatable across at least two runs on the same hardware.
A go-live test should use the concurrency you expect at peak, not the highest concurrency the server can absorb. Start from the number of application connections that can be active at the same moment, which is often lower than the total connections configured in the pool. Set -c to that figure, or to a documented peak estimate supplied by the application owners, and set -j so the load generator runs on separate cores from the database. Run long enough for caches to warm and checkpoints to occur, because short runs flatter the result.
- Use peak active sessions: Count concurrently active sessions at peak from application or pooler metrics, not total configured connections.
- Match the pool: If PgBouncer or another pooler sits in front of the database, benchmark through it so the server sees the same session count as production.
- Include a margin run: Repeat the test at a higher client count to show how the system behaves when peak is exceeded.
- Run for steady state: Discard the warm-up period and include at least one checkpoint cycle in the measured window.
- Record what the target was: Write down the expected peak and the acceptable latency before the run, so the result is judged against a stated goal.
Ask the application team to confirm the peak concurrency figure in writing before the test, since a wrong input makes the result meaningless.
A regression check compares the old and new versions under identical conditions, so the client and thread settings must be frozen. Choose a client count from the existing production curve, ideally a point just below the knee, and use it for both the source and target versions. Changing -c or -j between runs turns a comparison into a measurement of the harness. Run each version several times, on the same hardware class and with the same configuration except for settings that the upgrade itself requires. A difference that appears only at high concurrency may be real, so include one run near the ceiling as well as one at normal load.
- Freeze the harness: Keep
-c,-j, duration, scale factor and the pgbench script identical for both versions. - Compare at a fixed load point: Use a concurrency level taken from the production curve so the comparison reflects everyday operation.
- Add one high-load run: Include a run near the knee to expose contention changes that a light load would hide.
- Repeat before concluding: Multiple runs per version show the spread, so a small difference is not mistaken for a regression.
- Keep the client host out of the way: Confirm the load generator's CPU stays well below saturation in both runs, otherwise the comparison measures the client.
Verify that the target version's planner statistics and settings match what you intend to ship, since those change results independently of the engine itself.
A single-session test measures the time one client waits for each transaction when nothing else is competing for the server. It answers how fast an individual operation can be, which matters for interactive users and for batch jobs that run serially. Use -c 1 and a single thread (-j 1), because any additional client introduces queueing that the result would then include. Latency here reflects the cost of the query path, the network round trip between the client and server, and the commit cost, so place the client on a network path that resembles production. Read the average and the tail together, since a few slow transactions can hide behind a good mean.
- Use one client and one thread: Set
-c 1and-j 1so no queueing is measured. - Place the client realistically: Run the test from a host with the same network distance to the database as the application servers.
- Read the tail: Report percentile latency along with the average, because checkpoints and autovacuum affect the slow end.
- Run long enough: Collect enough transactions to make the percentiles stable, and discard the warm-up period.
- Separate it from capacity: Do not present a single-session figure as evidence of how many users the system can serve.
Confirm the network latency between the client and the server first, since at this scale it can account for much of the measured time.
Writing custom pgbench scripts that mirror your workload
A custom pgbench script is only as useful as its match to what your application actually sends to the database, so the first job is to capture that workload before writing any SQL. The source of truth should be the statements your system runs in production, collected from pg_stat_statements (enabled and reset over a known window) or from application logs and tracing. Group the captured statements by the transaction they belong to, not just by individual query, because pgbench runs each script as a unit. Record how often each transaction type runs relative to the others, since that ratio becomes the weights in the script (for example, @ weights on each \\set block of a -f file). Treat the weights as an illustrative starting point until they match a measured window of production traffic.
Parameter values and data distribution decide which plans PostgreSQL chooses, so a script that uses uniform random keys can look fast while hiding the problem you are testing for. Check how the production data is skewed: a few hot customers or products may own most rows, and recent dates may dominate reads. Your script should draw keys from ranges or distributions that reproduce that skew, and the benchmark database should be loaded with comparable row counts, value frequencies and table sizes, otherwise planner statistics will not reflect production. Keep transaction boundaries identical to the application, including explicit BEGIN and COMMIT, the isolation level it sets, and any SELECT ... FOR UPDATE locking, because those change lock contention and latency. Confirm with your application team which isolation level and statement timeouts the driver uses, and confirm that the script uses the same prepared-statement behavior as the driver.
Reading latency results without fooling yourself
A pgbench run produces numbers that look precise but can mislead. The cards below cover the checks that separate a real change in PostgreSQL behavior from noise, cache effects or a background process that happened to run during one test.
Averages hide tail latency
A mean latency can look healthy while a small share of transactions waits far longer than the rest. For a PostgreSQL go-live, the users who feel the problem are the ones in the tail, so read the p95 and p99 values that pgbench reports with --log or in aggregated per-interval output. Check the spread before you report the average. Compare the median with the highest percentile you track, and ask whether the tail matches the response time your application team has committed to.
Read throughput and latency together
Transactions per second and latency describe the same run from two sides, and either number alone can mislead. A higher TPS with much higher latency may mean the system is queuing work, not serving it faster. Compare runs at the same client count and the same --rate setting when you use a fixed-rate test. Never call a run faster based on TPS alone. Confirm that the latency at the chosen load still meets your target.
Warm and cold cache runs differ
The first run after a restart reads data from disk, while later runs may serve most pages from shared_buffers and the operating system page cache. Results from these two states are not comparable. Record whether each run started after a restart, and run the schedule you plan to use in production, including a warm-up period. Label every result as warm or cold so a later reader does not compare them by mistake.
Measure run-to-run variation first
Before you call a configuration change an improvement, repeat the same test several times and measure how far the results move on their own. Shared hosts, noisy storage and background tasks can produce differences larger than the effect of a setting change. Compare the range of results from unchanged runs with the change you measured. A difference inside the normal range is not an improvement. Record the scale, data size and host state with each run so the comparison holds up later.
Checkpoints and autovacuum cause spikes
Checkpoints flush dirty buffers to disk, and autovacuum reads and cleans tables. Either can run during one test and add a latency spike that does not appear in others, especially on write-heavy scripts. Check the PostgreSQL server log for checkpoint and autovacuum entries that line up with the spike times in your pgbench log. Do not attribute a spike to your configuration until you have matched it to a background event. Repeat the run with those tasks scheduled away from the measurement window if the pattern repeats.
Per-statement latency finds the tail
A transaction in a custom pgbench script contains several statements, and one of them often drives the slow end of the distribution. Enable per-statement reporting with --report-per-command to see which statement carries the tail, then investigate that statement with EXPLAIN (ANALYZE, BUFFERS) on the same data. Fix the statement that drives the tail, not the average transaction. Use the same per-command breakdown before and after each change so you can see where the effect landed.
How the benchmark phases feed a go-live or upgrade decision
The flow starts from production statements captured from real traffic, which define the custom workload a generic test cannot supply. Those statements shape the test environment and the data load, then a baseline run sets the reference point. Each later change to one variable is rerun and compared against that baseline, so a difference can be attributed to a single cause. The decision node sends the team to go-live or upgrade only when latency results meet the targets agreed beforehand, and a miss loops back to tuning.
Benchmark phases from workload capture through to the go-live or upgrade decision.
Keeping benchmark data, credentials and traffic under control
The first control for a pgbench run is the data it writes and reads. pgbench initializes its tables with pgbench -i and generates synthetic rows, so the default schema contains no customer records. The risk appears when teams point the tool at a copy of production or reuse a custom script that selects real account, customer or payment rows to mirror the workload. If the test needs realistic value distributions, generate them or use masked extracts, and confirm with your data owner that the masking covers every column the script touches. Keep benchmark databases on separate instances or schemas, and delete the copies once the test ends so that load results do not become a second, unmanaged store of sensitive data.
Credentials and network paths need the same separation. Create a dedicated PostgreSQL role for the benchmark with privileges limited to the benchmark database, and do not reuse application or administrator accounts in the connection string. Confirm in pg_hba.conf that the benchmark role can only authenticate from the load generator's address, and restrict firewall rules so the load generator cannot route to production hosts, production PgBouncer endpoints or production replicas. Store the benchmark password in your secrets tool rather than in shell history or script files, and rotate it after the run. Ask your security team to confirm how these settings are reviewed before go-live, because a misdirected -h flag is the most common way a load test reaches the wrong server.
Shared infrastructure needs scheduling as well as access control. A pgbench run with high client counts can consume CPU, disk I/O and network bandwidth that other databases, batch jobs or backups depend on, so the test can cause the very slowdowns you are trying to measure in production. Run benchmarks on isolated hardware or a staging cluster that mirrors production settings, or in an agreed window with the owners of any shared host. Keep the raw output, scripts and summary reports in the same access-controlled repository or ticketing system you use for other operational records, with the run date, PostgreSQL version and configuration recorded, so results can be audited and reproduced later.
Limits to confirm in your own environment
A pgbench number is only as meaningful as the setup behind it. The cards below cover the gaps that most often separate a benchmark result from production behavior, and what to confirm before a team signs off on a go-live or upgrade based on it.
Storage, network and memory match
A run on a laptop, a lab VM or a host with different disks, network latency or RAM will not predict production latency. Confirm that the storage type, filesystem, WAL volume placement, memory size and network path between the client and the server match the production design. Record the hardware and the relevant settings, such as shared_buffers and max_connections, alongside every result so a later reader can judge whether the comparison holds.
Data volume reaches production size
pgbench initializes tables at a chosen scale, and a small scale keeps most of the data in memory. Results at that size can look much faster than the same workload against a database whose working set exceeds RAM. Confirm the scale factor and total on-disk size against production, and check whether the buffer cache hit ratio during the run resembles what production shows at peak.
Application pooling and ORM behavior
The built-in script sends simple statements over a fixed set of connections, which rarely matches how applications open connections, prepare statements or issue many small queries through an ORM. A pool in front of PostgreSQL, such as PgBouncer, changes the connection count and session state the server sees. Confirm whether the test path includes the same pooler, driver and prepared-statement settings that production uses.
Failover, backup and recovery timing
A throughput and latency run measures steady-state behavior only. It does not measure how long a failover takes, how a replica behaves under the same load, or how long a base backup or point-in-time restore takes to complete. Those figures need their own tests against the chosen replication and backup tools. Confirm that recovery objectives are tested separately, and do not cite a pgbench result as evidence for them.
Continuous archiving docsMinor and major version differences
A result from one minor release does not transfer automatically to another, and a major upgrade can change planner behavior and I/O paths. PostgreSQL 18 introduced asynchronous I/O, so a before-and-after comparison across that boundary needs its own runs. Confirm the exact version string on both sides, keep the same configuration and data, and repeat the test on the target version before deciding the upgrade is safe.
PostgreSQL 18 release notesResults from one run
A single run shows one sample of latency and throughput, and cache state, background checkpoints and autovacuum activity can shift the numbers between runs. Confirm that each configuration was run several times from a warmed or deliberately cold state, that the spread between runs is recorded, and that latency percentiles were taken over the whole measurement window rather than a short sample.
What teams ask before benchmarking PostgreSQL themselves or hiring help
How much effort does a PostgreSQL benchmark take?
Effort depends on how much of the work is capture, environment setup, repeated runs and analysis, rather than running pgbench itself, which is quick once the environment exists. The largest drivers are how well you can capture the real workload, how closely the test environment matches production, how many scenarios you need (current configuration, a new major version, a changed pool size), and how many repeated runs are needed before results are trusted. Analysis of latency percentiles and server statistics often takes longer than the runs. Ask any partner to split their estimate into these phases so you can see where the time goes.
Can an in-house team benchmark PostgreSQL without outside help?
Yes, if the team can answer a few questions well: which transactions matter, what concurrency production sees, whether the test hardware and data volume are comparable, and how to tell noise from a real change. Teams with a DBA or platform engineer who has run load tests usually manage the basic pgbench runs themselves. Outside help tends to add value in workload capture from pg_stat_statements, in custom scripts that reproduce application behavior, and in a repeatable method for comparing an upgrade candidate against the current version. The trade-off is staff time against the risk of drawing conclusions from a flawed setup.
What does the client need to provide for a benchmark?
The work needs inputs from your side before any test runs. Typically that includes representative SQL statements or samples from production, the schema and key indexes, expected peak and average concurrency, the current PostgreSQL version and configuration, and a test environment with comparable CPU, memory, storage and network. You also need agreed access windows on the test system, a contact who can approve load on shared infrastructure, and data sets sized close to production. Missing inputs are the most common reason a benchmark produces numbers that cannot be used for a go-live decision.
How long does a benchmark cycle run, and what sets its length?
No duration is fixed in advance. Cycle length is set by how quickly the workload can be captured, how long it takes to build a comparable environment and load representative data, how many scenarios and runs are planned, and how many iterations follow when results show a bottleneck. Scheduling access to shared test hardware and agreeing on change control can add calendar time even when the technical work is small. Ask for a written schedule with the dependencies on your side listed separately from the work the partner performs.
Is pgbench's built-in test enough to decide on a go-live or upgrade?
Usually not on its own. The default pgbench script runs a TPC-B-like workload, which is useful for comparing hardware, configuration changes and PostgreSQL versions under a known load, but it does not reflect your queries, table shapes, transaction mix or client behavior. Custom scripts written with pgbench's -f option can model your statements, and the built-in test still helps as a baseline. Treat pgbench as one input next to production-derived workload data and application-level tests, and state clearly which scenarios each result covers.
Which client and thread counts should a pgbench run use?
Start from the concurrency your application produces at peak, then vary client counts around that value and find where throughput stops rising and latency climbs. Set --jobs (threads) so pgbench does not itself become the bottleneck, and run the client process on separate hardware from the database when possible. Each run should be long enough to pass warm-up effects and repeated several times to measure variance. Report average and tail latency together, because averages can hide the slow requests users notice.
What should a quote for a PostgreSQL benchmark include?
A useful quote lists the scope in writing: which workloads and scenarios are covered, which PostgreSQL versions and configurations are compared, what environment is used and who provides it, how many runs are included, and what the deliverables are, such as scripts, raw results, a summary of latency and throughput, and recommendations. It should separate one-time setup from any repeat testing and say what is excluded, for example tuning changes applied during the work or retesting after fixes. Ask how changes to scope are priced. DeployOpen agrees scope, deliverables and timelines in writing before work starts, and quotes follow from that written scope.
How DeployOpen scopes and delivers a PostgreSQL benchmark
DeployOpen treats a pgbench engagement as a written test plan tied to your environment, not a generic run of the default script. We agree what workload, hardware and success criteria the benchmark covers, then build, run, document and hand over the results in your own infrastructure.
How we scope
- Agree in writing which workloads, schemas and transaction mixes the benchmark must represent before any test runs.
- Confirm the target environment, including hardware, storage, network path, PostgreSQL version and any pooler in front of the database.
- Define the latency and throughput criteria and the upgrade or go-live decision each result must inform.
How we build
- Build custom pgbench scripts from your query patterns, and keep the built-in TPC-B-like test as a baseline with its limits recorded.
- Set up client hosts so the load generator does not compete with the database for CPU, memory or network.
- Run repeated test rounds at agreed client and thread counts, and record configuration, data volume and warm-up state for each run.
How we hand over
- Deliver a written report with throughput, latency percentiles, error rates and the exact commands and scripts used.
- Document which results are reproducible in your environment and which depend on conditions you must keep fixed.
- Hand over scripts, configuration files and a runbook so your team can repeat the benchmark before the next upgrade.
How we support
- Engagements are fixed-scope, so the agreed deliverables and timeline are set before work starts and changes go through a written change.
- Ongoing support, repeat benchmarks and retesting after upgrades or configuration changes are available as a retainer.
- Ask for the scope, assumptions and what your team must provide in writing, so the quote reflects the actual test work.

