Skip to content
ImagineWorld

Understanding and Monitoring Transactional Application Performance

node_idnode-book_ai-ready-postgresql-18_chapter-08-understanding-and-monitoring-transactional-application-perfo
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num8
chapter_titleUnderstanding and Monitoring Transactional Application Performance
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 8 — Understanding and Monitoring Transactional Application Performance

Section titled “Chapter 8 — Understanding and Monitoring Transactional Application Performance”

Understanding and Monitoring Transactional Application Performance

Section titled “Understanding and Monitoring Transactional Application Performance”

So far, we’ve focused on building transactional systems that are efficient by design, structuring tables carefully, writing procedures and functions that avoid unnecessary work, selecting data types and indexes that best suit the workload, and writing queries that are both effective and efficient. These choices lay a strong foundation for performance, but real efficiency is only proven when the system runs under pressure. The actual behavior of a transactional application becomes visible only when it handles live data, concurrent users, and constantly changing transaction patterns.

Performance, therefore, isn’t a static outcome of good design—it’s something that must be observed, managed, and improved over time. Even a well-built database can slow down as data volumes grow or usage patterns shift. Queries that once ran smoothly may begin to slow down, locks might appear more often, and resource consumption can rise without an apparent reason. To prevent these issues from eroding the user experience, developers need to be able to see what’s happening behind the scenes—how queries are executed, where time is being spent, and what parts of the system are struggling to keep up.

This chapter focuses on developing that visibility. It introduces the methods and tools that help you measure and understand how your database performs in real conditions: profiling, benchmarking, and continuous monitoring. By learning how to acquire and interpret performance metrics, identify bottlenecks, and connect symptoms to causes, you can move from reacting to problems to anticipating and preventing them.

Ultimately, understanding and monitoring performance is about maintaining balance. It’s about ensuring that as your application grows—handling more users, transactions, and data—it continues to perform reliably, predictably, and at scale.

This chapter covers the following topics:

  • Using pgBench to simulate a workload
  • The PostgreSQL statistics system
  • Queries, execution plans, and query statistics
  • The Explain tool
  • Eco-system tools and extensions to monitor and improve transaction performance

All examples in the chapter are available in the GitHub repo under psql_scripts / sample_scripts / chapter_8.sql. The benchmarking command and the benchmarking transactions can be found in psql_scripts / sample_scripts / pgbench -scripts/.

To enhance clarity, the SQL scripts in the repository include inline comments that explain the logic behind each transaction and its expected outcome. Additionally, the repository contains sample output files from the pgbench run for your comparison and reference.

Understanding PostgreSQL’s state and its transactional performance

Section titled “Understanding PostgreSQL’s state and its transactional performance”

Before moving to production and while the system is in production, the developer wants to understand the current state and behavior of tables, indexes, queries, functions, and stored procedures. For that purpose, PostgreSQL provides views into the current state and cumulative statistics of activities. We will demonstrate how these tools can be used to understand the state and key attributes of databases, tables, indexes, functions, and queries.

Because our database server is a dynamic system, we will use a benchmarking framework to apply a workload, allowing us to observe how the building blocks interact. pgbench is the most popular benchmarking framework for PostgreSQL. By default, pgbench tests a simplistic scenario that is loosely based on TPC-B, involving five SELECT, UPDATE, and INSERT commands bundled into one transaction that simulate simple bank teller operations. However, pgbench is also a robust framework that can easily be adapted to simulate other workloads.

For our use case, we will define the following transactions:

  1. Update the available inventory for product variants.
  2. Insert sales transactions and sales transaction lines for random customers.
  3. Delete sales transaction lines.
  4. Update the phone number for a random customer.
  5. Look up a customer by first name and last name.
  6. Identify the top customers.
  7. Identify the top-selling products.

We specified the following custom pgbench command script, which is run against the east_ecommerce_data database on localhost at port 5432, with 10 parallel connections (-c 10) for 20 minutes (-T 1200), and will report progress every 5 seconds (-P 5). The command also invoked the seven transactions outlined previously, each defined in its own SQL file. The @ sign determines the relative frequency of individual commands within the overall set:

vacuumdb -h localhost -p 5432 --dbname=east_ecommerce_data --full –verbose
psql -h localhost -p 5432 -d east_ecommerce_data -c "SELECT * FROM pg_stat_reset();"
psql -h localhost -p 5432 -d east_ecommerce_data -c "SELECT * FROM pg_stat_statements_reset();"
pgbench -h localhost -p 5432 \
-d east_ecommerce_data \
-c 10 -n -T 1200 -P 5 \
-f gen-inventory.sql@10 \
-f gen-sales-transactions.sql@4 \
-f delete-sales-transaction-line.sql@1 \
-f update-customer.sql@4 \
-f select-customer.sql@6 \
-f top-customers.sql@2 \
-f top-selling-products.sql@4 \
> pgbench_command_output.txt

