DEV Community

Cover image for Slow PostgreSQL Query? Locate the Cost Before the Fix
Ali moradi
Ali moradi

Posted on AI-assisted

Slow PostgreSQL Query? Locate the Cost Before the Fix

A slow query needs a diagnosis before it needs a fix.

In one PostgreSQL investigation, a recorded production plan showed 2,070.4 ms of execution time. JIT compilation consumed 2,023.5 ms within that total: 97.7%.

The operator-supplied audit summary also reported shared-buffer hits, with zero shared reads or temporary blocks in that sample.

Compilation was the dominant measured cost. That gave us a hypothesis to test.

A three-step diagnostic workflow: inspect the plan for compilation within execution and buffer activity; test the suspected cost with the same workload and a local JIT comparison; check output contents, ordering, individual timings, and controls.
The diagnostic workflow. Turning JIT off tests the explanation; broader workload evidence guides a permanent change.

Test the diagnosis

A separate local comparison ran the service operation with JIT enabled and disabled across three pairs:

  • JIT on: 603.7 ms median elapsed time.
  • JIT off: 21.7 ms median elapsed time.
  • Result digests: matched across all six executions.

These were local service timings, not a production before-and-after comparison.

The diagnostic workflow. Turning JIT off tests the explanation; broader workload evidence guides a permanent change.

Keep the conclusion narrow

Only three pairs were measured, JIT-on always ran first, and timings varied substantially. Buffer warming and run order limit attribution of the entire difference. Other workloads did not all improve.

PostgreSQL's JIT guidance explains the tradeoff: compilation overhead must earn its cost through execution savings.

For your own investigation:

  1. Inspect planning time, execution time, JIT, and buffer activity with EXPLAIN (ANALYZE, BUFFERS, SETTINGS). ANALYZE executes the statement. Reference
  2. Keep the workload and parameters stable; compare transaction-local JIT settings with balanced run order.
  3. Retain individual timings and compare output contents and ordering.
  4. Check representative workloads before persisting a setting.

Locate the cost. Test the diagnosis. Then choose the correction.

Top comments (0)