azure database for postgresql
183 TopicsPostgreSQL Bloated Tables
Introduction Bloat refers to the excess, wasted disk space occupied by "dead rows" (tuples) within tables and indexes that no longer hold active data. This occurs because PostgreSQL uses Multi-Version Concurrency Control (MVCC) to manage concurrent transactions, which ensures transaction snapshot isolation. Every UPDATE/DELETE Operation doesn't immediately delete old records from the table(data pages), but marks them with xmin/xmax markers (where xmin is the transaction ID that created the record, and xmax is the transaction ID that deleted or updated it). As a result, old version records remain physically in the database; the system doesn't discard anything immediately, it simply marks the last version as "deleted" with the appropriate xmax value. This accumulates multiple versions of the same record, of which ultimately only the newest is active, while the rest are "dead" data requiring future cleanup (VACUUM). So, instead of modifying or deleting data directly in place, updates and deletes leave the original data on disk and create new versions (Updates) elsewhere, meaning the physical file size doesn't shrink. VACUUM removes these dead row versions and makes their space reusable within the table, so it should run regularly (autovacuum) on frequently updated tables. Plain VACUUM allows normal reads and writes and usually retains reclaimed space within the table rather than returning it to the operating system. However, if the last pages contain no live rows, it can shorten the file and return that space to the operating system, while VACUUM FULL will rebuild the table and it’s indexes, returning the unused space to the operating system. MVCC, xmin/xmax, and Snapshot Isolation in PostgreSQL PostgreSQL uses the Multi-Version Concurrency Control (MVCC) mechanism to prevent parallel working requests (transactions) from interfering with each other's work. The foundation of MVCC is that each transaction sees a consistent "snapshot" of the database, a picture of records at the moment of its start. Database table bloat There are multiple factors than can contribute to database table bloat, which can impact queries performance and waste storage making your database grow indefinitely: Long-Running Transactions: Active or idle transactions freeze the visibility horizon (xmin), preventing VACUUM from freeing space occupied by dead rows. Delayed Autovacuum: Aggressive write workloads running faster than default or poorly tuned autovacuum settings leave dead space unrecovered. Replication & Standby Lags: Delayed logical replication slots or hot_standby_feedback on replicas force the primary database to hold old row versions. Mass Batch Deletions: Large single operation deletes free page space that PostgreSQL cannot shrink back from the OS without a heavy maintenance command like VACUUM FULL or tools like pg_repack / pg_squeeze. The diagram below illustrates how a PostgreSQL healthy table looks like comparing to a bloated table. How bloat impacts performance Disk space consumption: Bloat occupies excess disk space, and reading/writing the same amount of real data requires more I/O operations. Accordingly, disk usage and backup time increase because PostgreSQL has to operate on a large volume, while part of the data is effectively useless: Disk space consumption: Bloat occupies excess disk space, and reading/writing the same amount of real data requires more I/O operations. Accordingly, disk usage and backup time increase because PostgreSQL has to operate on a large volume, while part of the data is effectively useless. Increased I/O: The database must scan more physical data from disk to find the actual, active data. When PostgreSQL executes a query, it reads the required data pages, or blocks, from storage into memory. When those pages are heavily populated with dead tuples, fewer useful rows fit within each block. As a result, PostgreSQL may need to scan more physical data blocks to retrieve the same amount of active data.This additional scanning increases I/O activity, which can slow down queries and put extra pressure on storage resources. In simple terms, the database has to work through unnecessary data before finding the rows that actually matter. CPU overhead: PostgreSQL relies on Multi-Version Concurrency Control (MVCC) to determine which tuple versions are visible to each transaction. During a query, PostgreSQL evaluates tuple visibility according to the transaction's snapshot. When many dead tuples are present, more obsolete tuple versions may need to be examined while retrieving active data. This additional processing consumes CPU resources and increases the overall cost of read operations. Reduced cache efficiency: Bloated tables take up more memory space, reducing the amount of data that can be cached for faster access. Having data pages in memory does not completely eliminate the performance impact of dead tuples. Dead tuples still consume space within those pages, meaning that fewer active rows can be stored in the same amount of cached memory. As PostgreSQL scans the pages, it must evaluate tuple visibility and may need to examine more pages to find the active rows required by the query. Over time, this reduces the effective capacity of the buffer cache, increases memory pressure, and can contribute to additional cache misses and storage reads. Bloat can slow index lookups and scans, which will show up in slowly increasing query times and changing query plans. The impact of dead tuples is not limited to table data; indexes can become bloated as well. As rows are updated or deleted, obsolete index entries can remain until PostgreSQL's maintenance mechanisms clean them up. As these entries accumulate, the index grows and becomes less efficient. A larger index means PostgreSQL may need to examine more index pages to locate the required rows, increasing cache pressure and potentially causing more storage I/O. Once a matching entry is found, PostgreSQL may still need to visit the corresponding table page to verify tuple visibility. This additional work increases the cost of index scans and can further degrade query performance. Slower queries: All of these factors combine to make queries slower and less efficient. How to Monitor Table Bloat One of the most popular and efficient tools for monitoring bloated tables in PostgreSQL is pgstattuple extension. Once installed, you can use the pgstattuple function to get an overview of a particular table SELECT * FROM pgstattuple('your_table_name'); This query will return several key metrics: table_len: Total size of the table/index. tuple_count: Number of tuples (rows) in the table. tuple_len: Total size of all tuples. dead_tuple_count: Number of dead tuples, which contribute to bloat. dead_tuple_len: Total size occupied by dead tuples. SELECT * FROM pgstattuple('test'); table_len tuple_count tuple_len tuple_percent dead_tuple_count dead_tuple_len dead_tuple_percent free_space free_percent 2656870400 60000000 2160000000 81.3 0 0 0 7789300 0.29 Apart from pgstattuple, you can follow other methods to monitor your Postgres bloat, for example, pg_stat_user_tables provides statistics about access to user tables, which can help indirectly identify bloat. If you observe that seq_scan is increasing for a table, it might be an indication that the table's indexes are not performing optimally due to bloat. Other very useful query can be found in Show database bloat - PostgreSQL wiki. How to fix PostgreSQL bloats Rebuilding tables The most effective way to reclaim space in PostgreSQL is to rebuild the table, which physically rewrites the table's data and indexes, eliminating unused space and fragmentation. To rebuild a table and reorganize its physical space we can use native PostgreSQL feature vacuum full, however it requires exclusive lock on the table which, depending on the table size, can have a significant impact on your application availability. A special consideration regarding large object, is a specific vacuumlo process that can be used to remove orphaned large objects from a PostgreSQL database before a vacuum full can be done against pg_largeobjetcs. There are other options that can be used online such as pg_repack and pg_squeeze extensions. For both these extensions the target table must have either a PRIMARY KEY or a UNIQUE index on a NOT NULL column for the operation to be successful. Rebuilding Indexes In PostgreSQL B-tree index pages that become completely empty can be reclaimed and reused. However, partially emptied pages may still lead to inefficient space utilisation. For example, if most index entries on a page are deleted but a small number remain, the page continues to occupy space. As a result, workloads that repeatedly delete most, but not all, index entries across many key ranges can gradually accumulate sparsely populated index pages and lead to index bloat. For these usage patterns, periodic REINDEX should be considered to restore more efficient space utilisation. Optimizing indexing Regularly review and remove unnecessary, overlapping, or redundant indexes to prevent their contribution to bloat. We can leverage on Azure PostgreSQL Flexible Server index tuning feature for recommendations. Partition large tables Bulk data loads and deletions can be handled more efficiently through TABLE PARTITIONING, provided the partitioning strategy is designed around the workload. Instead of deleting large volumes of rows, an entire partition can be removed using DROP TABLE or detached with ALTER TABLE DETACH PARTITION. This is significantly faster than performing a bulk DELETE and avoids the additional VACUUM work that large deletions can generate Fine tuning autovacuum If autovacuum does not run frequently or aggressively enough, dead tuples can accumulate, causing PostgreSQL to consume additional disk space and potentially leading to significant table bloat. By tuning autovacuum thresholds and execution settings to match your workload, particularly for tables with heavy DML activity, you can ensure that dead space is reclaimed sooner and made available for reuse. Difference between dead tuples and reusable free space Characteristic Dead Tuples Reusable Free Space Definition Deleted or obsolete row versions that are no longer valid for new transactions. Valid empty space within a page that has been cleared of dead metadata. Reusability Cannot be overwritten by new INSERT or UPDATE operations. Can be immediately reused for incoming row versions. Visibility Trapped by the system until active older transactions finish using them. Available to the engine and registered in the Free Space Map (FSM). How to Resolve A VACUUM cycle purges dead tuples, turning them into Free Space. A VACUUM FULL or pg_repack is required to shrink the file and return it to the OS. Overhead of Diagnostics and Maintenance Bloat maintenance is not free. Both identifying bloat and reclaiming disk space can consume significant database resources, so these operations should be planned carefully on production systems. pgstattuple diagnostics: Detailed inspection of large tables can generate considerable read I/O and buffer activity. For routine monitoring, lightweight statistics such as n_dead_tup from pg_stat_user_tables are generally better suited to identifying potential problematic tables, while deeper inspection can be reserved for targeted investigations. VACUUM FULL: Reclaiming disk space with VACUUM FULL requires rewriting the table and holding an ACCESS EXCLUSIVE lock. This can make the table unavailable to concurrent workloads and requires additional disk space while the new copy is created. pg_repack: For environments where prolonged blocking is unacceptable, pg_repack provides an online alternative that allows normal activity during most of the rebuild. However, the operation still consumes I/O, storage and WAL resources and may require brief locking during its final stages. Test case Let’s run a test case to show how bloated tables and bloated indexes can impact storage usage on a PostgreSQL database, as well as impact on query performance. This test was run in an Azure PostgreSQL Flexible Server Version 16.15 with a compute size Standard_D2ds_v5 (2 vCores, 8 GiB memory, 3750 max iops) / 256 GiB. postgres=> CREATE DATABASE bloat; CREATE DATABASE postgres=> \c bloat bloat=> SELECT pg_size_pretty(pg_database_size('bloat')) AS db_size; db_size 7719 kB bloat=> CREATE TABLE test (col1 INT, col2 INT, col3 INT); CREATE TABLE bloat=> INSERT INTO test (col1,col2,col3) SELECT i,i,i FROM generate_series(1, 600000000) AS t(i); bloat=> select count(*) from test; count 600000000 bloat=> CREATE UNIQUE INDEX idx1 ON test (col1); bloat=> SELECT pg_size_pretty(pg_database_size('bloat')) AS db_size; db_size 37 GB bloat=> SELECT pg_size_pretty(pg_total_relation_size('public.test')) AS table_total_size; table_total_size 37 GB bloat=> SELECT pg_size_pretty(pg_relation_size('public.test')) AS table_size; table_size 25 GB bloat=> SELECT pg_size_pretty(pg_relation_size('public.idx1')) AS index_size; index_size 12 GB bloat=> SELECT schemaname, relname, n_dead_tup, n_live_tup, round(n_dead_tup::float/n_live_tup::float*100)dead_pct, autovacuum_count, last_vacuum, last_autovacuum, last_autoanalyze, last_analyze FROM pg_stat_all_tables WHERE n_live_tup > 0 AND schemaname='public' AND relname ='test'; schemaname | relname | n_dead_tup | n_live_tup | dead_pct | autovacuum_count | last_vacuum | last_autovacuum | last_autoanalyze | last_analyze ------------+---------+------------+------------+----------+------------------+-------------+-----------------+------------------+-------------- public | test | 0 | 600000000 | 0 | 0 | | | | bloat=> SELECT * FROM pgstattuple('test'); table_len | tuple_count | tuple_len | tuple_percent | dead_tuple_count | dead_tuple_len | dead_tuple_percent | free_space | free_percent -------------+-------------+-------------+---------------+------------------+----------------+--------------------+------------+-------------- 26568654848 | 600000000 | 21600000000 | 81.3 | 0 | 0 | 0 | 77844016 | 0.29 In above output from pg_stat_all_tables, we can see table test with no dead_tuples (n_dead_tup) and from pgstattuple output we confirm it with dead_tuple_count and see there’s very low free space available as well. Server-wide storage usage increases after table test and index idx1 creation bloat=> CREATE TABLE test2 AS SELECT * FROM test; CREATE TABLE bloat=> SELECT pg_size_pretty(pg_relation_size('public.test2')) AS table_size; table_size 25 GB bloat=> \dt+ List of relations Schema | Name | Type | Owner | Persistence | Access method | Size | Description --------+-------+-------+-------+-------------+---------------+-------+------------- public | test | table | edu | permanent | heap | 25 GB | public | test2 | table | edu | permanent | heap | 25 GB | (2 rows) bloat=> \d test Table "public.test" Column | Type | Collation | Nullable | Default --------+---------+-----------+----------+--------- col1 | integer | | | col2 | integer | | | col3 | integer | | | Indexes: "idx1" UNIQUE, btree (col1) bloat=> \d test2 Table "public.test2" Column | Type | Collation | Nullable | Default --------+---------+-----------+----------+--------- col1 | integer | | | col2 | integer | | | col3 | integer | | | Server-wide storage usage increases after table test2 creation bloat=> \timing Timing is on. bloat=> EXPLAIN ANALYZE SELECT t.col1, t2.col2 FROM test t JOIN test2 t2 ON t.col1 = t2.col1 AND t2.col1 = 6777731; QUERY PLAN Nested Loop (cost=1000.58..6369286.70 rows=1 width=8) (actual time=120379.691..120439.792 rows=1 loops=1) -> Index Only Scan using idx1 on test t (cost=0.57..2.59 rows=1 width=4) (actual time=0.820..0.824 rows=1 loops=1) Index Cond: (col1 = 6777731) Heap Fetches: 0 -> Gather (cost=1000.00..6369284.10 rows=1 width=8) (actual time=120378.867..120438.962 rows=1 loops=1) Workers Planned: 2 Workers Launched: 2 -> Parallel Seq Scan on test2 t2 (cost=0.00..6368284.00 rows=1 width=8) (actual time=113739.478..120360.332 rows=0 loops=3) Filter: (col1 = 6777731) Rows Removed by Filter: 200000000 Planning Time: 0.944 ms Execution Time: 120439.911 ms bloat=> DELETE FROM test2 WHERE col1 < 6777731; DELETE 6777730 bloat=> DELETE FROM test2 WHERE col1 > 6777731; DELETE 593222269 bloat=> SELECT COUNT(*) FROM test2; count ------- 1 Time: 162497.229 ms (02:42.497) bloat=> SELECT schemaname, relname,n_dead_tup, n_live_tup, autovacuum_count, last_vacuum, last_autovacuum, last_autoanalyze, last_analyze FROM pg_stat_all_tables WHERE relname IN ('test2'); schemaname | relname | n_dead_tup | n_live_tup | autovacuum_count | last_vacuum | last_autovacuum | last_autoanalyze | last_analyze ------------+---------+------------+------------+------------------+-------------+-------------------------------+-------------------------------+-------------- public | test2 | 151260968 | 0 | 2 | | 2026-10-28 15:42:04.591895+00 | 2026-10-28 15:42:08.369063+00 | public | test | 0 | 600000140 | 1 | | 2026-10-19 14:39:09.677403+00 | 2026-10-19 14:39:27.062848+00 | (1 row) bloat=> SELECT schemaname, relname,n_dead_tup, n_live_tup, autovacuum_count, last_vacuum, last_autovacuum, last_autoanalyze, last_analyze FROM pg_stat_all_tables WHERE relname IN ('test2'); schemaname | relname | n_dead_tup | n_live_tup | autovacuum_count | last_vacuum | last_autovacuum | last_autoanalyze | last_analyze ------------+---------+------------+------------+------------------+-------------+-------------------------------+-------------------------------+-------------- public | test2 | 0 | 0 | 3 | | 2026-10-28 15:52:23.885401+00 | 2026-10-28 15:42:08.369063+00 | (1 row) bloat=> SELECT * FROM pgstattuple('test2'); table_len | tuple_count | tuple_len | tuple_percent | dead_tuple_count | dead_tuple_len | dead_tuple_percent | free_space | free_percent -------------+-------------+-----------+---------------+------------------+----------------+--------------------+-------------+-------------- 26568818688 | 1 | 36 | 0 | 0 | 0 | 0 | 26464870540 | 99.61 (1 row) Time: 266381.968 ms (04:26.382) bloat=> SELECT pg_size_pretty(pg_relation_size('public.test2')) AS table_size; table_size 25 GB (1 row) Time: 4.848 ms As we can see even after rows deletion and vacuum performed to remove dead tuples, storage hasn’t decreased. bloat=> EXPLAIN ANALYZE SELECT t.col1, t2.col2 FROM test t JOIN test2 t2 ON t.col1 = t2.col1 AND t2.col1 = 6777731; QUERY PLAN ------------------------------------------------------------------------------------------------------------------------ Nested Loop (cost=0.57..3243266.60 rows=1 width=8) (actual time=99702.040..126103.260 rows=1 loops=1) -> Index Only Scan using idx1 on test t (cost=0.57..2.59 rows=1 width=4) (actual time=1.605..1.609 rows=1 loops=1) Index Cond: (col1 = 6777731) Heap Fetches: 0 -> Seq Scan on test2 t2 (cost=0.00..3243264.00 rows=1 width=8) (actual time=99700.432..126101.645 rows=1 loops=1) Filter: (col1 = 6777731) Planning Time: 0.645 ms Execution Time: 126103.317 ms (8 rows) Time: 126107.410 ms (02:06.107) bloat=> VACUUM FULL test2; Time: 126024.034 ms (02:06.024) bloat=> SELECT pg_size_pretty(pg_relation_size('public.test2')) AS table_size; table_size 8192 bytes (1 row) Time: 3.604 ms bloat=> SELECT * FROM pgstattuple('test2'); table_len | tuple_count | tuple_len | tuple_percent | dead_tuple_count | dead_tuple_len | dead_tuple_percent | free_space | free_percent -----------+-------------+-----------+---------------+------------------+----------------+--------------------+------------+-------------- 8192 | 1 | 36 | 0.44 | 0 | 0 | 0 | 8120 | 99.12 (1 row) Time: 3.682 ms bloat=> EXPLAIN ANALYZE SELECT t.col1, t2.col2 FROM test t JOIN test2 t2 ON t.col1 = t2.col1 AND t2.col1 = 6777731; QUERY PLAN ------------------------------------------------------------------------------------------------------------------------ Nested Loop (cost=0.57..3.62 rows=1 width=8) (actual time=0.033..0.036 rows=1 loops=1) -> Index Only Scan using idx1 on test t (cost=0.57..2.59 rows=1 width=4) (actual time=0.023..0.024 rows=1 loops=1) Index Cond: (col1 = 6777731) Heap Fetches: 0 -> Seq Scan on test2 t2 (cost=0.00..1.01 rows=1 width=8) (actual time=0.009..0.009 rows=1 loops=1) Filter: (col1 = 6777731) Planning Time: 0.143 ms Execution Time: 0.067 ms (8 rows) Time: 3.663 ms Now after vacuum full storage has decreased as expected. Note: Row versions may still be required by active snapshots and cannot be removed. Long-running transactions or other snapshot-retention conditions can therefore limit space reclamation. VACUUM FULL also requires an exclusive lock and may wait for transactions accessing the table to finish. Always investigate these conditions before running maintenance. test2: Before and after VACUUM FULL Metric Before VACUUM FULL (after autovacuum) After VACUUM FULL Physical table size 26,568,818,688 bytes (reported as 25 GB) 8192 bytes Query execution time (EXPLAIN ANALYZE) 126103.317 ms 0.067 ms Both measurements concern test2 with one live row. Execution times are the server-side values reported by EXPLAIN ANALYZE, not the client-reported elapsed times. These individual test runs illustrate the effect of the rebuild in this scenario and are not a general performance benchmark. Conclusion PostgreSQL table bloat is not simply a matter of counting dead tuples. Autovacuum can remove obsolete row versions and make their space available for reuse without substantially reducing the physical table size. In this test, test2 contained only one live row and no dead tuples after autovacuum, yet still occupied approximately 25 GB, with 99.61% of its space reported as free. The query continued to scan this large physical footprint, demonstrating why a low dead-tuple count alone does not establish that a table is space-efficient. “Rewriting” test2 with VACUUM FULL reduced the table to 8192 bytes, and the recorded query execution time fell from 126103.317 ms to 0.067 ms. These results illustrate the benefit of reclaiming excessive unused space in this specific scenario as the performance benefit for other workloads will vary. The comparison concerns a table reduced to a single row and it does not isolate index bloat or establish a general benchmark. The practical approach is to prevent avoidable bloat first: tune autovacuum for the workload, investigate long-running transactions and replication-related retention, and review indexing and partitioning strategies. Use lightweight statistics to identify candidates for investigation, then targeted diagnostics to assess dead tuples, reusable free space and physical size alongside query behaviour. When a rebuild is justified, choose VACUUM FULL or a supported online alternative according to locking tolerance, available storage and resource capacity. Successful maintenance should address the cause of bloat as well as its symptoms, and its benefit should be verified through before-and-after measurements. References https://learn.microsoft.com/azure/postgresql/troubleshoot/how-to-autovacuum-tuning https://www.postgresql.org/docs/current/sql-vacuum.html https://www.postgresql.org/docs/current/pgstattuple.html https://www.postgresql.org/docs/current/sql-vacuum.html https://github.com/reorg/pg_repack https://learn.microsoft.com/azure/postgresql/troubleshoot/how-to-perform-fullvacuum-pg-repack https://github.com/cybertec-postgresql/pg_squeeze https://www.postgresql.org/docs/current/sql-reindex.html https://www.postgresql.org/docs/current/ddl-partitioning.html https://wiki.postgresql.org/wiki/Show_database_bloat114Views0likes0CommentsPostgreSQL 18 EXPLAIN Improvements
PostgreSQL 18 makes EXPLAIN more useful for real-world performance troubleshooting by exposing more of what happens during query execution. Beyond plan shape and execution time, it provides better visibility into buffer activity, repeated index access, memory and disk usage, WAL behavior, parallel execution, and window-function processing. This makes it easier to identify the actual source of a performance issue and make more targeted tuning decisions. In this blog, we’ll explore the key EXPLAIN improvements in PostgreSQL 18 and see how they can help diagnose performance issues more effectively. What’s New in PostgreSQL 18 EXPLAIN 1) BUFFERS Is Now Automatic with EXPLAIN ANALYZE Before PostgreSQL 18, EXPLAIN ANALYZE did not show buffer stats unless you explicitly added BUFFERS. EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 5001; EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders WHERE customer_id = 5001; PostgreSQL 18 makes EXPLAIN ANALYZE more useful by including buffer statistics automatically. This helps reveal what execution time alone cannot: where the data is coming from. shared hit=120 read=12500 → disk-heavy shared hit=12500 read=120 → cache-heavy When investigating performance, correlate time, rows/loops, and buffer activity. The following example creates a large table with multiple rows per customer and uses an index to retrieve one customer’s rows. We then run the same EXPLAIN ANALYZE query in PostgreSQL 17 and PostgreSQL 18. -- Setup CREATE TABLE buffer_test (id INT, customer_id INT); INSERT INTO buffer_test SELECT x, (x % 10000) + 1 FROM generate_series(1,1000000) x; CREATE INDEX ON buffer_test(customer_id); VACUUM ANALYZE buffer_test; EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF) SELECT * FROM buffer_test WHERE customer_id = 5001; EXPLAIN Output PG 17 Bitmap Heap Scan on buffer_test (actual rows=100 loops=1) Recheck Cond: (customer_id = 5001) Heap Blocks: exact=100 -> Bitmap Index Scan on buffer_test_customer_id_idx (actual rows=100 loops=1) Index Cond: (customer_id = 5001) Planning Time: 0.076 ms Execution Time: 0.225 ms (7rows) EXPLAIN output PG 18 Bitmap Heap Scan on buffer_test (actual rows=100.00 loops=1) Recheck Cond: (customer_id = 5001) Heap Blocks: exact=100 Buffers: shared hit=103 -> Bitmap Index Scan on buffer_test_customer_id_idx (actual rows=100.00 loops=1) Index Cond: (customer_id = 5001) Index Searches: 1 Buffers: shared hit=3 Planning: Buffers: shared hit=6 Planning Time: 0.097 ms Execution Time: 0.142 ms (12 rows) In the PostgreSQL 18 output, focus on Buffers: shared hit and shared read to determine whether the query is primarily using cached pages or reading from storage. A high read count may indicate an I/O-heavy execution, while a high hit count indicates that most pages were already available in shared buffers. A query with substantial physical reads may be more I/O-sensitive, while high shared hits indicate the required pages were already cached. 2) Index Search Counts (Index Searches) PostgreSQL 18 adds Index Searches to show how many separate index searches were performed by an index scan. This is especially useful for nested loop joins, where an inner index scan may be searched repeatedly for rows produced by the outer side. The following example joins customers_idx with orders_idx. The query retrieves 10 customers, and for each customer PostgreSQL searches the orders index for matching rows. This makes it easy to see how PostgreSQL 18 exposes repeated index access that was not directly visible in PostgreSQL 17. -- Setup CREATE TABLE customers_idx ( id INT PRIMARY KEY ); CREATE TABLE orders_idx ( id INT, customer_id INT ); INSERT INTO customers_idx SELECT x FROM generate_series(1,1000) x; INSERT INTO orders_idx SELECT x, (x % 1000) + 1 FROM generate_series(1,100000) x; CREATE INDEX orders_customer_idx ON orders_idx(customer_id); VACUUM ANALYZE customers_idx; VACUUM ANALYZE orders_idx; EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF) SELECT c.id, o.id FROM customers_idx c JOIN orders_idx o ON o.customer_id = c.id WHERE c.id <= 10; EXPLAIN Output PG 17 Nested Loop (actual rows=1000 loops=1) -> Index Only Scan using customers_idx_pkey on customers_idx c (actual rows=10 loops=1) Index Cond: (id <= 10) Heap Fetches: 0 -> Bitmap Heap Scan on orders_idx o (actual rows=100 loops=10) Recheck Cond: (c.id = customer_id) Heap Blocks: exact=1000 -> Bitmap Index Scan on orders_customer_idx (actual rows=100 loops=10) Index Cond: (customer_id = c.id) Planning Time: 0.305 ms Execution Time: 0.666 ms (11 rows) EXPLAIN Output PG 18 Nested Loop (actual rows=1000.00 loops=1) Buffers: shared hit=1023 -> Index Only Scan using customers_idx_pkey on customers_idx c (actual rows=10.00 loops=1) Index Cond: (id <= 10) Heap Fetches: 0 Index Searches: 1 Buffers: shared hit=3 -> Bitmap Heap Scan on orders_idx o (actual rows=100.00 loops=10) Recheck Cond: (c.id = customer_id) Heap Blocks: exact=1000 Buffers: shared hit=1020 -> Bitmap Index Scan on orders_customer_idx (actual rows=100.00 loops=10) Index Cond: (customer_id = c.id) Index Searches: 10 Buffers: shared hit=20 Planning: Buffers: shared hit=77 read=3 Planning Time: 0.362 ms Execution Time: 0.590 ms (19 rows) Compare Index Searches with loops, actual rows, and Buffers. Here, the inner index is searched 10 times, exposing the repeated index probes performed by the nested loop. A high Index Searches count can reveal expensive repeated index access and help determine whether the join strategy, indexing, or query structure should be reviewed. 3) Fractional Actual Row Counts EXPLAIN now supports fractional row averages for repeatedly executed nodes, for example: rows=0.25 loops=1000 This is not “partial rows”; it is average output per execution. It helps reveal behavior in: nested loops parameterized scans correlated subqueries selective joins The following example uses a correlated subquery that executes repeatedly but returns a row only for a fraction of those executions. PostgreSQL 18 preserves fractional actual rows values, providing a more accurate picture of how often the node produces a result. -- Setup: CREATE TABLE frac_outer (id INT PRIMARY KEY); CREATE TABLE frac_inner (id INT PRIMARY KEY,value TEXT); INSERT INTO frac_outer SELECT x FROM generate_series(1,1000) x; -- Only 1 out of every 4 outer rows has a match INSERT INTO frac_inner SELECT x, 'match' FROM generate_series(4,1000,4) x; EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF) SELECT o.id, (SELECT i.value FROM frac_inner i WHERE i.id = o.id) FROM frac_outer o; EXPLAIN Output PG 17: Seq Scan on frac_outer o (actual rows=1000 loops=1) SubPlan 1 -> Index Scan using frac_inner_pkey on frac_inner i (actual rows=0 loops=1000) Index Cond: (id = o.id) Planning Time: 0.082 ms Execution Time: 0.790 ms (6 rows) EXPLAIN Output PG 18 Seq Scan on frac_outer o (actual rows=1000.00 loops=1) Buffers: shared hit=1255 SubPlan 1 -> Index Scan using frac_inner_pkey on frac_inner i (actual rows=0.25 loops=1000) Index Cond: (id = o.id) Index Searches: 1000 Buffers: shared hit=1250 Planning: Buffers: shared hit=27 Planning Time: 0.190 ms Execution Time: 0.752 ms (11 rows) Compare actual rows with loops. An actual rows=0.25 over 1,000 loops indicates that the node returns a row on average once every four executions. This is useful when troubleshooting nested loops and correlated subqueries where rounding the average to zero can hide meaningful execution behavior. 4) Better Memory/Disk Visibility for More Nodes PostgreSQL 18 extends memory and disk reporting to Material, Window Aggregate, and CTE-related nodes. This helps identify when growing intermediate results start using disk and cause query performance to degrade. Rather than immediately increasing work_mem, use EXPLAIN ANALYZE to determine which node is consuming resources and why. The following query calculates a running total over one million rows with work_mem intentionally limited to 1 MB. This creates memory pressure and causes the Sort operation to spill to disk, making it easier to see how PostgreSQL 18 identifies resource usage at individual plan nodes. -- Setup CREATE TABLE memory_test (id INT, dept_id INT, amount NUMERIC); INSERT INTO memory_test SELECT x, (x % 10) + 1, random() * 1000 FROM generate_series(1,1000000) x; VACUUM ANALYZE memory_test; SET work_mem = '1MB'; EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF) SELECT id, dept_id,amount, SUM(amount) OVER ( PARTITION BY dept_id ORDER BY id) FROM memory_test; EXPLAIN Output PG 17 WindowAgg (actual rows=1000000 loops=1) -> Sort (actual rows=1000000 loops=1) Sort Key: dept_id, id Sort Method: external merge Disk: 28592kB -> Seq Scan on memory_test (actual rows=1000000 loops=1) Planning Time: 0.159 ms Execution Time: 1069.011 ms (7 rows) EXPLAIN Output PG 18 WindowAgg (actual rows=1000000.00 loops=1) Window: w1 AS (PARTITION BY dept_id ORDER BY id) Storage: Memory Maximum Storage: 17kB Buffers: shared hit=6371, temp read=10716 written=10781 -> Sort (actual rows=1000000.00 loops=1) Sort Key: dept_id, id Sort Method: external merge Disk: 28592kB Buffers: shared hit=6371, temp read=10716 written=10781 -> Seq Scan on memory_test (actual rows=1000000.00 loops=1) Buffers: shared hit=6370 Planning Time: 0.055 ms Execution Time: 1129.466 ms (12 rows) The WindowAgg uses only 17 KB, while the Sort spills about 28 MB to disk. This clearly identifies the Sort, rather than the WindowAgg, as the source of the disk spill. This additional visibility helps pinpoint the resource-intensive node before making tuning changes such as increasing work_mem. 5) Better WAL Visibility (buffers full) For write-heavy statements, PostgreSQL already supports: EXPLAIN (ANALYZE, WAL) UPDATE ...; PostgreSQL 18 adds another signal: how often WAL buffers became full. Look at WAL as a set: Records : WAL records generated Fpi : Full-page images written to WAL Bytes : Total WAL volume generated buffers full : Number of times WAL buffers became full rows modified: Number of rows affected by the operation This is useful for bulk UPDATE/DELETE/INSERT diagnostics and replication-impact analysis. The following example updates 250,000 rows after a checkpoint, generating substantial WAL activity. -- Setup CREATE TABLE wal_test (id INT PRIMARY KEY,status INT,payload TEXT); INSERT INTO wal_test SELECT x, 0, repeat('x', 500) FROM generate_series(1,500000) x; VACUUM ANALYZE wal_test; CHECKPOINT; EXPLAIN (ANALYZE, WAL, COSTS OFF, TIMING OFF) UPDATE wal_test SET status = 1 WHERE id <= 250000; EXPLAIN Output PG 17 Update on wal_test (actual rows=0 loops=1) WAL: records=753424 fpi=17365 bytes=187303863 -> Index Scan using wal_test_pkey on wal_test (actual rows=250000 loops=1) Index Cond: (id <= 250000) Planning Time: 0.231 ms Execution Time: 2105.951 ms (6 rows) EXPLAIN Output PG 18 Update on wal_test (actual rows=0.00 loops=1) Buffers: shared hit=1821461 dirtied=34716 written=17355 WAL: records=753424 fpi=17365 bytes=184498617 buffers full=11293 -> Index Scan using wal_test_pkey on wal_test (actual rows=250000.00 loops=1) Index Cond: (id <= 250000) Index Searches: 1 Buffers: shared hit=17353 Planning: Buffers: shared hit=14 dirtied=1 Planning Time: 0.187 ms Execution Time: 2149.051 ms (11 rows) Check buffers full alongside WAL records, FPIs, and bytes to identify how often WAL buffers became full during the write operation. In PostgreSQL 18, inspect records, fpi, bytes, and buffers full together with the number of affected rows. These values help assess the WAL cost of a bulk operation and its possible effect on write throughput, storage, and replication. Frequent buffers full events can indicate sustained WAL pressure, but should be evaluated alongside total WAL volume and execution behavior 6) Improved Parallel Bitmap Heap Scan Stats PostgreSQL 18 adds worker cache statistics for parallel bitmap heap scans, improving per-worker visibility in parallel plans. When analyzing parallel execution, go beyond Workers Planned and Workers Launched and correlate worker-level behavior with buffers and row flow. The following example uses a Parallel Bitmap Heap Scan to retrieve matching rows through multiple processes. PostgreSQL 18 exposes additional worker-level statistics, allowing the activity of individual workers to be compared with the overall parallel scan. -- Setup CREATE TABLE pb_test AS SELECT x AS id, x % 10 AS category FROM generate_series(1,100000) x; CREATE INDEX pb_test_category_idx ON pb_test(category); VACUUM ANALYZE pb_test; SET max_parallel_workers_per_gather = 2; SET min_parallel_table_scan_size = 0; SET parallel_setup_cost = 0; SET parallel_tuple_cost = 0; SET enable_seqscan = off; SET enable_indexscan = off; EXPLAIN (ANALYZE, VERBOSE, BUFFERS, COSTS OFF, TIMING OFF) SELECT * FROM pb_test WHERE category < 3; EXPLAIN Output PG 17 Gather (actual rows=30000 loops=1) Output: id, category Workers Planned: 2 Workers Launched: 1 Buffers: shared hit=443 read=27 -> Parallel Bitmap Heap Scan on public.pb_test (actual rows=15000 loops=2) Output: id, category Recheck Cond: (pb_test.category < 3) Heap Blocks: exact=443 Buffers: shared hit=443 read=27 Worker 0: actual rows=0 loops=1 -> Bitmap Index Scan on pb_test_category_idx (actual rows=30000 loops=1) Index Cond: (pb_test.category < 3) Buffers: shared read=27 Query Identifier: 6421728296517627451 Planning: Buffers: shared hit=9 Planning Time: 0.065 ms Execution Time: 12.218 ms (19 rows) EXPLAIN Output PG 18 Gather (actual rows=30000.00 loops=1) Output: id, category Workers Planned: 2 Workers Launched: 1 Buffers: shared hit=445 read=27 -> Parallel Bitmap Heap Scan on public.pb_test (actual rows=15000.00 loops=2) Output: id, category Recheck Cond: (pb_test.category < 3) Heap Blocks: exact=443 Buffers: shared hit=445 read=27 Worker 0: actual rows=0.00 loops=1 Buffers: shared hit=2 -> Bitmap Index Scan on pb_test_category_idx (actual rows=30000.00 loops=1) Index Cond: (pb_test.category < 3) Index Searches: 1 Buffers: shared read=27 Query Identifier: 6365259442062613493 Planning: Buffers: shared hit=9 Planning Time: 0.085 ms Execution Time: 17.366 ms (21 rows) Workers Planned and Workers Launched alone do not show how much useful work each worker performed. Worker-level statistics can reveal cases where work distribution is uneven or a launched worker contributes very little. 7) Disabled Plan Nodes Are Explicitly Identified When experimenting with planner toggles: SET enable_seqscan = off; SET enable_hashjoin = off; SET enable_nestloop = off; PostgreSQL 18 can indicate disabled nodes more clearly in plan output, making “what-if” diagnostics easier to interpret. The following example disables sequential scans and executes a leading-wildcard search that has no suitable B-tree index access path. PostgreSQL still needs to perform a sequential scan, but PostgreSQL 18 makes this explicit in the plan with Disabled: true. -- Setup CREATE TABLE disabled_test ( id INT, notes TEXT); INSERT INTO disabled_test SELECT x, CASE WHEN x % 100 = 0 THEN 'order checked manually' ELSE 'normal order' END FROM generate_series(1,100000) x; VACUUM ANALYZE disabled_test; SET enable_seqscan = off; EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF) SELECT * FROM disabled_test WHERE notes LIKE '%checked%'; EXPLAIN Output PG 17: Seq Scan on disabled_test (actual rows=1000 loops=1) Filter: (notes ~~ '%checked%'::text) Rows Removed by Filter: 99000 Planning Time: 0.065 ms Execution Time: 7.045 ms (5 rows) EXPLAIN Output PG 18: Seq Scan on disabled_test (actual rows=1000.00 loops=1) Disabled: true Filter: (notes ~~ '%checked%'::text) Rows Removed by Filter: 99000 Buffers: shared hit=642 Planning: Buffers: shared hit=8 Planning Time: 0.096 ms Execution Time: 6.992 ms (9 rows) This makes planner experiments easier to interpret because you can distinguish between a normally selected plan node and one PostgreSQL used even though that planner method had been disabled. 8) Better Window Function Visibility Plans now expose additional details about window-function arguments. Combined with richer Window Aggregate memory/disk reporting, this improves troubleshooting for analytical workloads using: ROW_NUMBER() RANK() SUM() OVER (...) AVG() OVER (...) LAG() / LEAD() The following example uses LAG() to retrieve the previous value within each department. PostgreSQL 18 exposes more information about the window itself, making it easier to associate the window function with its partitioning, ordering, and resource usage. -- Setup CREATE TABLE window_test (id INT,dept_id INT,amount NUMERIC); INSERT INTO window_test VALUES (1, 1, 100), (2, 1, 200), (3, 1, 300), (4, 2, 150), (5, 2, 250); VACUUM ANALYZE window_test; EXPLAIN (ANALYZE, VERBOSE, COSTS OFF, TIMING OFF) SELECT id, dept_id,amount, LAG(amount, 1, 0) OVER ( PARTITION BY dept_id ORDER BY id ) AS previous_amount FROM window_test; EXPLAIN Output PG 17 WindowAgg (actual rows=5 loops=1) Output: id, dept_id, amount, lag(amount, 1, '0'::numeric) OVER (?) -> Sort (actual rows=5 loops=1) Output: id, dept_id, amount Sort Key: window_test.dept_id, window_test.id Sort Method: quicksort Memory: 25kB -> Seq Scan on public.window_test (actual rows=5 loops=1) Output: id, dept_id, amount Query Identifier: -674688654798365229 Planning Time: 0.083 ms Execution Time: 0.038 ms (11 rows) EXPLAIN Output PG 18 WindowAgg (actual rows=5.00 loops=1) Output: id, dept_id, amount, lag(amount, 1, '0'::numeric) OVER w1 Window: w1 AS (PARTITION BY window_test.dept_id ORDER BY window_test.id) Storage: Memory Maximum Storage: 17kB Buffers: shared hit=38 -> Gather Merge (actual rows=5.00 loops=1) Output: id, dept_id, amount Workers Planned: 1 Workers Launched: 1 Buffers: shared hit=38 -> Sort (actual rows=2.50 loops=2) Output: id, dept_id, amount Sort Key: window_test.dept_id, window_test.id Sort Method: quicksort Memory: 25kB Buffers: shared hit=38 Worker 0: actual rows=0.00 loops=1 Sort Method: quicksort Memory: 25kB Buffers: shared hit=37 -> Parallel Seq Scan on public.window_test (actual rows=2.50 loops=2) Disabled: true Output: id, dept_id, amount Buffers: shared hit=1 Worker 0: actual rows=0.00 loops=1 Query Identifier: -8082484858136532801 Planning: Buffers: shared hit=13 Planning Time: 0.106 ms Execution Time: 13.623 ms (28 rows) Check the Window, Output, and Storage fields to understand the window definition, function arguments, and WindowAgg memory usage. Instead of displaying only OVER (?), PostgreSQL 18 makes it easier to identify the applicable window definition and correlate it with resource consumption. PostgreSQL 17 and Earlier vs PostgreSQL 18 Area Earlier behavior PostgreSQL 18 Buffers with ANALYZE Usually requested explicitly Included automatically Index diagnostics Loops/time based interpretation Adds Index Searches Row precision Less precise averages Fractional row counts Material/Window/CTE resource visibility Limited Expanded memory/disk details WAL diagnostics records/fpi/bytes Adds buffers full Parallel bitmap visibility Less worker cache detail Worker cache statistics Disabled nodes Less explicit Explicitly indicated Conclusion With PostgreSQL 18, EXPLAIN provides deeper visibility into query execution through automatic buffer statistics, index search counts, fractional row reporting, improved memory and WAL details, worker-level cache statistics, and clearer window-function information. These enhancements make it easier to identify bottlenecks and make evidence-based tuning decisions.148Views1like0CommentsDecisions, decisions: Your guide to PostgreSQL at Microsoft Ignite 2026
Microsoft Ignite returns to San Francisco and online from November 17 to 20, 2026, and PostgreSQL is all over the agenda. Postgres has become the database of choice for modern application development, and more organizations are now relying on it to modernize the systems they already run and to power the AI apps and agents they are building next. Whether you are a technology leader shaping your data strategy, an architect weighing your options, or a developer who wants to see what's possible, we've done the decision making for you just this once. Below are 20 sessions planned for Ignite with PostgreSQL at their core that you can add to your schedule. Plus, we’ve highlighted a few activations and surprises you should plan to check out if you want to learn more about Postgres, engage with the experts, and potentially win an Xbox. One more thing: we have some exciting news to share for PostgreSQL at Microsoft. Tune in on Day 1, Tuesday, November 17, and keep an eye on this blog. Before you build your schedule Ignite has several session formats, and not all of them are streamed. Breakouts are 45 minutes, streamed live for the digital audience and available on demand. Theater sessions (25 minutes) are in person only but recorded for on-demand viewing. Lightning talks (15 minutes), table talks (45 minutes) and hands-on labs (75 minutes) are in-person experiences and are not recorded, so plan to be in the room. Labs require an RSVP. All times below are Pacific Time. Use the session scheduler in the Ignite catalog to save your favorites: Start with the big picture then find the right fit If you're new to PostgreSQL on Azure, or you're deciding where your next workload should land, start here. BRK362 | Data Foundations for Modern Apps, AI, and Agents Wednesday, Nov 18, 9:00 AM Join Microsoft engineering leaders to see how the database portfolio across Azure and Microsoft Fabric helps organizations modernize mission-critical applications while building a new generation of intelligent experiences. BRK366 | Database SOS: Choosing the right engine for your job Thursday, Nov 19, 1:30 PM Experts from across the Azure databases team compare database engines and share how to pick the right one for your next project. THR923 | What's new for open source data on Azure? Thursday, Nov 19, 1:30 PM Catch the most important open-source data updates on Azure in one technical briefing, including enhancements to Azure HorizonDB and Azure Database for PostgreSQL, and learn which capabilities matter most for your next modernization decision. THR884 | Two PostgreSQL services, one confident architecture decision Wednesday, Nov 18, 2:15 PM Which PostgreSQL on Azure service is the right fit for your workload? See how Azure Database for PostgreSQL compares to Azure HorizonDB across scale, availability, AI integration, operations and modernization needs. TT1865 | Bring your workload, leave with the best Postgres fit Tuesday, Nov 17, 2:00 PM Bring a real workload and pressure-test your architecture with peers and PostgreSQL experts. Compare requirements for scale, availability, migration, AI, operations and cost, and leave with a clearer decision framework, not a generic product pitch. Build AI apps and agents on PostgreSQL For teams turning operational data into AI experiences, these sessions show how to keep the stack simple and the data trusted. BRK370 | Build integrated AI apps with Azure HorizonDB Tuesday, Nov 17, 4:30 PM See how Azure HorizonDB brings PostgreSQL data together with AI functions, durable AI pipelines, vector and hybrid search, semantic ranking and knowledge graphs, through a technical walkthrough and live demo. BRK359 | Build intelligent PostgreSQL apps with Microsoft Fabric HorizonDB Tuesday, Nov 17, 3:15 PM Discover a Fabric-native PostgreSQL experience that lets applications query operational and analytical data through a single PostgreSQL experience, reducing data movement and ETL complexity while delivering real-time insights with built-in governance. THR881 | Microsoft Fabric HorizonDB: One PostgreSQL endpoint for AI apps Thursday, Nov 19, 11:05 AM Build intelligent applications without stitching together databases, analytics platforms and AI services. See how one PostgreSQL endpoint can unify transactional and analytical workloads so you can query live operational data and large-scale analytics together. LTG1254 | 5 ways to simplify your Postgres AI data pipelines on Azure Tuesday, Nov 17, 2:00 PM You can't ship AI features if pipelines break, drift or need constant glue code. Learn five PostgreSQL patterns to keep content fresh, generate embeddings and serve context to your applications. LTG1251 | Do you really need a separate vector database? Wednesday, Nov 18, 9:50 AM Choose a retrieval architecture based on the problem, not the label. In 15 minutes, learn when PostgreSQL-native vector, keyword and hybrid search can support an AI application, when graph context adds value, and which signals truly justify a separate service. LTG1252 | See Azure HorizonDB come alive in VS Code Wednesday, Nov 18, 1:20 PM Watch the PostgreSQL developer experience get faster right inside VS Code. This live demo shows schema exploration, querying and AI-assisted development for Azure HorizonDB without leaving your editor. LAB692 | Build a grounded AI agent with Azure HorizonDB for PostgreSQL Tuesday, Nov 17, 6:15 PM; Wednesday, Nov 18, 12:00 PM; Thursday, Nov 19, 2:45 PM; Friday, Nov 20, 9:00 AM Your agent is only as good as the data behind it. Build a working agent that retrieves trusted context from operational PostgreSQL data: create an AI pipeline, generate embeddings, combine vector and keyword retrieval, and connect the results to an agent workflow. Modernize and migrate with confidence Moving off a legacy database or running a large Postgres fleet? These sessions focus on lowering risk and moving faster. BRK451 | Accelerate Your Move to PostgreSQL with AI-Assisted Migration Thursday, Nov 19, 9:00 AM Modernizing databases doesn't have to be complex. Learn how AI-assisted and built-in tools simplify assessment, schema and code conversion, and data migration, and see a live demo of how to identify blockers early and build a repeatable modernization path. BRK368 | Postgres in Production on Azure: Lessons in Fleet Modernization Thursday, Nov 19, 11:30 AM Running PostgreSQL at scale requires performance, security, resilience and cost efficiency. Explore the latest innovations in Azure Database for PostgreSQL, including fleet management, elastic clusters, next-generation compute and storage, and immutable backups, and leave with proven patterns and real-world insights TT1702 | Eliminate your biggest Oracle migration blocker Thursday, Nov 19, 2:25 PM Bring your hardest Oracle migration question. Discuss assessment gaps, unsupported objects, conversion, validation, downtime and cutover with Microsoft experts and peers, and leave with practical next steps for moving to PostgreSQL on Azure. LTG1257 | Upgrade smarter with next-gen Postgres on Azure Thursday, Nov 19, 3:00 PM Upgrades stall when compatibility and rollback risk aren't proven early. See how to turn your next major-version upgrade on Azure Database for PostgreSQL into a repeatable test plan that checks extensions, performance, operations and rollback. Run PostgreSQL securely and reliably at scale For leaders and operators responsible for uptime, compliance and performance. BRK361 | Azure HorizonDB: Deep Dive into Architecture and Internals Wednesday, Nov 18, 4:15 PM Join the engineering and product leaders behind Azure HorizonDB for a look under the hood of a cloud-native PostgreSQL service: the storage engine, disaggregated compute and storage, replication, recovery design, and the elasticity that delivers predictable performance and resilience at scale. THR882 | Stop tuning databases, start optimizing with AI Thursday, Nov 19, 10:10 AM Most organizations don't have a database performance problem; they have an expertise bottleneck. See a new approach that combines observability, diagnosis, optimization recommendations and controlled remediation in a single AI-powered experience, while you keep governance and control. LTG1258 | Break your Postgres before production causes a breakdown Tuesday, Nov 17, 4:00 PM Validate recovery before an outage becomes the test. Watch a controlled PostgreSQL failure exercise and trace how backup, restore, immutability, geo-redundancy and retention choices affect your recovery objectives. TT1866 | Lock it down: Running PostgreSQL in regulated environments Tuesday, Nov 17, 4:00 PM Compare practical approaches for operating PostgreSQL under security, compliance and recovery requirements, covering identity, FIPS mode, immutable backups, long-term retention and confidential virtual machines. Bring your constraints and hear how peers turn policy into architecture. Play Decision Point: A game for Postgres Between sessions, come put your instincts to the test. Decision Point: A game for Postgresis a browser-based game that puts you in the role of a lead engineer racing to get an AI application launch-ready using Azure HorizonDB in VS Code. You don't need to be a database expert to play. Every round is a real-world decision, and every decision counts. In the "Ship the AI Agent" scenario, you're the lead engineer for Basket IQ, an AI shopping agent that is about to launch. You'll work through three engineering incidents and make the architecture and optimization calls that shape your Launch Readiness score. You'll find Decision Point in The Hub at various spots: Azure Community AMD booth #6044 Azure HorizonDB booth #AZ-11 See you at Ignite Whether you join us in San Francisco or virtually, we can't wait to connect. Register and explore the full catalog, stop by the Azure HorizonDB booth in the Expert Meet-Up area to meet the PostgreSQL team, and follow Microsoft for PostgreSQL on LinkedIn and X for live updates from the event. And don't forget to play Decision Point.147Views1like0CommentsPrivate Database, Public Tools - Securing Azure Database for PostgreSQL Flexible Server Behind MCP
You locked Azure Database for PostgreSQL Flexible Server behind a private network. Congratulations, but a firewall can’t tell what your MCP server is about to do. One poisoned document, one over trusting agent, and your privileged app hands over the whole corporate summary. Politely. Legitimately. No breach required. The fix isn’t more walls. Verify who’s really asking. Swap raw SQL for tight business tools. Lock data down with least privilege and row level security. Treat the LLM as untrusted, and audit every decision. Stop asking “is the database private?” Start asking: who can make it talk, and what can walk out?158Views1like0CommentsAn Index Scan Is Only Half the Story: On-Disk Ordering Affects Performance
Same Query, Same Index, Different Performance I recently worked with a customer planning a migration from on-premises PostgreSQL to Azure Database for PostgreSQL. During performance testing, they noticed something troubling: a query that completed in tens of milliseconds would now take 1-2 seconds in the Azure environment being evaluated. The query was using an index scan, and running it again was fast. But once the relevant data was evicted from cache, the long execution time came back. Naturally, the conversation turned toward storage performance. There was a clear difference in IOPS consumption, with the to-be-production server having 10-20% more IOPS consumption than a server they stood up for comparison purposes. A cold-cache query execution that performed a single Index Scan pulled over 100 pages from heap, whereas the other server only pulled 60 pages. The natural inclination was to think that somehow bloating and/or fragmentation was the cause, so they tried VACUUM FULL but did not see any improvement. That’s when they turned to us. Is the Index Really the Problem? The primary concern that the customer had – an Index Scan was not performing as well as expected – surfaced two hypotheses: something was wrong with the index, (i.e., bloat, leaf density, fragmentation), or something was wrong with the storage. Digging in with pg_stattuple and pg_statindex , we didn’t see anything glaringly wrong with leaf density or fragmentation. We also saw nothing from our telemetry that anything was wrong with the storage. With the usual suspects out of the picture, we needed to get back to the basic principles of indexing. It is important to remember that when it comes to indexing a table, a regular index scan uses the index to locate matching tuples, then visits the table’s heap pages to retrieve them. The index is ordered; the heap doesn’t have to be. Suppose a query returns 200 rows. If those rows live on five heap pages, Postgres can retrieve them with relatively little page access. If they are scattered across 100 pages, retrieving the same 200 rows requires a much larger working set. Both queries can say Index Scan in the execution plan, but that doesn’t mean they do equivalent work. When those pages are cached, the difference can be easy to miss. When they need to be read from storage, the extra page accesses become much more expensive. Correlation Was the Hint One useful clue was in pg_stats . Using generic table and column names here: SELECT correlation FROM pg_stats WHERE schemaname = 'public' AND tablename = 'order_items' AND attname = 'order_id'; correlation describes how closely a column’s logical ordering follows the table’s physical ordering. Values near 1 or -1 indicate strong ordering; values near 0 indicate little relationship. Postgres uses this statistic when estimating index scan costs. In this case, the slower environment had a correlation around 0.037 , while the faster performance-test environment was around 0.571 . That certainly suggested a layout difference! But correlation is a sampled, column-wide statistic. It doesn’t tell us exactly how many heap pages contain the rows for one particular lookup. A table can have groups of related rows packed together without those groups appearing in globally sorted order. We needed to measure the thing the query actually cared about. The Query That Made It Click Postgres exposes a system column called ctid , which identifies a tuple’s physical location as (block_number, tuple_number) . Extracting the block number lets us count the distinct heap pages containing our matching rows: SELECT count(*) AS rows_found, count(DISTINCT split_part( trim(both '()' FROM ctid::text), ',', 1 )) AS distinct_heap_pages FROM public.order_items WHERE order_id = 12345; This example assumes an ordinary, non-partitioned table. For a partitioned table, count distinct (tableoid, block_number) pairs instead, since different partitions can have the same block numbers. Also, ctid is a diagnostic tool here, not a permanent row identifier – updates and table rewrites can change it. For two representative lookup values, these were the actual counts, with the lookup values anonymized: Lookup Rows returned Slower environment: heap pages Faster environment: heap pages A 157 119 33 B 200 101 5 There it was. For lookup B, the slower environment’s matching rows occupied about 20 times as many heap pages. These counts aren’t a complete accounting of query I/O – index pages and other accesses still matter – but they directly expose the heap footprint of the result. The index wasn’t failing to find the rows. The rows were simply spread across far more pages once it found them. How Did the Rows Get So Scattered? The customer had loaded data into the Azure environment in parallel. That helped load throughput, but the concurrent loading interleaved rows belonging to different lookup values. Related rows that had been packed together in the source environment no longer landed together in the destination heap. Parallel loading doesn’t inherently guarantee a scattered table. The outcome depends on how work is divided and how inserts reach the heap. In this customer’s case, though, the loading method explained the observed layout difference. Recreating the same index didn’t restore that locality. A B-tree orders its own entries; building or rebuilding it does not reorder the underlying table. This also explained the cache behavior. Repeat executions benefited from cached pages, masking the cost of the larger footprint. Once those pages were evicted, the query had to fetch them again. More scattered data also meant more pages competing for cache space. Fix the Layout, Then Measure Again VACUUM FULL wouldn't solve this layout problem, as it rewrites the table to reclaim space from dead tuples and compact the heap, but it doesn't sort the surviving rows by the lookup key. It might reduce the page count if there is bloat, but related rows can still be interleaved with unrelated rows afterward. The issue here was less about fragmentation or bloat and more about which tuples were arranged together on disk. The next step was to reorganize the heap around the lookup key. CLUSTER can rewrite a table in index order, but it takes an ACCESS EXCLUSIVE lock, so it needs careful scheduling. The customer used pg_repack with --order-by to reorganize the data and reported improved performance on a restored test instance. That’s not a maintenance-free operation either: check extension support, free space, and locking requirements before choosing it. Afterward, refresh statistics with ANALYZE , repeat the distinct-page query, and compare execution plans and timings under comparable cache conditions. Running the diagnostic itself warms pages, so don’t treat the immediately following execution as a cold-cache test! Neither clustering nor repacking permanently maintains the ordering. Future writes can erode locality, so the migration loading strategy and ongoing workload both deserve attention. Final Thoughts Before blaming storage latency, check how many pages each environment needs to read for the same query. For this customer, correlation prompted us to examine the heap layout. Counting unique heap pages showed just how scattered the matching rows were. The lesson wasn’t “don’t load in parallel” or “Azure needs a bigger disk.” Migrating the same rows and indexes doesn’t necessarily migrate the same physical layout. An index scan is only half the story!244Views2likes0CommentsPostgreSQL Performance Bottlenecks: Managing Connections and Read-Intensive Workloads
Introduction PostgreSQL is a robust and highly scalable database system, but as applications grow in size and complexity, performance challenges can begin to emerge. Slow queries, high resource consumption, and inefficient configuration can create bottlenecks that affect query execution and the overall responsiveness of an application. Identifying and addressing these bottlenecks is essential for maintaining consistent PostgreSQL performance, particularly as workloads increase. In this blog, we’ll explore two common performance challenges: managing a high number of database connections and handling read-intensive workloads. We’ll look at how excessive connections can affect PostgreSQL performance and discuss approaches for efficiently scaling read workloads. Too many connections can slow PostgreSQL down The Problem: A high number of concurrent connections can increase memory and CPU usage, potentially affecting overall database performance. The Root Cause: PostgreSQL uses a process-based architecture, where each client connection is handled by a dedicated backend process. As the number of connections grows, the associated resource overhead can become significant. The Solution: Configure max_connections according to the available server resources and workload requirements and use a connection pooler to efficiently manage application connections at scale. In Postgresql servers establishing a connection is a very expensive operation that requires server resources, and when not properly handled, can lead to several performance issues with resource consumption. This is attributed to the fact that each new connection requires forking of the OS process and a new memory allocation for the connection. As a result, transactional applications frequently opening and closing the connections at the end of transactions can experience higher connection latency, resulting in lower database throughput (transactions per second) and overall higher application latency. Using a connection pooling mechanism when designing applications can significantly reduce connection latency by reusing existing connections and enables higher database throughput on the server. With connection pooling, a fixed set of connections are established at the startup time and maintained. This also helps reduce the memory fragmentation on the server that is caused by the dynamic new connections established on the database server. Connection pooling reduces the number of times that new connections must be opened. The pooler maintains ownership of the physical connection. It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls Open on a connection, the pooler looks for an available connection in the pool. If a pooled connection is available, it returns it to the caller instead of opening a new connection. When the application calls Close on the connection, the pooler returns it to the pooled set of active connections instead of closing it. Once the connection is returned to the pool, it is ready to be reused on the next Open call. It is therefore recommended to leverage connection pooling, i.e., PgBouncer, which is a built-in feature in Azure PostgreSQL Flexible Server. Architecture The diagram illustrates how connection pooling with PgBouncer can reduce the number of direct connections to PostgreSQL. Without connection pooling, each application establishes connections directly to the database, which can increase resource usage as the number of clients grows. With PgBouncer acting as an intermediary, application connections are pooled and a smaller set of database connections can be reused, helping PostgreSQL handle connection-heavy workloads more efficiently. Additionally, consider setting idle/timeout parameters which can reduce the number of unnecessary connections established to your server and make a huge difference on your server resources availability: idle_in_transaction_session_timeout statement_timeout lock_timeout idle_session_timeout Scaling read-intensive workloads with Azure Read Replicas The Problem: Read-heavy workloads can place significant pressure on the primary PostgreSQL server, potentially affecting performance as application traffic and query volume increase. The Root Cause: When read and write operations are handled by the same primary server, resource-intensive or high-volume read queries compete with write operations for available database resources. The Solution: Use PostgreSQL read replicas to offload read traffic from the primary server and introduce a routing layer, such as Virtual endpoints or Pgpool-II, to direct read queries to replicas while keeping write operations on the primary. Read-heavy applications often reach a point where vertically scaling the primary is no longer the most efficient answer. Azure Database for PostgreSQL read replicas provide separate read-only servers, but the application still needs a routing strategy. Flow Destination Purpose INSERT / UPDATE / DELETE / DDL Primary writer Preserve write semantics SELECT Read replica Offload read-intensive work Important distinction: This is read scaling, not write scaling. Read replicas do not reduce the write-capacity burden on the primary, and replication is asynchronous, so applications must tolerate some lag. Virtual endpoints, which is a built-in feature in, can provide stable connection points for Azure Database for PostgreSQL, helping applications maintain consistent connection strings when server roles change after a promotion. Writer endpoint (read/write): Always points to the current primary server, ensuring that write operations are directed to the correct server after a role change. Read-only endpoint: Can point to either a read replica or the primary server. It targets one server at a time. This is a valid option when the application can route read and write operations through separate connections. However, the read-only endpoint targets a single server at a time and does not distribute read traffic across multiple replicas. Virtual endpoints simplify connection management by allowing applications to use consistent endpoints while the underlying server roles can change. Pgpool-II can sit between clients and the database endpoints, inspect eligible SQL statements, and distribute read traffic while keeping writes on the primary. Useful when the application cannot separate read and write traffic itself, or when read workloads need to be distributed across multiple replicas. However, this approach introduces an additional component that needs to be deployed, configured, and managed. Architecture Below diagram illustrates Pgpool-II as a single PostgreSQL endpoint between an application and Azure Database for PostgreSQL: Writes and consistency-sensitive reads go to the primary. Eligible SELECT queries are distributed across two read replicas. Pgpool-II handles SQL-aware routing, load balancing, and backend health checks. Overall, it demonstrates how read-heavy workloads can scale without requiring the application to select individual database servers. Install Pgpool-II on Ubuntu VM The following section describes the installation steps for Pgpool-II version 4.7.2 on an Ubuntu VM version 24.04.4. Package names and paths can vary by Ubuntu and Pgpool-II version, so test in a non-production environment first. We will install Pgpool-II and psql client tools and check the connection from the VM to involved Postgresql servers. Afterwards we will configure Pgpool-II by setting the main configuration file and the authentication files needed to connect to Postgresql servers. Prerequisites and assumptions: An Azure Database for PostgreSQL Flexible Server primary and at least one read replica. Network connectivity and DNS resolution from the client host to every database endpoint on TCP 5432. A PostgreSQL login for application access plus suitable accounts for Pgpool-II health and streaming-replication checks. TLS validation appropriate to the environment. A workload that can tolerate asynchronous replica lag for the reads that will be offloaded. All the examples below are performed from a bash shell: sudo apt install -y curl ca-certificates gnupg lsb-release # Optional: PostgreSQL client from the PGDG repository sudo install -d /usr/share/postgresql-common/pgdg sudo curl -o /usr/share/postgresql-common/pgdg/apt.postgresql.org.asc --fail https://www.postgresql.org/media/keys/ACCC4CF8.asc echo "deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.asc] https://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" \ | sudo tee /etc/apt/sources.list.d/pgdg.list sudo apt update sudo apt install -y postgresql-client-17 pgpool2 sudo systemctl enable --now pgpool2 Validate the database endpoints first Test and validate the connection from the VM client to Postgres servers to resolve endpoint, authentication, TLS, and firewall issues before introducing Pgpool-II. export PGUSER="<app_user>" export PGDATABASE="postgres" export PGPASSWORD="<password>" psql "host=<primary>.postgres.database.azure.com port=5432 sslmode=require" -c "select pg_is_in_recovery(), inet_server_addr();" psql "host=<replica>.postgres.database.azure.com port=5432 sslmode=require" -c "select pg_is_in_recovery(), inet_server_addr();" Expected result: pg_is_in_recovery() is false on the primary and true on a read replica. Configure Pgpool-II for read scaling Below is a minimal illustrative of main Pgpool-II configuration file. Review all defaults in your installed version before production use. Configuration file # /etc/pgpool2/pgpool.conf backend_clustering_mode = 'streaming_replication' # - pgpool Connection Settings - listen_addresses = '*' port = 9999 # - pgpool Communication Manager Connection Settings - pcp_listen_addresses = 'localhost' pcp_port = 9898 # - Backend Connection Settings - backend_hostname0 = '<primary>.postgres.database.azure.com' backend_port0 = 5432 backend_weight0 = 0 backend_application_name0 = 'primary' backend_hostname1 = '<replica-1>.postgres.database.azure.com' backend_port1 = 5432 backend_weight1 = 1 backend_application_name1 = 'replica1' # Add more replicas as backend_hostname2, backend_port2, and so on. load_balance_mode = on connection_cache = on sr_check_user = '<check_user>' health_check_user = '<check_user>' ssl = on Why primary weight 0? This example intentionally sends load-balanced reads only to replicas. If your consistency or capacity design should allow reads on the primary, assign it a non-zero relative weight instead. An example of pgpool.conf changed configuration: backend_clustering_mode = streaming_replication listen_addresses = '*' port = 9999 pcp_listen_addresses = ‘*’ pcp_port = 9898 backend_hostname0 = 'pgpool-prim.postgres.database.azure.com' backend_port0 = 5432 backend_weight0 = 0 backend_application_name0 = 'primary' backend_hostname1 = 'pgpool-repl1.postgres.database.azure.com' backend_port1 = 5432 backend_weight1 = 1 backend_application_name1 = 'repl1' backend_hostname2 = 'pgpool-repl2.postgres.database.azure.com' backend_port2 = 5432 backend_weight2 = 1 backend_application_name2 = 'repl2' pool_passwd = 'pool_passwd' ssl = on ssl_ca_cert_dir = '/etc/ssl/certs/' load_balance_mode = on read_only_function_list = 'inet_server_addr(),pg_is_in_recovery()' sr_check_user = 'edu' sr_check_password = '' health_check_user = 'edu' Authentication files Pgpool-II primarily uses two authentication configuration files to manage connections and privileges: pool_hba.conf and pool_passwd. Similar to PostgreSQL's native pg_hba.conf, this file handles client-to-Pgpool-II access control. It defines which hosts, IP ranges, databases, and users are allowed to connect, and specifies the required authentication method (such as trust, md5, scram-sha-256). Avoid broad 0.0.0.0/0 trust or password rules. Restrict source networks, prefer SCRAM where supported, and control file ownership and permissions. # /etc/pgpool2/pool_hba.conf host all all <trusted-client-cidr> scram-sha-256 When using password-based methods like md5 or scram-sha-256, Pgpool-II cannot look up user passwords directly from the PostgreSQL system catalogs in real-time. Instead, it references the pool_passwd file to verify client credentials before passing the connection to the backend server. This file is populated using commands like pg_md5 or pg_enc. # /etc/pgpool2/pool_passwd cd /etc/pgpool2 sudo pg_enc -m -k /etc/pgpool2/.pgpoolkey -f /etc/pgpool2/pgpool.conf -u <app_user> -p By using SCRAM authentication, we need to provide a protected encryption key used by pg_enc. This file is by default located in the users home directory but can be referenced by environment variable PGPOOLKEYFILE. # /etc/pgpool2/.pgpoolkey sudo sh -c 'umask 077; printf %s '<encryption-key>' > /etc/pgpool2/.pgpoolkey' sudo chmod 600 /etc/pgpool2/.pgpoolkey Note: Pgpool-II commonly runs as the postgres operating-system user and it will look for the pgpoolkey under its home directory. Though not used for standard database traffic, pcp.conf is a third critical authentication file used by Pgpool-II. It contains credentials that authorize administrators to execute remote management commands via the Pgpool Control Protocol (PCP) toolset. This file contains user ID and his password for pgpool communication manager authentication and store username:md5(password). # /etc/pgpool2/pcp.conf echo -n '<pcp_password>' | pg_md5 ## Add the generated hash, for example: <pcp_user>:<md5_hash> sudo chmod 600 /etc/pgpool2/pcp.conf ## Optional client password file: ~/.pcppass echo 'localhost:9898:<pcp_user>:<pcp_password>' > ~/.pcppass chmod 600 ~/.pcppass After changes the pgpool-II service needs to be restarted sudo systemctl restart pgpool2 sudo systemctl status pgpool2 --no-pager PCP administration quick reference In Pgpool-II, as mentioned above, PCP stands for Pgpool Control Protocol, which is an administrative interface and command set used to manage and monitor a running Pgpool-II instance. Pgpool-II management operations, such as checking node status or detaching nodes, are available through PCP commands, independently of normal PostgreSQL client connections. The examples below use PCP's default port, 9898, and a dedicated PCP account. Limit access to the local host or a controlled administration network. Common command pattern: pcp_<command> -h localhost -p 9898 -U <pcp_user> -w [command options] Choose -W when you want the utility to ask for the PCP password. Choose -w for unattended execution; in that case the credential must already be available through ~/.pcppass or the file named by PCPPASSFILE. Task Command Operational note List configured node count pcp_node_count -h localhost -p 9898 -U <pcp_user> -w Returns the number of backend entries known to the current Pgpool-II configuration; the total is not limited to nodes that are presently attached. Show one node pcp_node_info -h localhost -p 9898 -U <pcp_user> -w -n 1 -v Reports Pgpool-II's view of the selected backend, together with backend status and role details available for that node. Show all nodes pcp_node_info -h localhost -p 9898 -U <pcp_user> -w -a -v Useful before and after maintenance to compare all configured backends. Health-check statistics pcp_health_check_stats -h localhost -p 9898 -U <pcp_user> -w -n 1 Returns the accumulated health-check results and timing information for the requested backend ID. Show effective configuration pcp_pool_status -h localhost -p 9898 -U <pcp_user> -w Prints the configuration values currently reported by Pgpool-II. Detach a node gracefully pcp_detach_node -h localhost -p 9898 -U <pcp_user> -w -n 1 -g Requests a controlled detach and allows active client work to drain until Pgpool-II's configured limits are reached. Detach a node immediately pcp_detach_node -h localhost -p 9898 -U <pcp_user> -w -n 1 Removes the selected backend from Pgpool-II service immediately; established client sessions can be interrupted. Attach a node pcp_attach_node -h localhost -p 9898 -U <pcp_user> -w -n 1 Returns a configured backend to the Pgpool-II pool. Check connectivity, expected role and replication health before doing so. Show child processes pcp_proc_info -h localhost -p 9898 -U <pcp_user> -w -a -v Provides details about Pgpool-II worker processes and their connection slots. Reload configuration pcp_reload_config -h localhost -p 9898 -U <pcp_user> -w Asks the local Pgpool-II instance to reread its configuration; settings that require a restart remain unchanged until restart. Safe detach and attach workflow Check the current topology with pcp_node_info -a -v and confirm the target node ID. If possible, detach with -g so active clients can drain. Remember that detach changes Pgpool-II state only; it does not stop the PostgreSQL backend. Perform the planned maintenance and validate the backend directly, including DNS, TLS, authentication, pg_is_in_recovery(), and replication health. Use pcp_attach_node only when the backend is safe to rejoin with the expected role and acceptable replication state. Otherwise use the documented recovery procedure for your topology. Re-run pcp_node_info -a -v and SHOW POOL_NODES, then open fresh application sessions to validate routing. Important: pcp_attach_node does not repair or resynchronise a PostgreSQL replica. It only returns an existing backend to Pgpool-II service. Avoid pcp_promote_node for Azure Database for PostgreSQL read replicas because Azure role changes should be performed through Azure-supported promotion or failover operations, then reconciled with the Pgpool-II configuration and state. An example of pcp administration command: psql -p 9999 -h localhost -U edu -d postgres -c "show pool_nodes;" node_id hostname port status pg_status lb_weight role pg_role select_cnt load_balance_node replication_delay last_status_change 0 pgpool-prim.postgres.database.azure.com 5432 up unknown 0.000000 primary unknown 10 false 0 2026-09-15 16:48:00 1 pgpool-repl1.postgres.database.azure.com 5432 up unknown 0.500000 standby unknown 5 true 0 2026-09-15 16:48:00 2 pgpool-repl2.postgres.database.azure.com 5432 down unknown 0.500000 standby unknown 0 false 0 2026-09-15 16:53:58 pcp_attach_node -n 2 psql -p 9999 -h localhost -U edu -d postgres -c "show pool_nodes;" node_id hostname port status pg_status lb_weight role pg_role select_cnt load_balance_node replication_delay replication_state replication_sync_state last_status_change 0 pgpool-prim.postgres.database.azure.com 5432 up unknown 0.000000 primary unknown 0 false 0 2026-09-15 16:48:00 1 pgpool-repl1.postgres.database.azure.com 5432 up unknown 0.500000 standby unknown 0 true 0 2026-09-15 16:48:00 2 pgpool-repl2.postgres.database.azure.com 5432 up unknown 0.500000 standby unknown 0 false 0 2026-09-15 16:53:58 Check if load balancing works A single long-lived connection can remain assigned to one load-balancing node. Therefore, test both routing correctness and distribution across multiple new sessions. Check What to verify Backend status Primary and replicas appear up, with the expected roles. SELECT distribution select_cnt increases on intended read backends. Write routing A controlled INSERT/UPDATE reaches the primary. Read-after-write Application paths requiring fresh data remain on the primary or otherwise handle lag. Failure behaviour Replica loss, Pgpool-II restart, and recovery are tested without assuming automatic correctness. psql -h localhost -p 9999 -U <app_user> -d postgres -c "show pool_nodes;" for i in $(seq 1 20); do psql -h localhost -p 9999 -U <app_user> -d postgres -Atc "select inet_server_addr(), pg_is_in_recovery();" done psql -h localhost -p 9999 -U <app_user> -d postgres -c "show pool_nodes;" An example of expected output: node_id hostname port status pg_status lb_weight role pg_role select_cnt load_balance_node replication_delay replication_state replication_sync_state last_status_change 0 pgpool-prim.postgres.database.azure.com 5432 up unknown 0.000000 primary unknown 0 false 0 2026-09-28 09:35:07 1 pgpool-repl1.postgres.database.azure.com 5432 up unknown 0.500000 standby unknown 9 true 0 2026-09-28 09:35:07 2 pgpool-repl2.postgres.database.azure.com 5432 up unknown 0.500000 standby unknown 11 false 0 2026-09-28 09:35:07 Troubleshooting quick reference Symptom Likely area to inspect All reads go to primary load_balance_mode, weights, query eligibility, transaction state, and backend roles FATAL: unable to get session context Pgpool-II authentication files, pool_passwd, key permissions, user mapping, and service logs Replica shown down DNS, firewall, TLS, credentials, health checks, and PCP state Uneven read distribution Session reuse, backend weights, number of client sessions, and statement_level_load_balance Stale results Replica lag and application consistency requirements Performance worsened after adding middleware Separate query execution time from time waiting for a connection; compare representative tests through and around the proxy Consistency and routing caveats Read replicas are asynchronously updated. A replica can return older data than the primary. A SELECT inside a transaction might be routed differently after a write, at serializable isolation, or when it contains functions Pgpool-II cannot safely classify as read-only. Session-level load balancing does not guarantee an even per-query distribution when applications keep connections open for long periods. Health detection and query routing are not the same as a complete high-availability design for the Pgpool-II tier itself. A single Pgpool-II VM is a single point of failure. Customer-managed middleware remains the customer’s operational responsibility, including patching, monitoring, capacity, certificates, secrets, and recovery procedures. Production checklist Benchmark with realistic concurrency, transaction boundaries, prepared statements, and connection lifetimes. Define which application paths tolerate eventual consistency, and which must read from the primary. Monitor Pgpool-II backend state, SELECT counters, process utilization, logs, health checks, and replica lag. Run Pgpool-II redundantly if the endpoint is business-critical; test the load balancer or failover mechanism in front of it. Use TLS, least privilege, restricted network access, protected secrets, and documented certificate rotation. Test primary maintenance, replica unavailability, Pgpool-II restart, DNS changes, and application retry behaviour. Keep Pgpool-II and operating-system packages patched, and review release notes before upgrades. What problem does each technology solve? These technologies address different bottlenecks in different scenarios. Choose the component that matches the problem first and combine them only when the workload has clearly distinct requirements. Technology Primary problem solved Best fit Important limitation Virtual Endpoints Stable writer and read-only connection points when Azure PostgreSQL server roles change. Applications that can use separate read/write and read-only connection strings and want role changes without changing those strings. The read-only endpoint targets one server at a time; it does not inspect SQL or distribute reads across multiple replicas. Pgpool-II SQL-aware read/write routing, read distribution across replicas, connection reuse, and backend health visibility. A single PostgreSQL endpoint when the application cannot split traffic itself or reads must be distributed across multiple replicas. Customer-managed middleware adds deployment, patching, monitoring, security, capacity, and availability responsibilities. PgBouncer Lightweight connection pooling that reduces connection churn and backend-connection pressure. Many short-lived or idle client connections, especially when the built-in Flexible Server endpoint is suitable. It is not a SQL-aware read/write router across Azure read-replica endpoints, and transaction pooling requires compatibility testing. Azure Managed Redis Application-level caching that serves reusable data before another PostgreSQL query is required. Frequently repeated, cacheable reads with explicit freshness, expiry, and invalidation rules. Requires application integration and a deliberate consistency, eviction, security, and cost design. Decision guide If the main problem is… Start with… Why Connection strings must remain stable when primary and replica roles change. Virtual Endpoints The writer and read-only endpoints abstract the underlying server names after supported role changes. The application can already separate writes from reads and needs one read target. Virtual Endpoints They provide dedicated writer and read-only connection points without adding customer-managed SQL-routing middleware. One SQL endpoint must route writes to the primary and distribute eligible reads across multiple replicas. Pgpool-II It can inspect eligible statements and apply read distribution in a streaming-replication topology. Short-lived or excessive idle PostgreSQL connections are consuming resources. PgBouncer Connection pooling directly reduces connection churn and the number of server-side backend connections. Frequently requested objects can be served without querying PostgreSQL. Azure Managed Redis Cached values can satisfy repeated reads before they reach the primary or replicas. Conclusion PostgreSQL performance problems should be addressed at the layer where they originate. PgBouncer is the most direct option for reducing connection churn and controlling backend-connection pressure. Azure Database for PostgreSQL read replicas add read capacity, while Virtual Endpoints provide stable writer and read-only connection points for applications that can separate those traffic paths. When the application cannot perform that separation, or when eligible reads must be distributed across multiple replicas through a single PostgreSQL endpoint, Pgpool-II provides SQL-aware routing, load balancing, connection reuse, and backend health visibility. That flexibility comes with additional operational responsibility, so the Pgpool-II tier must be secured, monitored, patched, capacity-tested, and designed for availability. Azure Managed Redis complements these database-side approaches by serving reusable data before a PostgreSQL query is issued. It is valuable for cacheable reads, but it requires explicit application logic for freshness, expiry, invalidation, and failure handling. The strongest design is therefore not the one with the most components. It is the one that identifies the actual bottleneck and introduces the smallest appropriate capability: Virtual Endpoints for stable role-based connection points, Pgpool-II for SQL-aware routing across replicas, PgBouncer for connection efficiency, and Azure Managed Redis for application-level caching. Validate the chosen design with realistic concurrency, replica lag, failover, session behaviour, and application consistency requirements before production adoption. References Azure Database for PostgreSQL server parameters: https://learn.microsoft.com/azure/postgresql/parameters/concepts-parameters Azure Database for PostgreSQL connection pooling strategy: https://learn.microsoft.com/azure/postgresql/connectivity/concepts-connection-pooling-best-practices PgBouncer in Azure Database for PostgreSQL: https://learn.microsoft.com/azure/postgresql/connectivity/concepts-pgbouncer PgBouncer feature compatibility: https://www.pgbouncer.org/features.html Azure Database for PostgreSQL read replicas: https://learn.microsoft.com/azure/postgresql/read-replica/concepts-read-replicas https://learn.microsoft.com/azure/postgresql/read-replica/concepts-read-replicas-virtual-endpoints Pgpool-II documentation: https://www.pgpool.net/about https://www.pgpool.net/docs/4.7/html/intro-whatis.html https://www.pgpool.net/docs/4.7/html/auth-methods.html https://www.pgpool.net/docs/4.7/html/runtime-config-load-balancing.html https://www.pgpool.net/docs/4.7/html/pcp-commands.html Azure Managed Redis documentation: https://learn.microsoft.com/azure/redis Azure Cache for Redis retirement guidance: https://azure.microsoft.com/products/cache302Views3likes0CommentsPostgres Trip Report from Postgres Summit US 2026
Photo gallery: Microsoft team at Postgres Summit US 2026 Postgres Summit US 2026 was a conference of connections: between database internals and the infrastructure underneath them, between AI ideas and production engineering, and between the people building PostgreSQL today and those who will carry it forward. For anyone who could not be in New York, this report captures the talks, technical questions, hallway conversations, and community moments that defined the week. The event also opened a new chapter. After years as PGConf NYC, the conference returned as Postgres Summit US, bringing more than 240 developers, DBAs, architects, contributors, technology leaders, and partners to Convene on Broadway from September 30 through October 2. The Microsoft team contributed six sessions across performance, replication, infrastructure, benchmarking, AI, developer tools, and community sustainability. Around those talks was a much larger program shaped by speakers and attendees from across the PostgreSQL ecosystem. 01 - Microsoft speaker highlights 02 - What the wider program was talking about 03 - Workshops and the hallway track 04 - The conversations continued after the slides 05 - What we brought home from New York 06 - Explore the Postgres Summit US 2026 program Gratitude for the organizers, speakers, sponsors, and attendees 01 - Microsoft speaker highlights Abe Omorogbe and Jared Meade: "Tour of Postgres on Azure with HorizonDB, Agentic workflows, & VS Code." Their end-to-end tour moved from HorizonDB's shared-storage architecture, rapid failover, and elastic read scale to SQL-declared chunking and embedding pipelines, durable incremental processing, intelligent product search, Copilot CLI Postgres skills, and an interactive VS Code query-plan visualizer. Although the demos used Microsoft technology, the engineering message applied broadly: production AI needs a dependable data layer, observable workflows, and tools that help developers understand what the database is doing. Microsoft Azure HorizonDB Documentation Landing Page | Microsoft Learn Claire Giordano delivered two talks that connected PostgreSQL's technical foundations with its future. In "A Secret Decoder Ring for Postgres Replication: A Beginner's Guide," Claire turned the alphabet soup of logical, physical, streaming, synchronous, and asynchronous replication into approachable mental models tied to high availability, disaster recovery, read scaling, migrations, WAL, and Patroni. Slides from Claire's talk: A Secret Decoder Ring for Postgres Replication: A Beginner's Guide In Claire Giordano's talk, "Building the next generation of Postgres contributors: what's working & what's getting in the way," she marked PostgreSQL's 30th anniversary by examining the project through three lenses: the soul of its people and culture, the machine of its workflows and governance, and the fuel of economics and funding. Together, the talks asked both how PostgreSQL keeps data moving and how the community keeps itself moving. Slides from Claire's talk: Building the next generation of Postgres contributors: what's working & what's getting in the way Divya Bhargov: "Same Postgres, Moving Ground: How Infrastructure Changes Shape Database Behavior." Divya explored a production reality that applies to every environment: PostgreSQL can remain stable while VM families, storage layers, operating systems, kernels, and networking stacks change underneath it. Drawing from large-scale operational experience, she showed why teams should correlate database symptoms with infrastructure transitions before assuming every behavioral change originated inside PostgreSQL. Gayathri Paderla: "PostgreSQL Performance Mysteries: When Low IOPS Still Means High Latency." Gayathri unpacked real production cases where latency increased even though familiar signals such as IOPS, query duration, CPU pressure, and indexing did not point to the cause. The trail instead led through memory behavior, cache eviction, PostgreSQL shared buffers, the operating system page cache, and storage interactions. The session showed how to correlate pg_buffercache, pg_stat_statements, wait events, storage behavior, and cache-warming techniques such as pg_prewarm. The practical lesson was memorable: low IOPS does not mean storage is uninvolved, and a normal query metric does not mean the application is experiencing normal latency. Slides from Gayathri's talk: PostgreSQL Performance Mysteries When low IOPS still means high latency - Speaker Deck Richard Yen: "Pushing PostgreSQL to the Limit: How to Benchmark Hardware with Postgres." Richard challenged the numbers used to sell hardware and cloud storage. Massive advertised IOPS or throughput does not tell a DBA whether the real limit will be storage, CPU bandwidth, PostgreSQL locks, checkpoints, archive_mode overhead, or autovacuum interference. His session focused on building an impartial PostgreSQL benchmarking harness, instrumenting both system and database metrics, and avoiding synthetic-test traps that can produce confident but misleading conclusions. Slides from Richard's talk: Pushing PostgreSQL to the Limit: How to Benchmark Hardware with Postgres 02 - What the wider program was talking about Beyond the Microsoft sessions, the schedule showed where PostgreSQL engineering is headed. The keynote "Lessons Learned from Developing Agentic AI Tooling for Postgres" set a practical tone for AI. Other sessions explored hybrid search, agent memory, AI-agent security, PostgreSQL 19, planner behavior, VACUUM, index prefetching, change data capture, driver maintenance, Kubernetes migrations, replication, and zero-downtime operations. The breadth of the program mattered. Healthcare, financial services, government, SaaS, analytics, and cloud-native teams have different workloads, but they share the same production requirements: reliability, security, predictable performance, recovery, regional availability, and a clear way to choose the right platform for each workload. The question is no longer simply whether PostgreSQL is enterprise ready. It is how each organization should use PostgreSQL without creating unnecessary operational complexity. 03 - Workshops and the hallway track The workshop track made the conference approachable for people at different stages of their PostgreSQL journey. Sessions such as "Getting Comfortable with Postgres," "Postgres DBA Basics Nobody Told You,"And "Locks, Monitoring & the Config That Matters" turned administration, configuration, troubleshooting, and performance concepts into hands-on practice. That mix of beginner-friendly learning and deep technical sessions is one of the best things about PostgreSQL conferences. Photo gallery: hands-on learning and community conversations 04 - The conversations continued after the slides The Day 1 reception gave everyone time to compare notes after the first full program, and many of the best exchanges continued at sponsor booths, over dinner, and between sessions. Engineers compared production lessons. Contributors heard directly from users. Teams discovered that problems they had considered unique were often shared by people at other companies. That hallway track is difficult to capture in an agenda, but it is a big reason people travel to PostgreSQL events. Postgres Summit US is organized by the United States PostgreSQL Association (PgUS) and supported by volunteer organizers, reviewers, speakers, and sponsors. The sponsor community included cloud providers, database companies, observability vendors, and open-source specialists. Microsoft was proud to participate, but the event's real strength came from the range of people willing to share what they had built, what had failed, and what they had learned. 05 - What we brought home from New York Microsoft brought home five key takeaways from Postgres Summit US 2026: Production AI is now a PostgreSQL architecture and operations discussion. The community is moving beyond AI prototypes toward dependable data foundations, secure agent access, observable pipelines, hybrid search, and production-ready developer tooling. Infrastructure changes can affect database behavior even when PostgreSQL itself has not changed. VM, storage, operating-system, kernel, and networking changes must be considered when diagnosing PostgreSQL performance and reliability. Observability and explainability are essential at scale. Effective diagnosis requires correlating PostgreSQL internals, query behavior, memory, caching, wait events, infrastructure metrics, and storage behavior rather than relying on one familiar metric. Organizations want to consolidate more workloads on PostgreSQL without increasing operational complexity. Customers expect simpler operations, predictable performance, stronger recovery, high availability, and clear guidance for selecting the right PostgreSQL platform. Community knowledge sharing remains one of PostgreSQL’s greatest strengths. Technical sessions, workshops, hallway conversations, and candid production lessons help practitioners, contributors, and new community members learn from one another. These takeaways reinforce Microsoft’s continued investment in PostgreSQL performance, developer experiences, AI integration, operational reliability, and open-source collaboration. The transition from PGConf NYC to Postgres Summit US felt appropriate. The event still had the technical depth, welcoming hallway conversations, and practical learning that people value, but the scope was broader. AI-enabled applications are moving into production, PostgreSQL 19 is opening new possibilities, and operators are asking sharper questions about reliability and performance. Microsoft will continue investing in PostgreSQL performance, developer experiences, AI integration, and open-source collaboration. We are already looking forward to the next gathering. Microsoft booth, reception, community dinner, and New York moments 06 - Explore the Postgres Summit US 2026 program Conference schedule :https://postgresql.us/events/postgressummitus2026/schedule/ Conference sessions and abstracts: https://postgresql.us/events/postgressummitus2026/sessions/ Gratitude for the organizers, speakers, sponsors, and attendees A conference like this only happens because many people contribute behind the scenes. Thank you to Postgres Summit US, the volunteer organizers, the program committee, the speakers who did the work behind every slide and demo, the sponsors who helped make the event possible, and the attendees who brought thoughtful questions and real production experience into every room. To everyone who shared a lesson, asked a difficult question, demonstrated a new idea, or welcomed someone new to the community: thank you. Hopefully these photos and highlights give you a feel for the energy in New York. See you at the next PostgreSQL gathering.239Views2likes0CommentsWhy Microsoft contributes to Postgres: What I tell people
Last week at PGConf.EU in Valencia, I gave a talk about the Postgres work being done at Microsoft (slides here). Getting ready for that talk, I kept noticing how much has changed in the Postgres team at Microsoft in the last 8 years. When I joined Microsoft through the Citus Data acquisition in early 2019, Microsoft contributed to Postgres in only one of the 9 ways it does today: our Azure Database for PostgreSQL managed service. We weren't sponsoring Postgres community conferences. We weren't sharing our expertise via blog posts and conference talks. We didn't have a Postgres open source contributors team. We didn't have a monthly podcast. And POSETTE: An Event for Postgres didn’t exist yet. It's heartwarming to see how far we've come. But sometimes, when I'm meeting people new to open source—especially those with a more proprietary software background—they will ask: “Why does Microsoft contribute to the Postgres open source project?” And when they learn my job is to lead our Postgres community efforts, they'll ask: “How do you know your open source work drives revenue?” Here's what I tell people about why Microsoft contributes to Postgres. Contributing upstream makes Postgres better for everyone, including Azure customers In my PGConf.EU 2026 talk, I used a slide like the one below to show how upstream and downstream fit together. Open source people use the “upstream” and “downstream” terms all the time, but they're not obvious to everyone. Quick definition: the upstream project is the Postgres open source project itself. Downstream services, like Azure Database for PostgreSQL and Azure HorizonDB, are built on top of it. Figure 1: Slide from my talk at PGConf.EU 2026, depicting the upstream Postgres open source project and our downstream managed services on Azure. If you run a Postgres managed service, you depend on Postgres—and we believe that means you have a responsibility to give back. So since 2019, we’ve been building a Postgres open source contributors team, to do our part to keep Postgres healthy for the long haul. And our upstream work benefits everyone who uses Postgres, including our downstream Azure customers. What might not be obvious: the things we learn running a Postgres service on Azure help the Postgres project too. When our engineers find a bug in Postgres while running it on Azure, they fix it upstream, which benefits Postgres users everywhere. Even open source developers need to eat Back in 2023 I wrote a meaty treatise of a blog post (complete with a hand-drawn infographic) about all the Postgres work happening at Microsoft. In that post, I included a section on why Microsoft has been building a team of Postgres contributors whose main focus is the upstream project. My answer to “why” hasn’t changed—I’ve included it in every edition of the annual what’s new blog post since, including the 2026 edition of What’s new with Postgres at Microsoft: In order to thrive, an open source ecosystem needs commercial support as well as volunteer efforts. Even open source developers need to eat! For the Postgres open source ecosystem to flourish, companies like Microsoft need to support the project by funding development in the Postgres core. Which we do. PostgreSQL is a complex piece of software that runs mission-critical workloads across the globe. To provide the best possible experience on Azure, it follows that we need to thoroughly understand how it works. By having PostgreSQL committers and contributors on our team, they can share knowledge internally across different orgs, or directly answer internal questions regarding incidents or extension development. Because today's cloud operates at a scale most on-prem solutions never encountered, unique cloud data center problems, often relating to performance, now require special attention. Our in-house team of deep Postgres experts are focused on tackling these cloud-scale issues upstream, in the Postgres core. Another benefit: our team's Postgres expertise gives Azure customers confidence in our cloud database services, too. Commercial funding of PostgreSQL developers has another benefit: it gives developers the long-term stability to pursue the big things, the groundbreaking changes that are super important to the future. In particular, the Postgres contributor team at Microsoft is focused on some big architectural changes (example: Asynchronous IO) that you wouldn’t be able to do without the funding for a full-time, multi-year effort. Example: one of those groundbreaking Postgres changes I mentioned landed last year: Asynchronous IO shipped in Postgres 18 and continues to evolve in Postgres 19 on forward. If I were writing those 2023 words above fresh today, I’d add one more reason: The Postgres project is about more than code. The project also runs on docs, the build farm, web infrastructure, packaging, translations, mentoring, conferences, trademark protection, the extension ecosystem, meetups, and more. That’s why our Postgres team contributes to the project in all sorts of ways beyond code. Nine ways Microsoft contributes to Postgres When explaining to people why we have a team dedicated to the upstream Postgres project, it helps to see how we contribute to the broader Postgres ecosystem—both our work on the Postgres code and community, and our managed services on Azure. So let’s walk through nine of the ways our team is contributing today. Figure 2: Infographic of 9 of the ways our team at Microsoft is contributing to the Postgres ecosystem. Clockwise, starting with our code contributions: Upstream Contributions to Postgres: Microsoft employs a dedicated team of Postgres committers and contributors working directly on upstream Postgres—plus a team working on open-source extensions such as Citus. While many of us believe commits are not a perfect measure of impact, they are a metric we have and they do give you a feel for scope. In the first release candidate of Postgres 19 (RC1), Microsoft’s team contributed 15% of the author commits (631 out of 4,098) and 17% of patch reviews (1,232 out of 7,240). The Microsoft team’s work spans performance, query planner, Async IO, security, and more. (Postgres 19 release notes) Supporting Postgres Events: Microsoft sponsors, and helps to organize, PostgreSQL community conferences and user groups worldwide. In the last year we sponsored 16 Postgres conferences, including PGConf.EU, PGConf.dev, PGConf India, and Postgres Summit US. Our team also shows up as speakers and program committee members. And several people on our team volunteer their time to co-organize conferences too: Daniel Gustafsson with Nordic PGDay; Melanie Plageman with PGConf.dev; Tomas Vondra with Prague PostgreSQL Developers Day (P2D2); and Cornelia Biacsics with PostgreSQL Conference Germany. Benefactor Sponsor of PGCA & the PostgreSQL project: Earlier this year, Microsoft made a benefactor donation to the PostgreSQL Community Association (PGCA), a non-profit chartered by the PostgreSQL core team in 2011 to protect and defend the Postgres trademarks. Full disclosure: I wear two hats here: I serve on the PGCA Board of Directors, and I work at Microsoft. With my PGCA hat on, I’m so appreciative of Microsoft’s support for the PGCA mission. (PGCA Sponsors) Visual Studio Code Extension for PostgreSQL: Lets you work with Postgres right inside VS Code. Over 785K installs, and it works with any Postgres database, not just Azure. (aka.ms/pgsql-vscode) POSETTE: An Event for Postgres: Free and virtual developer event with expert speakers from the Postgres ecosystem, now in its 6 th year. POSETTE 2027 will happen on 30 and 31 March 2027. (PosetteConf.com/2027) Azure Database for PostgreSQL: Our fully-managed database as a service, supporting the latest releases of Postgres open source. One thing I’m particularly happy to see: we supported Postgres 17 within 3 days of its release, and Postgres 18 on release day. With Postgres 19, we expect to support it on release day for both new servers and Major Version Upgrade. (aka.ms/azure-postgres-docs) Azure HorizonDB: Currently in preview, Azure HorizonDB is a new PostgreSQL-compatible database service built on a shared storage architecture, for applications that need to scale. (aka.ms/azure-horizondb-docs) Microsoft Blog for PostgreSQL: Our blog about Postgres, Azure, and our Postgres community initiatives. (aka.ms/microsoft-blog-postgres) Talking Postgres podcast: A monthly podcast about the people who work on Postgres and why they do what they do. I have the privilege of hosting it, and it’s so much fun. 44 episodes to date. (TalkingPostgres.com) And there’s more! Beyond the nine, our team keeps releasing new open-source tools for the Postgres community. Two recent ones: pghacker-mcp: This open-source MCP server lets you get answers to questions about Postgres’s design history and source code, with citations. Ask why a feature works the way it does, and an agent finds the relevant pgsql-hackers mailing list threads, commits, and code that answer it, and quotes them. (pghacker-mcp.dev) pg_durable: An open-source Postgres extension that lets you write long-running, fault-tolerant SQL functions, with retries and scheduling built in. It’s handy for things like ETL, database maintenance, and AI apps. Our team uses pg_durable in AI pipelines, Oracle to Postgres migrations, and pg_textsearch. (aka.ms/pg_durable) The revenue impact of upstream work is indirect—but it’s real Which brings me back to the question new hires ask me the most, especially if they come from a proprietary software background: Question: “How do we know our work on the upstream Postgres project moves the needle on Azure revenue?” My answer: The revenue impact of our open source work is indirect. And while it can't easily be measured, it's real. That's true of the patches our engineers write, and it's true of the podcast, POSETTE, and the conferences we sponsor. You can't trace most commits to a dollar of revenue, any more than you can trace a conference talk to one. Here's the thing: Azure Database for PostgreSQL and Azure HorizonDB are built on Postgres. As the Postgres project continues to thrive and grow, so do our Azure services. It all starts with people When we help make Postgres better, everyone who uses Postgres benefits, including our Azure customers. On the Talking Postgres podcast we sometimes talk about the toothbrush test: when you brush your teeth in the morning, are you looking forward to the work you'll be doing that day? My work leading our Postgres community efforts at Microsoft definitely passes the toothbrush test. 😊 And the biggest reason is the people. In my talk at PGConf.EU I said that Microsoft’s investment in the Postgres project starts with people. And the inspiration for my Postgres community work also starts with people: the people in the broader Postgres open source community, and my Postgres teammates at Microsoft. : Slide from my talk at PGConf.EU 2026 about Microsoft’s work with Postgres, with headshots of the people contributing to the upstream Postgres open source project—who inspire me every day. About Microsoft's Perspectives on PostgreSQL Perspectives on PostgreSQL is a monthly blog series featuring insights from Microsoft engineers, contributors, and builders working with PostgreSQL. Explore more articles on the Microsoft for PostgreSQL blog.From Alert to Online Repack: Playbook for PostgreSQL Table Bloat on Azure Database for PostgreSQL
I ran a experiment on my own Azure Database for PostgreSQL Flexible Server: deliberately bloat a table, build a monitoring job that would catch it, and then reclaim the space while keeping the application available. This post is the scenario-specific playbook that came out of that experiment: first the detector, then the remediation built around pg_cron and pg_repack. It is intended for update- or delete-heavy tables with measurable physical bloat, enough temporary storage for an online rebuild, and a maintenance window in which brief lock waits and elevated I/O are acceptable. Everything below was run in a lab. I validated the process end to end on Azure Database for PostgreSQL Flexible Server running PostgreSQL 17, with 32 GiB of storage and autogrow enabled. I use bloatlab throughout as the name of my existing application database. Replace it with your own database name. Every table, timestamp, and command in this post came from that lab. Setup I loaded a table (customer_orders) with 3,000,000 rows (~1 KB payload each), then held back autovacuum first with a long-running transaction, then by explicitly disabling it on the table and ran repeated full-table UPDATE passes against random rows. That's the only artificial part of this: in production, the same accumulation happens naturally on any update- or delete-heavy table, just slower. SELECT pg_size_pretty(pg_total_relation_size('customer_orders')) AS total_size, pg_size_pretty(pg_relation_size('customer_orders')) AS table_size, pg_size_pretty(pg_indexes_size('customer_orders')) AS indexes_size; total_size table_size indexes_size row_count 3471 MB 3348 MB 122 MB 3,000,000 After the bloat-inducing passes: SELECT pg_size_pretty(pg_total_relation_size(s.relid)) AS total_size, pg_size_pretty(pg_relation_size(s.relid)) AS table_size, pg_size_pretty(pg_indexes_size(s.relid)) AS indexes_size, s.n_live_tup, s.n_dead_tup, round(100.0 * s.n_dead_tup / NULLIF(s.n_live_tup + s.n_dead_tup, 0), 2) AS dead_pct FROM pg_stat_all_tables s WHERE s.schemaname = 'public' AND s.relname = 'customer_orders'; total_size table_size indexes_size n_live_tup n_dead_tup dead_pct 13 GB 13 GB 422 MB 3,000,000 6,000,000 66.67 Row count never moved. Physical size roughly quadrupled. That gap between row count and bytes on disk is the whole story of this post. Part 1: build the alarm before you need it I built a watchdog first instead of jumping straight to the fix because bloat is silent by default. PostgreSQL does not proactively alert you when a table grows unexpectedly. In many cases, the issue becomes visible only after the table has expanded significantly and starts affecting performance or storage. Azure Monitor's storage_percent metric can show storage trending toward an autogrow threshold, but remediation is more useful before additional storage has already been provisioned. Step 1: a catalog check you can run anywhere This query reads catalog statistics and does not scan table data. Validate permissions and workload policies before running it in production: SELECT schemaname, relname, n_dead_tup, n_live_tup, round(100.0 * n_dead_tup / NULLIF(n_live_tup + n_dead_tup, 0), 2) AS dead_tup_pct, autovacuum_count, last_vacuum, last_autovacuum, last_autoanalyze, last_analyze FROM pg_stat_all_tables WHERE n_live_tup > 0 ORDER BY dead_tup_pct DESC NULLS LAST; Step 2: don't trust dead_tup_pct on its own Here's that made me build a real watchdog instead of a one-off check. I polled the lab every 5 minutes and caught this the moment autovacuum finally ran: checked_at (UTC) live_tuples dead_tuples dead_tup_pct table_size table_size_bytes 13:05 3,000,000 9,000,000 75.00 13 GB 14,452,064,256 13:10 3,000,000 9,000,000 75.00 13 GB 14,452,064,256 13:15 3,000,000 0 0.00 13 GB 14,452,064,256 13:20 3,000,000 0 0.00 13 GB 14,452,064,256 last_autovacuum confirmed autovacuum ran at 13:12:06. Dead-tuple percentage dropped from 75% to 0% and the table stayed byte-for-byte the same size, 14,452,064,256 bytes, before and after. dead_tup_pct is derived from n_dead_tup, PostgreSQL’s estimated number of dead rows. I use it as an investigation signal, not as a direct measurement of reclaimable space. It says nothing about whether the file itself shrank. A watchdog built only on this number would have reported healthy at 13:15 while the table was still sitting at 13 GB. Step 3: get the physical truth with pgstattuple This query performs a full table scan and is more resource-intensive than lightweight monitoring checks. Run it during off-peak hours to minimize impact; it provides an accurate view of table contents and reusable space. CREATE EXTENSION IF NOT EXISTS pgstattuple; SELECT *, round(free_percent + dead_tuple_percent, 2) AS approx_bloat_pct FROM pgstattuple('public.customer_orders'); table_len tuple_count tuple_percent dead_tuple_count dead_tuple_percent free_percent 14,043,430,912 3,000,000 23.5 3,000,000 23.5 52.22 Only 23.5% of that 13 GB file held live data. Another 23.5% was dead but not yet vacuumed, and 52.22% was already-vacuumed free space just sitting there reusable by future rows in this table, but not returned to the OS. Total physical waste: roughly 76% of the file (75.72%). Index bloat can be checked the same way: SELECT *, round(100.0 * (1 - avg_leaf_density/100), 2) AS index_bloat_pct FROM pgstatindex('public.idx_customer_orders_status'); Step 4: find what's stopping autovacuum from keeping up Three checks worth running whenever bloat outpaces autovacuum. Long-running or idle-in-transaction sessions are the most common real-world cause: SELECT pid, age(backend_xid) AS age_in_xids, now() - xact_start AS xact_age, now() - query_start AS query_age, state, query FROM pg_stat_activity WHERE state != 'idle' ORDER BY 2 DESC LIMIT 10; Unused replication slots can also hold back vacuum: SELECT slot_name, slot_type, database, xmin FROM pg_replication_slots ORDER BY age(xmin) DESC; So can uncommitted prepared transactions: SELECT gid, prepared, owner, database, transaction FROM pg_prepared_xacts ORDER BY age(transaction) DESC; Also worth a quick check: is autovacuum_enabled explicitly turned off on the table, or is autovacuum_vacuum_scale_factor tuned too high for how fast the table changes? Step 5: wire all of this into pg_cron pg_cron is available on Flexible Server through azure.extensions, with no restart required. Its control tables (cron.job and cron.job_run_details) live in the database where the extension is created commonly postgres. Jobs targeting another database use cron.schedule_in_database. In this article, bloatlab is the existing application database that contains customer_orders; replace it with your own database name. This is the exact job I ran: \c postgres CREATE EXTENSION IF NOT EXISTS pg_cron; \c bloatlab -- History table (created once, in the SAME database the job below runs in) CREATE TABLE IF NOT EXISTS bloat_alert_history ( checked_at timestamptz NOT NULL DEFAULT now(), schemaname text, relname text, table_size_bytes bigint, dead_tup_pct numeric, live_tuples bigint, dead_tuples bigint, alert_triggered boolean ); \c postgres -- Idempotent: unschedule any previous copy of this job name first SELECT cron.unschedule(jobid) FROM cron.job WHERE jobname = 'bloat-ratio-check'; -- Every 5 min in this lab (fast feedback); 15-30 min is plenty in production SELECT cron.schedule_in_database( 'bloat-ratio-check', '*/5 * * * *', $$ INSERT INTO bloat_alert_history (schemaname, relname, table_size_bytes, dead_tup_pct, live_tuples, dead_tuples, alert_triggered) SELECT schemaname, relname, pg_total_relation_size(relid) AS table_size_bytes, round(100.0 * n_dead_tup / NULLIF(n_live_tup + n_dead_tup, 0), 2) AS dead_tup_pct, n_live_tup, n_dead_tup, (round(100.0 * n_dead_tup / NULLIF(n_live_tup + n_dead_tup, 0), 2) > 20) AS alert_triggered FROM pg_stat_user_tables WHERE relname = 'customer_orders'; $$, 'bloatlab', null, true ); Here's what actually happened when I ran it (re-verified live on a PostgreSQL 17 instance with pg_cron installed): You are now connected to database "postgres" as user "postgres". CREATE EXTENSION You are now connected to database "bloatlab" as user "postgres". CREATE TABLE You are now connected to database "postgres" as user "postgres". unschedule ------------ t (1 row) schedule_in_database ----------------------- 6 (1 row) And triggering the job body manually inside bloatlab the same way pg_cron fires it every 5 minutes to confirm the insert actually works end-to-end. This is the exact body of the scheduled job: INSERT INTO bloat_alert_history (schemaname, relname, table_size_bytes, dead_tup_pct, live_tuples, dead_tuples, alert_triggered) SELECT schemaname, relname, pg_total_relation_size(relid) AS table_size_bytes, round(100.0 * n_dead_tup / NULLIF(n_live_tup + n_dead_tup, 0), 2) AS dead_tup_pct, n_live_tup, n_dead_tup, (round(100.0 * n_dead_tup / NULLIF(n_live_tup + n_dead_tup, 0), 2) > 20) AS alert_triggered FROM pg_stat_user_tables WHERE relname = 'customer_orders'; INSERT 0 1 SELECT * FROM bloat_alert_history; checked_at | schemaname | relname | table_size_bytes | dead_tup_pct | live_tuples | dead_tuples | alert_triggered --------------------------------+------------+------------------+-------------------+--------------+-------------+-------------+----------------- 2026-09-02 09:52:26.002581+02 | public | customer_orders | 122880 | 0.00 | 1000 | 0 | f (1 row) SELECT jobid, jobname, schedule, database, active FROM cron.job ORDER BY jobid; jobid | jobname | schedule | database | active -------+--------------------+-------------+----------+-------- 6 | bloat-ratio-check | */5 * * * * | bloatlab | t (1 row) Worth showing why the \c bloatlab matters: with the table created in postgres instead, registration still succeeds no error at setup time but running that same INSERT INTO bloat_alert_history query against bloatlab fails immediately: ERROR: relation "bloat_alert_history" does not exist LINE 1: INSERT INTO bloat_alert_history ^ One thing to get right: \c targets. cron.schedule_in_database's job body executes inside whichever database you pass as its 4th argument (bloatlab here) not wherever you were connected when you called it. bloat_alert_history has to live in that same database, or every run fails with relation "bloat_alert_history" does not exist. The extension, and cron.job/cron.job_run_details, stay in postgres by convention; only the history table needs to move. Important: as written, this doesn't send a real notification. alert_triggered is just a boolean column the job only inserts a row into bloat_alert_history every 5 minutes. Nobody gets paged, emailed, or messaged unless you separately wire that table (or the query) into a real channel: an Azure Monitor action group, a Logic App, or a Teams webhook. Until you do that, this is silent detection you have to go query yourself. A 20% dead-tuple threshold worked well as a starting point tune it per table based on write pattern. What the Watchdog Caught Over Eight Hours SELECT to_char(checked_at,'YYYY-MM-DD HH24:MI') as checked_at, live_tuples, dead_tuples, dead_tup_pct, pg_size_pretty(table_size_bytes) as table_size, alert_triggered FROM bloat_alert_history ORDER BY checked_at; checked_at (UTC) live_tuples dead_tuples dead_tup_pct table_size alert 11:15 3,000,000 0 0.00 6063 MB false 11:20 3,000,000 3,000,000 50.00 7064 MB true 11:30 2,988,902 6,011,103 66.79 10 GB true 12:05 3,000,000 9,000,000 75.00 13 GB true 13:10 3,000,000 9,000,000 75.00 13 GB true 13:15 3,000,000 0 0.00 13 GB false (autovacuum ran) 13:45 3,000,000 3,000,000 50.00 13 GB true 14:10 - 19:00 3,000,000 ~6,000,000 66.67 13 GB true, ~5 hours 19:05 2,999,914 377 0.01 3465 MB false - fixed Five hours of continuous alerting with the table pinned at 13 GB that's the exact silent, ongoing cost this kind of monitoring exists to catch. And the last row isn't me manually re-checking: it's the same cron job automatically confirming the pg_repack fix below worked, five minutes after it finished. Keeping the history table itself in check The watchdog asks, “Is this table bloated?” Retention also needs maintenance, but these records live in two different databases: bloat_alert_history lives in bloatlab, while cron.job_run_details lives in the database where pg_cron is installed postgres in this article. PostgreSQL does not support cross-database table references, so I use two cleanup jobs, each running in the database that owns the table. SELECT cron.unschedule(jobid) FROM cron.job WHERE jobname = 'bloat-alert-history-cleanup'; -- Once every 24h at 03:00 UTC (use '0 */12 * * *' for every 12h instead) -- Job 1: clean application history inside bloatlab. SELECT cron.schedule_in_database( 'bloat-alert-history-cleanup', '0 3 * * *', $$ DELETE FROM bloat_alert_history WHERE checked_at < now() - interval '30 days'; $$, 'bloatlab', null, true ); -- Keep this registration idempotent. SELECT cron.unschedule(jobid) FROM cron.job WHERE jobname = 'cron-run-history-cleanup'; -- Job 2: clean pg_cron history inside postgres. SELECT cron.schedule( 'cron-run-history-cleanup', '5 3 * * *', $$ DELETE FROM cron.job_run_details WHERE end_time < now() - interval '7 days' AND jobid IN ( SELECT jobid FROM cron.job WHERE jobname IN ( 'bloat-ratio-check', 'bloat-alert-history-cleanup', 'cron-run-history-cleanup' ) ); $$ ); cron.job_run_details is pg_cron’s run-history table and lives in the database where pg_cron is installed postgres in this example. Because the application history table lives in bloatlab, I use two separate cleanup jobs: one in bloatlab for 30-day application-history retention, and one in postgres for seven-day cron run-history retention. If you'd rather not maintain custom SQL for this, Azure has a native path too: Monitor Using Metrics and Logs in Azure Database for PostgreSQL Flexible Server - Azure Database for PostgreSQL | Microsoft Learn Portal's Diagnose and solve problems blade also ships ready-made Autovacuum monitoring and Autovacuum blockers/wraparound workbooks, and Azure Advisor raises a High bloat ratio recommendation automatically once a server crosses its threshold. Part 2: fix it online with pg_repack Once the watchdog told me the table was bloated, the obvious next move is VACUUM FULL. I didn't use it, and here's why: it reclaims space correctly, but it holds an ACCESS EXCLUSIVE lock on the table for the entire rewrite. For a multi-GB table under live traffic, that's real, customer-visible downtime. pg_repack can reclaim the space while normal reads and writes continue for most of the run. It is an online alternative to VACUUM FULL, not a guarantee of zero user impact: it still needs ACCESS EXCLUSIVE locks (typically brief) during setup and the final swap, and lock contention, workload pressure, or an interrupted run can delay or affect the application. Here’s the mechanism, followed by every command I ran in this lab. How it works under the hood For a table with a primary key or unique index (required), pg_repack: Creates a log table and a trigger that captures every INSERT/UPDATE/DELETE on the original table during the repack. Bulk-copies the current live rows into a shadow table using a plain INSERT ... SELECT, no exclusive lock, reading only live data and skipping all the bloated free space. Rebuilds all indexes on the shadow table. Replays everything the trigger captured onto the shadow table, iteratively, until caught up. Takes a brief ACCESS EXCLUSIVE lock just long enough to swap the shadow table in for the original -- a metadata-only rename, not a data rewrite. Drops the old table and temporary objects, then runs ANALYZE. Only steps 1 and 5 require ACCESS EXCLUSIVE locks. In this lab, I did not separately measure the exact lock-hold duration for those phases; they are typically short because they cover setup and metadata swap work rather than the bulk copy. That is not guaranteed: acquiring either lock can take longer when other transactions, DDL, or queued sessions are present, and final impact depends on workload, dependencies, server resources, and table activity. The bulk copy and index build run while normal traffic continues, but they still consume I/O, CPU, storage, and connection capacity. Decision point: I treat pg_repack as an option only after the applicability checks pass. If physical bloat is confirmed, the table has a qualifying key, there is enough storage, I/O, and WAL headroom, and brief blocking is acceptable, I plan a controlled pg_repack run. If any of those checks fail, I choose the safer path for that problem: ordinary VACUUM for space reuse, REINDEX for index-only bloat, or VACUUM FULL during an approved maintenance window. Everything I ran, in order After allowing the extension through the server's azure.extensions setting, create it in the target database; no server restart is required: CREATE EXTENSION IF NOT EXISTS pg_repack; Two things I had to know going in: azure_pg_admin is not a true PostgreSQL superuser on Flexible Server, so pg_repack needs -k / --no-superuser-check to run without complaint. TCP keepalives on the client connection turned out to be necessary in my lab more on that below. The command that did the actual work: pg_repack -d "host=<server>.postgres.database.azure.com port=5432 dbname=<db> \ user=<admin> sslmode=require keepalives=1 keepalives_idle=20 keepalives_interval=10 keepalives_count=6" \ -t public.customer_orders -k --echo It completed cleanly in 13 minutes 28 seconds against a 13 GB table. Here's the real --echo trace it produced, with my own annotations added: -- 1. Trigger + log table setup (brief exclusive lock on the original table for setup) LOCK TABLE public.customer_orders IN ACCESS EXCLUSIVE MODE SELECT repack.create_log_table(24851) CREATE TRIGGER repack_trigger AFTER INSERT OR DELETE OR UPDATE ON public.customer_orders FOR EACH ROW EXECUTE PROCEDURE repack.repack_trigger('order_id') -- 2. Bulk-copy live rows only (no exclusive lock) INSERT INTO repack.table_24851 SELECT order_id,customer_id,order_status,order_total,created_at,updated_at,payload FROM ONLY public.customer_orders -- 3. Rebuild indexes on the new copy CREATE UNIQUE INDEX index_24859 ON repack.table_24851 USING btree (order_id) CREATE INDEX index_24861 ON repack.table_24851 USING btree (customer_id) CREATE INDEX index_24862 ON repack.table_24851 USING btree (order_status) -- 4. Catch up on everything written during steps 2-3 (ran twice: bulk pass + mop-up pass) SELECT repack.repack_apply($1, $2, $3, $4, $5, $6) -- 5. Atomic swap -- final exclusive-lock phase; duration depends on contention (rename operation, not a data copy) LOCK TABLE public.customer_orders IN ACCESS EXCLUSIVE MODE LOCK TABLE repack.table_24851 IN ACCESS EXCLUSIVE MODE SELECT repack.repack_swap($1) COMMIT -- 6. Cleanup and finalize SELECT repack.repack_drop($1, $2) ANALYZE public.customer_orders When it doesn't go cleanly the first time I encountered this warning after a client-side connection dropped during the copy phase in my lab. Before retrying, inspect the table and repack schema to determine which temporary objects remain: WARNING: The table's row triggers are not migrated to the new table. In this lab, the following commands removed the identified leftovers. Replace <oid> only after verifying the object identifiers, dependencies, and active sessions. Do not treat this as a universal cleanup sequence: DROP TRIGGER IF EXISTS repack_trigger ON public.customer_orders; DROP TABLE IF EXISTS repack.log_<oid> CASCADE; DROP TYPE IF EXISTS repack.pk_<oid> CASCADE; -- pg_repack's own error handling can miss this one What actually changed Metric Before After pg_repack Total size (table + indexes) 13 GB + 422 MB ≈ 14.45 GB 3465 MB (3348 MB + 116 MB) n_dead_tup / dead % 6,000,000 / 66.67% 323 / 0.01% pgstattuple tuple_percent (live data ratio) 23.5% 93.99% pgstattuple waste (dead + free %) 75.72% 4.99% Downtime - No full outage observed; latency spikes and one statement timeout occurred In this lab, I observed no full application outage during the 13-minute 28-second run, but I did observe latency spikes and one statement-timeout event. Treat this as a test result, not a guarantee: pg_repack still acquires ACCESS EXCLUSIVE locks in critical phases, and production impact depends on lock contention, workload intensity, client timeouts, server headroom, and whether the run completes cleanly. One thing pg_repack doesn't do pg_repack returns space to the filesystem inside the data directory, but it doesn't shrink the Azure-provisioned storage tier itself. If Storage Auto-Growth already bumped into a server from, say, 32 GiB to 64 GiB before you remediate, the server stays provisioned and billed at 64 GiB afterward, since Flexible Server storage doesn't scale back down. That's exactly why Part 1 and Part 2 of this post are meant to be used together: run pg_repack proactively, off the back of the pg_cron alert, before autogrow ever fires. One more practical note: Azure Monitor's storage_used / storage_percent metrics can lag real time by up to an hour. Verify results directly with pg_stat_user_tables / pgstattuple immediately after a repack, rather than trusting the portal graph right away. Conclusion Table bloat is manageable once you distinguish statistical signals from physical storage evidence. The key is to treat dead_tup_pct as a hint rather than a verdict. Pair it with pgstattuple or a physical size check so that “autovacuum ran” is never mistaken for “the file became smaller.” When physical bloat is confirmed and the prerequisites are satisfied, pg_repack can reclaim space while preserving availability for most of the operation—but it still requires careful planning for locks, resource consumption, and failure recovery. There is no universal bloat percentage that requires remediation. Reusable free space may be acceptable when it is stable and causes no storage, performance, or maintenance pressure. Investigate when waste keeps growing, affects large tables, slows queries, threatens storage headroom, or indicates that autovacuum is falling behind or being blocked. A bloated table does not always mean autovacuum is misconfigured, but it is a reason to check autovacuum health: last run time, dead tuple trend, long-running transactions, replication slots, table-level settings, and whether cleanup is keeping pace with the write workload. Key takeaways Don't rely on dead_tup_pct alone -- pair it with pgstattuple or physical size checks for ground truth. Schedule a pg_cron job against pg_stat_user_tables so bloat gets caught in minutes, not after an Advisor recommendation. Consider pg_repack instead of VACUUM FULL when a table must remain available and the scenario fits: physical bloat is confirmed, a suitable primary key or unique index exists, temporary storage and I/O headroom are available, and brief lock attempts are acceptable. On Azure Database for PostgreSQL Flexible Server, use -k / --no-superuser-check when the administrative role is not a true PostgreSQL superuser. Configure client keepalives when network stability or long-running connections warrant them. After an interrupted pg_repack run, inspect and remove only verified leftover objects before retrying; do not run generic DROP commands without validating object identifiers and dependencies. Remember that pg_repack frees space inside the data directory; it does not reduce the Azure-provisioned storage tier. Use proactive monitoring to avoid unnecessary autogrow events.593Views3likes0CommentsPostgres MCP Server: Connect AI coding agents to PostgreSQL
Coding agents can write SQL, troubleshoot applications, and reason about data. Useful database work starts with your schema and environment context. We are pleased to announce that Microsoft has released the Postgres MCP Server under the MIT License. Built entirely in Rust for fast, resource-efficient operation, it connects Model Context Protocol (MCP) compatible coding agents to PostgreSQL, so your agent can inspect real database context and run permitted operations. The server works with PostgreSQL locally, on-premises, on Azure, AWS, GCP, or through another PostgreSQL-compatible service. It is built for anyone who works with PostgreSQL through a coding agent, including application developers, database administrators, data professionals, platform engineers, and PostgreSQL enthusiasts. Give AI agents live PostgreSQL context The Postgres MCP Server exposes PostgreSQL operations as tools that your coding agent can call. After connecting to a profile, ask: "List the tables in my PostgreSQL database." "Show me the ten most recent orders." "Generate the schema for these tables and indexes." "What is slowing down my PostgreSQL server?" The tools let your agent: Generate queries and run analytics. Run read-only SQL or use separate tools for data and schema changes. Explore and design schemas. Inspect tables, indexes, functions, sequences, and other database objects before generating database changes. Diagnose performance. Detect server capabilities and collect focused performance metrics for the server and its queries. Manage connections. Create named connection profiles, connect to the right database, and switch between environments without placing credentials in the MCP client configuration. Install and connect securely Prerequisites: Node.js 22 or later, which includes npm and npx. Linux x64 or arm64, macOS x64 or arm64, or Windows x64. Windows on Arm uses x64 emulation. An MCP-compatible coding agent or client. A reachable PostgreSQL or wire-compatible database and a database role with the permissions needed for your intended tasks. No separate installation is required when you use npx; it downloads and runs the package for you. If you prefer the postgres-mcp command to be available globally, install the package: npm install --global @microsoft/postgres-mcp The examples use npx. With a global installation, replace npx -y Microsoft/postgres-mcp with postgres-mcp. Create a profile and store its password: npx -y @microsoft/postgres-mcp connection add local \ "postgresql://postgres@localhost:5432/postgres" npx -y @microsoft/postgres-mcp connection set-password local The server stores the password in your operating system keyring, separate from the profile. For headless or CI environments without a keyring, use the environment-based connection option. Add the server to clients that use the mcpServers configuration: { "mcpServers": { "postgres": { "command": "npx", "args": ["-y", "@microsoft/postgres-mcp", "run"] } } } Configuration formats and file locations differ by client. The Postgres MCP usage guide includes examples for supported clients. For Azure Database for PostgreSQL, the server can use Microsoft Entra ID when a saved profile does not contain a password. PostgreSQL role permissions remain the security boundary. New profiles permit write tools unless you set access_mode: ro. For exploration, combine that setting with a read-only database role. Your MCP client controls approval prompts, and CSV tools can read only from approved local paths. Add expert PostgreSQL skills The open-source Postgres Skills repository complements the MCP server with expert guidance for query performance, indexing, vector search, security, operations, Azure workflows, and AI and knowledge graph scenarios. These reusable instructions help coding agents apply PostgreSQL best practices when investigating an issue or completing a task, while the MCP server supplies the live database context and permitted operations needed to act on that guidance. Next steps Explore the Postgres MCP Server repository. Review the Postgres MCP usage and security guide. Follow the Postgres Skills plugin setup guide. Share feedback or contribute through Postgres MCP GitHub issues. Thank you!2.2KViews0likes2Comments