The pgbench configuration uses script weights (the values after @) to control the relative frequency of each transaction type in the workload. The figures shown here are taken from a single 10-minute run and are intended to illustrate how different transaction mixes affect relative execution frequency, throughput, and latency, not to present statistically significant performance results. In practice, meaningful benchmarking requires multiple runs under controlled conditions and analysis of averages and variability.

We run the pgbench command after a VACUUM FULL (which rewrites the table to reclaim space and remove dead tuples) to start from a clean slate, and we reset the statistics counters. Unlike a regular VACUUM, VACUUM FULL requires an exclusive lock and is typically used only for controlled experiments like this.

Figure 8.1: Relative distribution of transaction counts for the pgbench custom script

Figure 8.1 shows the relative frequency of actual query execution, whereas Figure 8.2 shows TPS and latency during a 10-minute run.

Figure 8.2: TPS and average latency for custom queries during a 10-minute run

PostgreSQL provides a set of cumulative statistics that help developers and DBAs understand the system’s status and behavior. We will explain the most important ones to the developer. For a comprehensive overview, please refer to the PostgreSQL documentation.

All the statistics explained in the following subsections are part of the cumulative statistics system. Some questions, such as How frequently is this index used on a given day*?*, may require resetting the statistics. Resetting the statistics using pg_stat_reset () and pg_stat_statements_reset () provides a clean baseline, making it easier to measure the impact of a specific workload or changes made during a defined time window, rather than analyzing performance data accumulated since the server started. pg_stat_ reset (``) resets PostgreSQL’s built-in (native) statistics, such as table and index usage, while pg_stat_statements_ reset (``) resets query-level statistics collected by the pg_stat_statements extension. There are also functions to reset statistics for a single object type or for a specific object.

The pg_stat_databases view provides insight into an individual database. The SELECT * FROM pg_stat_database WHERE datname = ' east_ecommerce_data '``; query produces the output in Table 8.1. The D escription column highlights the data elements that are relevant to the developer.

Output

Sample

Description

datid

21702

datname

east_ecommerce_data

numbackends

13

Number of backends currently connected to this database

xact_commit

1090

Successful versus canceled transactions

xact_rollback

7

blks_read

142

Blocks read from disk vs. blocks hit in cache

blks_hit

232236

tup_returned

21361088

Rows fetched by sequential scans (full table scans) and index scans

tup_fetched

11616

Rows returned by index scans (more efficient for targeted lookups)

tup_inserted

790

Activity ratio

tup_updated

1205

Activity ratio

tup_deleted

66

conflicts

0

temp_files

0

Number of temporary files created by queries (e.g., sort, hash, materialization spills to disk)

temp_bytes

0

deadlocks

11

checksum_failures

0

checksum_last_failure

blk_read_time

0

blk_write_time

0

session_time

30671.051

active_time

25113.086

idle_in_transaction_time

0

sessions

11

sessions_abandoned

0

sessions_fatal

0

sessions_killed

0

parallel_workers_to_launch

0

parallel_workers_launched

0

stats_reset

2025-10-04 …

Table 8.1: Sample output of pg_stat_database

Here are some observations based on the sample in Table 8.1:

  • The cache hit ratio (blks_hit / (blks_hit + blks_read)) is over 99%, which means that most reads are served from memory, which is ideal for performance. If this drops significantly, it may indicate increased I/O pressure (or a workload shift such as scanning newly accessed data). Before changing shared_buffers, confirm the pattern over time and validate overall memory headroom; tuning may include adding memory, improving indexing/query patterns, or addressing large scans—rather than increasing shared_buffers by default.
  • The commit ratio compares the number of committed transactions to the number that were rolled back. In this sample, the commit ratio is very high. Commit ratios below 90% warrant detailed analysis to identify and resolve the reasons the transaction is rolled back frequently.
  • Load distribution examines the balance of tuples returned by index scans and sequential scans, as well as those fetched by sequential scans, inserts, updates, and deletes. A high tup_returned value on large tables might suggest missing indexes, as the database must scan the entire table instead of using a more direct index path. It provides a general feeling for the activity in the database.
  • Deadlocks occur when multiple queries create a cycle of lock waits (each waiting on a lock held by another), and PostgreSQL cancels one of the queries to resolve the issue. While occasional deadlocks can occur in highly concurrent systems, a consistently high number indicates application logic or transaction design flaws that need investigation. Deadlocks cause queries to be canceled, and the application must be able to retry them. The ratio of deadlocks to successful transactions should be minimal.
  • Temporary files are created when sort operations or complex queries require more working memory than is available, prompting the use of persistent storage. This slows down the system significantly. Setting the log_temp_files option in the PostgreSQL log system identifies queries that create temporary files. pgBadger helps to identify the culprit. Once the query has been identified, the next step is to rewrite problematic queries. If that proves impossible, we can also increase work_mem. This is a flexible setting that can be changed per session, per user, or for the entire server.

