PostgreSQL Stories: From slow query to fast—via stats
A simple LIMIT 1 join between a ~100k-row postgres_dbs table and a ~90M-row events table ran for hours. The cause was a merge join that scanned ~79M non-matching events sorted ahead of the 'dpg-' serviceId prefix. Adding manual lower and upper bounds on the indexed JSON expression brought the query down to milliseconds, but the real fault was that PostgreSQL only kept statistics on whole JSON objects, not on data->>'serviceId'. Running CREATE STATISTICS on that expression gave the planner accurate distributions, and the original query then finished in under a millisecond without rewrites.
Related posts
- Introducing Postgres Query Insights in ClickHouse Cloud
ClickHouse mediumAdept
Postgres Query Insights, now in preview for ClickHouse Cloud Managed Postgres, ranks every normalized query pattern by impact and aggregates per-execution counters (CPU, cache vs disk reads, temp spills, unlaunched parallel workers, WAL) to explain why a pattern is slow. A worked example traces a p99 regression to a sort spilling to disk, confirmed with EXPLAIN (ANALYZE, BUFFERS) and fixed with an index or work_mem tuning. Telemetry comes from pg_stat_ch, an Apache 2.0 extension that normalizes literals at parse-analyze time so values and PII never leave the database. It enqueues raw per-statement events via a non-blocking try-lock on a shared-memory ring buffer at about 3% overhead, dropping events under pressure rather than back-pressuring Postgres.
- pg_stat_ch: a PostgreSQL extension that exports every metric to ClickHouse
ClickHouse hardMaster
pg_stat_ch is an open-source (Apache 2.0) PostgreSQL 16–18 extension that captures every statement execution, including failed queries and DDL, as a fixed-size ~4.6KB event with 45 fields and streams it to ClickHouse for APM-style analysis. On the hot path each backend memcpys the event into a cache-line-padded shared-memory ring buffer. A background worker flushes batches once a second over ClickHouse's native protocol with LZ4 compression, and materialized views handle all aggregation on the ClickHouse side. Key design choices are fixed-size events for predictable memory (query text is truncated at 2KB), dropping events instead of applying back-pressure, and a try-lock path with per-backend batching that cuts lock acquisitions about 5x. On pgbench TPC-B with 32 clients, extension code costs about 2% CPU but throughput drops about 11% because of contention on the enqueue lock.
- ClickHouse and PostgreSQL - a Match Made in Data Heaven - part 1
ClickHouse mediumAdept
ClickHouse can query PostgreSQL data in place through the postgresql table function and the PostgreSQL table engine. Simple WHERE clauses are pushed down to Postgres, while aggregation, joins, sorting and LIMIT run in ClickHouse. On the 28M-row UK house price dataset, a low-selectivity filter makes Postgres choose a parallel sequential scan over the index, taking about 28s, and querying through ClickHouse gives similar times because Postgres still does the scan. Queries using ClickHouse-specific functions such as toYear are not pushed down and can run much slower. Rewriting joins with conditional aggregates like medianIf, or copying the data into local MergeTree tables, is what delivers the large speedups.
- Postgres Support Recap: Investigating Postgres Query Performance
Neon mediumAdept
Three starting points for diagnosing slow Postgres queries: use pg_stat_statements to find long-running queries by mean execution time and then EXPLAIN ANALYZE them, check the cache hit ratio (in Neon via the neon_stat_file_cache view, since Neon extends shared buffers with a local file cache), and look for table and index bloat caused by MVCC dead tuples. A hit ratio below 99% suggests the working set doesn't fit in memory, which calls for more shared_buffers or a larger Neon compute. Bloat is reduced with VACUUM, VACUUM FULL or REINDEX, all of which take locks. PgHero, run via Docker, gives a free dashboard alternative.
- The side quest that freed 10% of our database
incident.io mediumAdeptA single lateral-join query answering "who's on call for this rotation layer right now" consumed 34% of incident.io's Postgres replica CPU. It was using a GiST exclusion-constraint index that lacked organisation_id and start_at, so every lookup read a layer's full history. Adding a five-column btree index did nothing on its own, because the planner assumed the four ID columns were independent and kept choosing the GiST index. Rewriting the predicate as a row-value comparison with a matching ORDER BY, which only btree indexes can serve, forced the new index and cut per-call time from 44ms to 0.26ms, buffers by 115x and CPU share to 0.3%.