Takeaways for the d eveloper

pg_stat_database is a good starting point to understand overall behavior, but it is not sufficient. While it helps identify specific problems, such as deadlocks, temporary files, and insufficient shared buffer allocation, it is only a starting point.

Next, we will dive into a similar diagnostic view for tables.

The pg_stat_user_tables view provides a per-database view of user-defined tables. PostgreSQL exposes the same statistics at different scopes: pg_stat_all_tables includes user and system tables, pg_stat_user_tables includes only user tables, and pg_stat_sys_tables includes only system (catalog) tables. The view includes information on the number of rows in the table, as well as the number of rows updated, deleted, or inserted. Furthermore, we obtain information about how often this table is accessed, either through a sequential scan or an index scan. For both methods, we receive information about the number of live tuples found. Lastly, the view shows the number of dead tuples (bloat) in the table, when the vacuum process was last executed, and how much bloat has accumulated since then.

Table 8.2 displays the results of the SELECT * FROM pg_stat_user_tables WHERE relname = ' product_variant_inventory '``; query. The D escription column highlights the data elements that are relevant to the developer.

Output

Sample

Description

relid

49196

schemaname

inventory

relname

product_variant _...

seq_scan

202

How the table was accessed, and how relevant that access was

last_seq_scan

2025-09-25 …

seq_tup_read

28435

idx_scan

1125364

last_idx_scan

2025-09-25 …

idx_tup_fetch

1125368

n_tup_ins

144

How active the data in that table was, and what kind of changes happened

n_tup_upd

1095406

n_tup_del

0

n_tup_hot_upd

1095061

How many tuples had a HoT update (see

Balance of live tuples versus dead tuples (dead tuples contribute to bloat, but bloat also includes free space in pages)

n_dead_tup

0

n_mod_since_analyze

0

What happened since the last vacuum or analysis

n_ins_since_vacuum

0

last_vacuum

last_autovacuum

2025-09-25 …

last_analyze

last_autoanalyze

2025-09-25 …

vacuum_count

0

autovacuum_count

16

analyze_count

0

autoanalyze_count

19

total_vacuum_time

0

Total time table has been manually vacuumed, in milliseconds (ms)

total_autovacuum_time

216

Total time this table has been vacuumed by autovacuum (ms)

total_analyze_time

0

Total time table has been manually analyzed (ms)

total_autoanalyze_time

317

Total time this table has been analyzed by autovacuum (ms)

Table 8.2: Sample output of pg_stat_user_tables

Here are some observations based on the sample shown in Table 8.2:

  • 98% index scans indicate that the table is almost always accessed via indexes.
  • Huge update activity—no inserts, no deletes. This table could be a hotspot for MVCC and deadlocks between concurrent transactions.
  • Almost all updates were HoT updates, which is good (see Chapter 7*,* Designing for High - Transaction Volumes and Writing Efficient Transactional Code for the definition of Heap only Tuple (HoT) updates).
  • No bloat (dead tuples), which means that vacuum is keeping up.

The pgstattuple view provides a deeper insight into a specific table. Table 8.3 shows us the result of running SELECT * FROM pgstattuple (``' product_variant_inventory '``);.

Output

Sample

Description

table_len

40960

Length in bytes

tuple_count

144

Number of live rows

tuple_len

4608

Overall size of the table

tuple_percent

11.25

% of table with live rows

dead_tuple_count

0

How much bloat is in the table

dead_tuple_len

0

dead_tuple_percent

0

free_space

32284

Free space

free_percent

78.82

% of table length that is free space

Table 8.3: Sample output of pgstattuple for the table product_variant_inventory

Here are some observations based on the sample in Table 8.3:

  • A moderate amount of free space can be a healthy sign: it often means vacuum has reclaimed dead tuples and left reusable room behind, which is normal for update-heavy tables or tables configured with a lower fill factor. However, a high free_percent, especially on a large table, can also signal bloat (many sparsely populated pages). For that reason, interpret free_percent alongside dead_tuple_percent, table_len, and vacuum history, rather than treating it as a standalone indicator of healthy vacuuming.
  • Significant amounts of free space in the table could be reclaimed by using tools such as pg_squeeze or VACUUM FULL to reduce on-disk storage, memory consumption, and I/O. However, both processes physically rebuild the table and can be costly, requiring extra disk space, strong locks, especially VACUUM FULL, and heavy I/O. On small or update-heavy tables, the gains may be short-lived, so use these tools selectively rather than by default.

Takeaways for the d eveloper

The two views, pg_stat_user_tables and pgstattuple, enable developers to inspect how tables are accessed (index scan versus sequential scan), how they’re updated (insert, update, delete), and how the table size is impacted (% of bloat and free space).

Key metrics to watch and inspect are as follows:

  • Are large tables frequently being accessed via sequential scans? If so, then let’s try to understand which queries do that, and if that access pattern is by design or can be changed to leverage indexes.
  • The % of bloat (dead tuples) in the table must be monitored. While every table that undergoes updates and deletes is expected to experience some bloat, it is crucial to monitor bloat to ensure it does not spike or grow over time. Bloat increases I/O and consumes memory, potentially having a significant impact on performance. When table bloat grows, we need to increase vacuuming.
  • The % of free space must also be monitored, as it also has an impact on I/O. Tools such as pg _ squeeze or VACUUM FULL can be used to reclaim free space.

The pg_stat_user_indexes view provides the developer with insights into user-defined indexes. Table 8.4 shows the output of SELECT * FROM pg_stat_user_indexes WHERE indexrelname = ' idx_east_customer_lastname_firstname '``;. The D escription column highlights the data elements that are most relevant to the developer.

Output

Sample

Description

relid

49211

OID of the table for this index

indexrelid

50453

OID of the index itself

schemaname

east_customer

Schema name

relname

customer

Name of the table for this index

indexrelname

idx_east_customer _...

Name of the index itself

idx_scan

36526

How often the index was scanned and when the last scan was

last_idx_scan

2025-09-28 …

idx_tup_read

2695924

Number of index entries examined and returned by scans on this index

idx_tup_fetch

2300362

Number of live table rows fetched because of those entries

Table 8.4: Sample output of pg_stat_user_indexes

Table 8.4 shows that this index is being used. While last_idx_scan shows us the date and time of last usage, we need to reset the statistics to understand the frequency of use.

pgstattuple sheds more light on the state of this index. Table 8.5 shows the result of the SELECT * FROM pgstattuple (``' idx_customer_lname '``); query.The D escription column highlights the data elements that are relevant to the developer.

Output

Sample

Description

table_len

65536

tuple_count

1402

tuple_len

34928

tuple_percent

53.3

dead_tuple_count

0

How much bloat is in the index

dead_tuple_len

0

dead_tuple_percent

0

free_space

8244

free_percent

12.58

% of index length that is free space

Table 8.5: Sample output of pgstattuple

Here are some observations based on the sample shown in Table 8.5:

  • No bloat, which means that the vacuum processes are keeping up.
  • A relatively small percentage of free space. No action is required.

Takeaways for the d eveloper

The pg_stat_user_indexes and pgstattuple views identify possible bloat in the index, indicating how much space could be reclaimed by VACUUM FULL or the use of pg_squeeze (more about that later in this chapter). Most importantly, they inform us whether (and how often) the index is utilized. An unused index should be removed, as it still requires updates and can contribute to the write amplification discussed in the previous chapter. Also watch for redundant or duplicate indexes: PostgreSQL enforces unique index names, not the uniqueness of indexed content, so it is possible to have multiple indexes that cover the same keys (for example, overlapping indexes created alongside primary keys/unique constraints or multi-column indexes).

We can gain a simple view into user-defined functions and procedures using the pg_stat_user_functions view. However, these stats are not collected by default; track_functions controls their collection. To enable it, set track_functions = pl (or all) in postgresql.conf (or via ALTER SYSTEM) and reload/restart the server. Table 8.6 displays the output of pg_stat_user_functions for two functions in the east_ ecommerce _data database. The D escription column highlights the data elements that are most relevant to the developer.

[ RECORD 1 ] -----

Description

funcid

24426

schemaname

api

funcname

execute_sales_transaction

calls

27494

# of times called

total_time

389575.235

Time spent in total, incl. called procedures

self_time

389575.235

Time spent in this procedure

[ RECORD 2 ] -----

funcid

30799

schemaname

api

funcname

generate_random_sales_transaction

calls

27494

# of times called

total_time

477337.889

Time spent in total, incl. called procedures

self_time

87759.396

Time spent in this procedure

Table 8.6: Sample output of the pg_stat_user_functions view

pg_stat_user_functions only provides data about call frequency and the amount of time spent in the function or procedure itself, respectively, in functions or procedures that it calls. While pg_stat_user_functions does not tell us that generate_random_sales_transaction calls execute_sales_transaction, the plpgsql_check linter, described in Chapter 6*,* Functions and Stored Procedures can help identify call trees.

Queries are central to performance analysis. Before we explore performance analytics, let’s review how PostgreSQL converts the declarative query statement into an imperative plan that instructs the database server on what to do.

Figure 8.3 describes PostgreSQL’s step-by-step approach to transforming a query into an execution plan.

Figure 8.3: PostgreSQL query execution

PostgreSQL starts by parsing the query, checking for syntactic correctness, building a query tree of its components, and integrating any view definitions referenced in the query.

The next step, also known as Planner/Optimizer, creates all possible execution plans for the query building blocks. It always creates a sequential scan plan and builds plans that leverage any existing indexes for index scans, provided the query operators are compatible with the index. The same applies to order by clauses.

If the query involves several tables, then the planner/optimizer creates strategies for each join, choosing between nested loop joins (the table on the right is scanned once for every row found on the left), merge joins (both tables are sorted on the join attribute and then scanned once in that order), and hash joins (the right table is scanned and a hash table is created based on the join attributes, and then the left table is scanned, using the hash of the corresponding join attribute to identify matching rows). It will also try to reorder joins, typically joining the most selective relations first to reduce the number of rows processed downstream.

The optimizer uses an arbitrary cost unit based on disk page fetches and row-count estimates to select the best plan. The EXPLAIN tool shows us the query plan and the associated estimated cost.

Using the EXPLAIN tool to understand query plans

Section titled “Using the EXPLAIN tool to understand query plans”

SQL is a declarative language that specifies what is needed, unlike imperative languages such as Python or C++ that instruct the computer on what to do. To convert the SQL declaration into a step-by-step process, PostgreSQL generates an execution plan that determines which indexes to use, how to join tables, and how many parallel workers to deploy to produce the results. PostgreSQL relies on statistics about table sizes, data distribution, and indexes to develop this plan.

While the pg_stat_statements view helps us identify long-running queries, it doesn’t provide details on how the planner converts the query into execution steps. The EXPLAIN tool offers that insight.

We invoke the EXPLAIN tool simply by prefixing a query with EXPLAIN, and it returns a tree structure that describes the hierarchical execution plan. Here is a simple example:

EXPLAIN SELECT count(*) FROM customer WHERE postal_code like 'MA%';
QUERY PLAN
-----------------------------------------------------------------
Aggregate (cost=45.69..45.70 rows=1 width=8)
-> Seq Scan on customer (cost=0.00..44.67 rows=407 width=0)
Filter: ((postal_code)::text ~~ 'MA%'::text)

This hierarchical execution plan tells us the following:

  • This is an aggregate query (it combines many rows into a smaller result, such as COUNT(``*)) that will return the initial result after 45.69 cost units and the complete result after 45.70 cost units. (Remember that the cost unit is an arbitrary unit based on units of disk fetches and row estimates; it is meant for comparing alternative plans on the same system. It is not micro- or milli-seconds!)
  • The result will be a single row that is eight bytes wide (the planner’s estimated average row width for this plan node’s output).
  • PostgreSQL performed a sequential scan, inspecting every single row and applying a filter for ' MA% '.

Sequential scans can be expensive when only a small subset of rows is needed, because every record must be checked. If a record is not in shared buffers, it must be read from persistent storage, which is a slow process. If we create an index on the postal code column, then PostgreSQL can revert to an index-only scan, which is significantly faster:

Sequential scans can be the most efficient option when a large portion of the table must be read; this is why the planner may choose a sequential scan even when an index exists.

CREATE INDEX idx_customer_postal_code ON customer(postal_code);
EXPLAIN SELECT count(*) FROM customer WHERE postal_code like 'MA%';
Aggregate (cost=33.74..33.75 rows=1 width=8)
-> Index Only Scan using idx_customer_postal_code on customer (cost=0.28..32.72 rows=407 width=0)
Filter: ((postal_code)::text ~~ 'MA%'::text)

In this case, the planner expects to complete the query after 33.75 cost units using an index-only scan—a 35% percent improvement!

EXPLAIN uses internal statistics about table sizes and indexes to develop its plans. Those may deviate slightly from actual table data, as they are sample-based. To compare the planned and actual execution times, use EXPLAIN ANALYZE, which creates the plan, executes the query, and reports any differences.

Significant differences indicate that the internal statistics may need to be updated using ANALYZE. To run EXPLAIN ANALYZE with an update, delete, or insert query, but without changing the underlying data, put the query into a BEGIN/ROLLBACK block, which will execute the query, but not commit any changes.

Let’s look at a more involved example—a query that finds the top 10 customers by total sales in the prior month:

SELECT c.id, c.first_name, c.last_name, SUM(stl.qty * stl.price_at_sale) AS total_sales FROM customer c
JOIN sales_transaction st ON c.id = st.customer_id
JOIN sales_transaction_line stl ON st.id = stl.sales_transaction_id
WHERE st.transaction_date>= CURRENT_DATE - INTERVAL '1 month'
GROUP BY c.id, c.first_name, c.last_name
ORDER BY total_sales DESC
LIMIT 10;
Limit (cost=2920.00..2920.02 rows=10 width=54)
-> Sort (cost=2920.00..2923.53 rows=1414 width=54)
Sort Key: (sum(((stl.qty)::numeric * stl.price_at_sale))) DESC
-> HashAggregate (cost=2871.77..2889.44 rows=1414 width=54)
Group Key: c.id
-> Hash Join (cost=910.00..2821.90 rows=4987 width=33)
Hash Cond: (st.customer_id = c.id)
-> Hash Join (cost=846.19..2744.95 rows=4987 width=20)
Hash Cond: (stl.sales_transaction_id = st.id)
-> Seq Scan on sales_transaction_line stl (cost=0.00..1663.21823.57 rows=89721 width=21)
-> Hash (cost=823.57..823.57 rows=1809 width=19)
-> Seq Scan on sales_transaction st (cost=0.00.. rows=1809 width=19)
Filter: (transaction_date>= (CURRENT_DATE - '1 mon'::interval))
-> Hash (cost=46.14..46.14 rows=1414 width=22)
-> Seq Scan on customer c (cost=0.00..46.14 rows=1414 width=22)

EXPLAIN tells us that this query will take 2,920 cost units and will not use any indexes. There are two parts of the plan (highlighted in gray) that appear to be particularly expensive and may benefit from an index.

CREATE INDEX idx_sales_transaction_date ON sales_transaction(transaction_date);
CREATE INDEX idx_sales_transaction_line_st_idtransaction_date_line
ON sales_transaction_line(sales_transaction_id);

The new plan shows that the query is taking advantage of both indexes (highlighted in gray), and the query execution cost has been reduced by 23%:

Limit (cost=2233.64..2233.67 rows=10 width=54)
-> Sort (cost=2233.64..2237.18 rows=1414 width=54)
Sort Key: (sum(((stl.qty)::numeric * stl.price_at_sale))) DESC
-> HashAggregate (cost=2185.41..2203.09 rows=1414 width=54)
Group Key: c.id
-> Hash Join (cost=64.40..2135.54 rows=4987 width=33)
Hash Cond: (st.customer_id = c.id)
-> Nested Loop (cost=0.58..2058.59 rows=4987 width=20)
-> Index Scan using idx_sales_transaction_dateIndex Scan using idx_sales_transaction_line_st_idtransaction_date_line on sales_transaction st (cost=0.29..312.12 rows=1809 width=19)
Index Cond: (transaction_date>= (CURRENT_DATE - '1 mon'::interval))
-> on sales_transaction_line stl (cost=0.29..0.94 rows=3 width=21)
Index Cond: (sales_transaction_id = st.id)
-> Hash (cost=46.14..46.14 rows=1414 width=22)
-> Seq Scan on customer c (cost=0.00..46.14 rows=1414 width=22)

Query plans are notoriously difficult to read. Tools such as pgAdmin (see the next section) include visualizers to help developers make sense of the data. There are also specialized websites, such as pgexplain.dev and explain.depesz.com (see Figure 8.4), that help developers understand the output and identify opportunities for improvement.

Figure 8.4: Graphical query plan visualization (pgexplain.dev)

EXPLAIN has many more capabilities beyond the scope of this book, such as inspecting buffer usage and comparing plan time with actual execution time. Consult Learn PostgreSQL by Luca Ferrari andEnrico Pirozzi for a more detailed description of the EXPLAIN tool.

PostgreSQL also has a module that can automatically log execution plans for slow statements (above a configurable threshold), which is useful for capturing real production plans and spotting plan changes over time without manually running EXPLAIN. For more information, refer to the PostgreSQL documentation: https://www.postgresql.org/docs/current/auto-explain.html.

While the EXPLAIN tool helps us dive into individual execution plans, the pg_stat_statements view provides the starting point to understand the execution frequency and basic metrics for the queries. For each query, it provides over 50 data elements. We will focus here on the ones that are most relevant to the developer (see Table 8.7).

ColumnDescription
callsThe number of times this query has been called
total_exec_timeThe total time spent executing the query, in milliseconds
rowsThe total number of rows retrieved by this query
shared_blks_hitThe number of blocks already cached when read for the query
shared_blks_readThe number of blocks that had to be read from the disk

Table 8.7: Key columns returned by pg_stat_statements

We will use these data elements to identify long-running queries and queries with a low cache-hit ratio.

This query helps identify the top 10 queries with the longest total runtime. To put that value in context, the query also shows the individual query as a percentage of total run time:

WITH totals AS (
SELECT
SUM(total_exec_time) AS sum_exec_time,
SUM(calls) AS sum_calls
FROM pg_stat_statements
)
SELECT
SUBSTRING(query, 0, 30) AS query, calls AS nbr_of_calls, TO_CHAR(calls/totals.sum_calls, 'FM99.00%') as perc_total_calls,
ROUND(total_exec_time) AS total_exec_time, TO_CHAR(total_exec_time/totals.sum_exec_time, 'FM99.00%') AS perc_exec_time
FROM pg_stat_statements
JOIN totals ON TRUE
ORDER BY total_exec_time DESC
LIMIT 10;

Please note, for the sake of improved readability, we have truncated the length of the query column to 25 characters:

query | nbr_of_calls | perc_total_calls | total_exec_time | perc_exec_time
-------------------------+--------------+------------------+-------
SELECT b.label AS brand, | 1459 | .01% |6729820 | .55%
SELECT c.id, c.first_nam | 1459 | .01% |3245209 | .26%
CALL delete_random_sales | 682 | .01% |1064932 | .09%
SELECT stl.sales_transac | 682 | .01% | 718165 | .06%
NOT EXISTS (SELECT $4 FR | 682 | .01% | 324412 | .03%
CALL generate_random_sal | 2903 | .03% | 59404 | .00%
CALL api.execute_sales_t | 2903 | .03% | 45930 | .00%
CALL random_inventory_in | 7055 | .06% | 20109 | .00%
DELETE FROM sales_transa | 46 | .00% | 16687 | .00%
DELETE FROM ONLY "east_s | 46 | .00% | 16655 | .00%

The output indicates that the first two select queries take a disproportionate amount of time, even though they represent only a tiny percentage of the overall calls. They can be primary targets for further analysis using the EXPLAIN facility.

Queries are significantly faster if most of their data is in shared buffers— that is, they have a high cache-hit ratio. The following query identifies the top 10 queries by ascending buffer hit ratio:

WITH totals AS (
SELECT SUM(shared_blks_hit + shared_blks_read) AS sum_accesses,
SUM(shared_blks_hit) AS sum_hits
FROM pg_stat_statements
)
SELECT
SUBSTRING(query, 0, 25) AS query, calls AS nbr_of_calls,
shared_blks_hit, shared_blks_read,
100* (shared_blks_hit::numeric / NULLIF(shared_blks_hit + shared_blks_read,0))::NUMERIC(5,2) AS hit_cache_ratio
FROM pg_stat_statements
JOIN totals ON TRUE
ORDER BY hit_cache_ratio ASC
LIMIT 10;

Please note, for the sake of improved readability, we have truncated the length of the query column to 25 characters:

query | nbr_of_calls | shared_blks_hit | shared_blks_read | hit_cache_ratio
-------------------------+--------------+-----------------+-----+-----
DELETE FROM sales_transa | 682 | 2831 | 579 | 83.00
CALL delete_random_sales | 682 | 6156828 | 623 | 100.00
SELECT "oid", "typname" | 13 | 44 | 0 | 100.00
explain SELECT c.id, c.f | 1 | 234 | 0 | 100.00
UPDATE product_variant_i | 7055 | 35646 | 3 | 100.00
SELECT qty | 8754 | 17572 | 0 | 100.00
DELETE FROM ONLY "east_s | 46 | 206449 | 0 | 100.00
SELECT * FROM east_custo | 4294 | 335824 | 5 | 100.00
explain SELECT b.label A | 1 | 303 | 0 | 100.00
WITH totals AS ( +| 2 | 6 | 0 | 100.00
SEL | | | |

Hit-cache rate values below 80% for frequently run queries indicate increased reads from persistent storage. This may mean that shared buffers are undersized, but it can also reflect workload patterns (for example, large scans or newly accessed data) or broader cache behavior outside PostgreSQL. Before tuning, confirm the trend over time and correlate it with I/O metrics and query patterns rather than treating the hit rate as a standalone sizing rule.

Other tools to understand transaction performance

Section titled “Other tools to understand transaction performance”

In this section, we explore two popular open source tools that aid developers in understanding database activity and query performance: pgAdmin and pgBadger. pgAdmin is a popular DBA-focused tool for creating and managing schemas, tables, procedures, functions, foreign tables, and all other constructs available in PostgreSQL. pgBadger is a log analyzer focused on PostgreSQL, identifying slow queries, temporary files, and other events occurring in PostgreSQL. While pgAdmin connects to PostgreSQL live via queries that it runs every few seconds, pgBadger analyzes the Postgres logs.

pgAdmin can be downloaded from pgadmin.org and is an open source GUI tool used to manage DDL and DML. pgAdmin also has a dashboard that tracks overall database activity (see Figure 8.5) in terms of sessions, queries, and I/O.

Figure 8.5: The pgAdmin activity dashboard

The dashboard also gives easy access to the database state (Figure 8.6), with the database backend processes and their current workload. This view can also be used to kill a database process.

Figure 8.6: pgAdmin database state display

pgAdmin also provides a view of the server configuration and a simplistic log viewer.

pgBadger is an open source tool that analyzes PostgreSQL log files to generate detailed, interactive HTML reports, providing insights into database traffic, errors, and activity patterns to help developers troubleshoot issues and optimize performance (see Figure 8.7). It identifies slow queries, detects error spikes and unusual activity, diagnoses concurrency problems such as locks and deadlocks, and tracks long-term performance trends, all with minimal overhead and without requiring agents or background processes.

Figure 8.7: pgBadger showing SQL traffic

pgBadger is widely used to understand and analyze query performance in the context of concurrent sessions, vacuum processes running simultaneously, checkpoints, and the creation of temporary files, among other factors. As it works directly off the PostgreSQL logs, it has no impact on performance and is very easy to use.

PostgreSQL has a vibrant ecosystem, with many contributions coming in the form of extensions. Approximately 50 extensions are part of the standard PostgreSQL contrib module and can be easily installed with the CREATE EXTENSION command. If you are working in the cloud, then consult the DBaaS provider’s documentation to learn which other extensions are available for use. On premises, extensions that are not part of the PostgreSQL contrib module must be installed manually. We recommend working with your PostgreSQL partner company to identify extensions that are reliable, secure, and well-maintained.

In Chapter 6, Functions and Stored Procedures we introduced the pg_background extension to initiate background processes, similar to Oracle’s autonomous transaction pragma. The same chapter also described the use of plpgsql_check as a PL/pgSQL linter and dependency analyzer.

pg_squeeze is a PostgreSQL extension that can help address one of the performance issues mentioned earlier: reduction of free space. While the vacuum process continually removes dead tuples, it does not return disk space to the operating system (even though it does make space inside the table reusable for future rows). VACUUM FULL would do that, but VACUUM FULL requires an exclusive lock on the table and thus is typically only used with supervision during a maintenance window or periods of low activity. pg_squeeze addresses that problem. It removes unused space from a table and optionally sorts tuples by a specific index to create a clustered table. As with any table-rewrite maintenance, plan for prerequisites (for example, a primary key), ensure that autovacuum remains healthy, and allow temporary disk headroom during the operation.

pgstattupleBeforeAfter
table_len409608192
tuple_count144144
tuple_len46084608
tuple_percent11.2556.25
dead_tuple_count00
dead_tuple_len00
dead_tuple_percent00
free_space322842984
free_percent78.8236.43

Table 8.8: pgstattuple output before and after pg_squeeze

Table 8.8 displays the results of applying pg_squeeze to the product_variant_inventory table. The overall table size was reduced to 20% of its original size, which typically improves cache efficiency and reduces I/O for workloads that frequently access this table.

This section consolidates the chapter’s key takeaways into an actionable checklist to guide your performance tuning efforts.

  • Overall d atabase h ealth:
    • Monitor your cache-hit ratio using pg_stat_database. If it drops below 80–90%, consider increasing shared_buffers to reduce disk I/O.
      • Keep an eye on deadlocks and temporary files. A high number of deadlocks points to application-level contention issues, while frequent large temporary files often indicate that work_ mem is too low for certain queries (or that queries are poorly shaped for memory use). To reduce the likelihood of deadlocks, keep transactions as short as possible and ensure that code paths acquire locks and update rows in a consistent order.
      • Investigate low commit ratios (below 90%). It could signify frequent errors or issues in your application logic that cause transactions to be rolled back.
  • Table and i ndex m anagement:
    • Identify how your tables are accessed with pg_stat_user_tables. If large tables are frequently accessed via sequential scans, investigate which queries are responsible and determine whether new indexes are needed or whether partitioning could reduce the amount of data scanned (via partition pruning).
      • Monitor table bloat. While some bloat is normal for tables with frequent updates and deletes, ensure it doesn’t grow uncontrollably over time. If it does, consider more aggressive vacuum settings.
      • Reclaim unused space. Monitor the percentage of free space in tables and indexes using pgstattuple. Tools such as pg_squeeze or VACUUM FULL (use with caution, as it acquires an exclusive lock) can reclaim this space to reduce I/O.
      • Eliminate unused indexes. Use pg_stat_user_indexes to find indexes with zero or very few scans. Unused indexes still incur overhead during write operations and should be removed. When doing so, keep indexes that enforce primary keys or unique constraints, and periodically look for redundant (duplicate/overlapping) indexes that add maintenance cost without improving performance.

This chapter wraps up the transaction-focused part of the book by explaining how developers can analyze and optimize PostgreSQL database performance through systematic monitoring and benchmarking. Using tools such as pgbench, pg_stat_database, pg_stat_statements, and EXPLAIN, the chapter showed how to identify long-running queries, detect inefficient indexing, and manage table bloat. It also introduced visualization and analysis tools such as pgAdmin and pgBadger, along with extensions such as pg_squeeze to reclaim storage without downtime. Overall, the chapter highlighted that maintaining optimal database performance is an ongoing process of observation, tuning, and refinement—essential for ensuring scalability, stability, and responsiveness in transactional applications.

The following chapter will focus on analytics use cases. You will understand the requirements for analytics, how to optimize data for high-performance analytics with PostgreSQL, and how to leverage PostgreSQL’s capabilities.