JusDB
Free DB Audit
PostgreSQL

PostgreSQL High CPU Usage: How to Find the Query and Fix It

Trace high CPU in self-managed PostgreSQL 16 to 18 from the hot OS process to the query and plan behind it, then rule out JIT, parallel workers, connections, and autovacuum.

JusDB Team
Published November 21, 2026
20 min read

The database host sits near 100% CPU, application latency climbs, and top shows a wall of postgres processes. High CPU in PostgreSQL is a symptom, not a diagnosis. Something is executing: a query reading far more rows than it returns, a nested loop running millions of times, JIT compiling a short query, too many active sessions for the cores you have, or autovacuum grinding through a large table. This guide walks the path from the hot operating system process to the statement and plan behind it on self-managed PostgreSQL 16, 17, and 18, with notes for PostgreSQL 19.0, which shipped on 19 November 2026. Each step uses only built-in views and pg_stat_statements, so you can run it during an incident without installing anything new.

TL;DR
  • Map the hot OS pid from top to pg_stat_activity.pid, and read backend_type first: client backend, autovacuum worker, or parallel worker.
  • An active session with a NULL wait_event is not in an instrumented wait. For most queries, that means it is on the CPU.
  • Rank statements by total_exec_time in pg_stat_statements, then read their plans with EXPLAIN (ANALYZE, BUFFERS) for seq scans, bad estimates, and nested loops.
  • Check JIT (on by default in 16 to 18, off by default in 19), parallel workers, and active connection counts against your core count.
  • A sudden CPU step with flat traffic often means a plan changed after ANALYZE. Compare per-statement mean time before and after.

Scope and review date: November 2026. This guide covers self-managed PostgreSQL 16, 17, and 18 on Linux, with notes where PostgreSQL 19.0 differs. Managed services such as Amazon RDS add their own metrics and are out of scope. Queries, defaults, and column names were checked against the PostgreSQL documentation for each version on 25 November 2026. They were not run in a lab, so rehearse them on a staging server first.


How do I find which PostgreSQL process is using the CPU?

PostgreSQL runs one operating system process per connection, plus background processes. The standard Unix tools chapter documents that each connection process sets its title to postgres: user database host activity, so top and ps already tell you the user, database, and command type. Background processes show their role instead, such as autovacuum worker or checkpointer.

bash
# Full command lines, sorted by CPU (procps-ng top)
top -c -o %CPU

# Or a one-shot list of the 15 busiest PostgreSQL processes
ps -eo pid,pcpu,etime,args --sort=-pcpu | grep '[p]ostgres:' | head -15

Interpretation: note the pids that stay at the top across several refreshes. One process pinned near 100% is usually a single expensive query. Many processes each using a share of the CPU usually means many concurrent queries, which points at query volume or connection count rather than one bad plan.

Take those pids into pg_stat_activity. Its pid column is the same operating system process ID, and backend_type tells you what kind of process it is.

sql
SELECT pid, backend_type, leader_pid, usename, datname, client_addr,
       state, wait_event_type, wait_event,
       now() - query_start AS runtime,
       left(query, 120) AS query
FROM pg_stat_activity
WHERE pid IN (41873, 41902, 42011);   -- the pids from top

Interpretation: client backend is an application query. autovacuum worker and parallel worker need different fixes (covered below). For a parallel worker, leader_pid points to the client backend that launched it, and that leader's row holds the query text.

From a hot OS process to the plan behind it

Four hops: each one narrows the problem from a process to a plan node

PostgreSQL CPU triage path Step 1: top or ps identifies the hot operating system process ID. Step 2: pg_stat_activity maps that pid to a backend type and the query it is running. Step 3: pg_stat_statements shows which statements used the most execution time overall. Step 4: EXPLAIN ANALYZE with BUFFERS shows which plan node does the work. top or ps hot OS pid pg_stat_activity backend and query pg_stat_statements top total time EXPLAIN ANALYZE costly plan node 1 2 3 4 which process what it runs now what ran most overall where the work goes autovacuum and parallel workers branch off at step 2

Why both steps 2 and 3: pg_stat_activity shows only what runs at this instant, while pg_stat_statements shows cumulative cost. A query that runs thousands of times a minute for a few milliseconds each rarely shows up in a snapshot but can dominate the total.

Which queries are running on the CPU right now?

The pg_stat_activity documentation says wait_event is NULL unless the backend is currently waiting, and that an active backend with a non-null wait_event "is being blocked somewhere in the system". The reverse is the useful part: an active backend with no wait event is executing. Wait events do not instrument every code path, but for most queries this is CPU time.

Group the active sessions by what they wait on. Run it a few times, a second apart, because a single sample can mislead.

sql
SELECT coalesce(wait_event_type, 'CPU (no wait event)') AS waiting_on,
       coalesce(wait_event, '-') AS wait_event,
       count(*) AS sessions
FROM pg_stat_activity
WHERE state = 'active'
  AND pid <> pg_backend_pid()
GROUP BY 1, 2
ORDER BY sessions DESC;
\watch 1

Interpretation: compare the CPU row with the number of cores (nproc on the host). If on-CPU sessions regularly exceed the core count, sessions are queuing for CPU and every query slows down. If most active sessions show LWLock or IO instead, the CPU is not the bottleneck and the next sections on contention apply.

Active sessions grouped by wait event

Illustrative output on a 16-core host: shaped like real psql output, numbers invented

postgres@db-01:~
postgres=# -- grouped query from above, \watch 1 waiting_on | wait_event | sessions---------------------+---------------+---------- CPU (no wait event) | - | 41 LWLock | LockManager | 6 IO | DataFileRead | 3 Client | ClientRead | 1(4 rows)

Read it as a queue: 41 sessions want CPU on 16 cores, so roughly 25 are waiting for a core at any moment. Reduce the work per query or the number of concurrent queries; adding work_mem or I/O capacity will not help here.

Then list the on-CPU sessions oldest first:

sql
SELECT pid, backend_type, usename, now() - query_start AS runtime,
       left(query, 100) AS query
FROM pg_stat_activity
WHERE state = 'active' AND wait_event IS NULL
  AND pid <> pg_backend_pid()
ORDER BY query_start
LIMIT 20;

Interpretation: if one query has run for minutes and you need the CPU back, SELECT pg_cancel_backend(pid) cancels it and leaves the connection open. pg_terminate_backend closes the connection and is the heavier tool. Cancelling only buys time; the statement will return.

Which queries used the most CPU time since the last reset?

pg_stat_statements keeps cumulative statistics per normalized statement. It must be in shared_preload_libraries, which needs a restart, and query IDs must be computed (compute_query_id at its default auto is enough). If it is not loaded yet, schedule that restart now: you cannot rank statements after the fact without it. Our pg_stat_statements guide covers setup in detail.

sql
SELECT queryid, calls,
       round(total_exec_time) AS total_ms,
       round(mean_exec_time::numeric, 2) AS mean_ms,
       rows,
       shared_blks_hit, shared_blks_read,
       round(100 * total_exec_time / sum(total_exec_time) OVER (), 1) AS pct,
       left(query, 80) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 15;

Interpretation: total_exec_time is elapsed execution time, so it includes time spent waiting on locks and disk, not only CPU. A statement near the top with a high shared_blks_hit and a low shared_blks_read is reading from memory and is likely CPU-bound. Compare rows with calls: a statement that touches millions of buffers to return one row per call is the classic candidate for an index.

When should you reset pg_stat_statements?

The counters are cumulative since the last reset, so a top list after six months of uptime reflects six months of history, not today's spike. Check the window first:

sql
SELECT stats_reset, dealloc FROM pg_stat_statements_info;

Interpretation: stats_reset is the start of the window. A non-zero dealloc means more distinct statements were seen than pg_stat_statements.max (default 5000) and the least-executed entries were evicted, so rare but expensive statements may be missing.

Prefer snapshots over resets: a reset destroys the baseline you need to compare against. Copy the view into a table on a schedule and diff two snapshots for the incident window.

sql
CREATE TABLE IF NOT EXISTS pgss_snap AS
  SELECT now() AS taken_at, queryid, dbid, userid, calls, total_exec_time
  FROM pg_stat_statements WITH NO DATA;

INSERT INTO pgss_snap
  SELECT now(), queryid, dbid, userid, calls, total_exec_time
  FROM pg_stat_statements;

Interpretation: subtracting the earlier snapshot from the later one per queryid, dbid, and userid gives the time each statement used during the spike only. That is the list to work from.

If you do reset, reset narrowly. On PostgreSQL 17 and later the function returns the reset time and takes a fourth argument, minmax_only, which clears only the min and max timings. On PostgreSQL 16 it takes three arguments and returns void.

sql
-- Reset one statement after you fix it (0 means any user or database)
SELECT pg_stat_statements_reset(0, 0, 1234567890123456789);

Interpretation: this gives a clean before-and-after for the fixed statement without losing the rest of the history.

What in the query plan is burning CPU?

Take the top statements and read their plans with EXPLAIN (ANALYZE, BUFFERS). On PostgreSQL 18 and later, the EXPLAIN documentation notes that buffer information is included automatically with ANALYZE; on 16 and 17, add BUFFERS yourself. ANALYZE executes the statement, so wrap writes in a transaction you roll back.

sql
BEGIN;
EXPLAIN (ANALYZE, BUFFERS)
SELECT o.id, o.total
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE c.region = 'south' AND o.status = 'open';
ROLLBACK;

Interpretation: find the node with the largest share of actual time, remembering that time is per loop and must be multiplied by loops. Then compare the estimated rows with the actual rows on that node. Three patterns account for most CPU-heavy plans.

Three plan patterns that burn CPU

Switch patterns to see what EXPLAIN shows and what to try first

Seq scan with a filter

AspectSeq scan with a filter
What EXPLAIN showsSeq Scan with a large Rows Removed by Filter and few rows returned
Why it costs CPUEvery row in the table is read from cache and tested against the condition
First thing to tryAn index on the filter columns, or a partial index for a common constant

Bad row estimate

AspectBad row estimate
What EXPLAIN showsEstimated rows=10 on a node whose actual rows are in the hundreds of thousands
Why it costs CPUThe planner picks a join method and order that suit 10 rows and run badly on many
First thing to tryANALYZE the table, raise the column's statistics target, or add extended statistics for correlated columns

Nested loop explosion

AspectNested loop explosion
What EXPLAIN showsAn inner node with loops in the hundreds of thousands under a Nested Loop
Why it costs CPUThe inner scan repeats once per outer row, so small per-loop times add up
First thing to tryFix the outer estimate first; if the inner side is a seq scan, index the join key

Order matters: fix estimates before forcing plans. A bad estimate is often the cause of both the seq scan and the nested loop, and settings such as enable_nestloop = off hide the cause for every query in the session.

Index design is a topic of its own; the PostgreSQL indexing best practices guide covers column order, partial indexes, and when an index will not be used. If the expensive statement is intermittent and hard to reproduce, auto_explain can log its plan when it runs slowly in production.

Is JIT compilation adding CPU to your queries?

PostgreSQL can compile parts of a query with LLVM at run time. The JIT documentation says it helps "long-running CPU-bound queries", and that for short queries the compilation overhead "will often be higher than the time it can save". The decision is based on the planner's estimated cost, not real run time, so a short OLTP query with an inflated estimate can pay for compilation on every execution.

JIT defaults by version

PostgreSQL 19 turned JIT off by default; 16, 17, and 18 still have it on

PostgreSQL 16 to 18

SettingPostgreSQL 16 to 18
jiton
When JIT runsEstimated cost above jit_above_cost (100000)
Inlining and optimizationAbove jit_inline_above_cost and jit_optimize_above_cost (500000 each)
Risk for OLTPShort queries with high estimates pay compile time on each execution

PostgreSQL 19

SettingPostgreSQL 19
jitoff
When JIT runsOnly where you enable it, then by the same cost thresholds
Inlining and optimizationAbove jit_inline_above_cost and jit_optimize_above_cost (500000 each)
Risk for OLTPRemoved by default; analytic workloads may now need JIT turned on

Source: the PostgreSQL 19 release notes say the cost-based JIT decision "has been determined to be unreliable". The cost thresholds are from the 18 configuration docs.

Find statements that spend time in JIT with the jit_* columns of pg_stat_statements, available since PostgreSQL 15.

sql
SELECT queryid, calls,
       round(mean_exec_time::numeric, 2) AS mean_ms,
       jit_functions,
       round((jit_generation_time + jit_inlining_time
            + jit_optimization_time + jit_emission_time)::numeric) AS jit_ms,
       left(query, 80) AS query
FROM pg_stat_statements
WHERE jit_functions > 0
ORDER BY jit_ms DESC
LIMIT 10;

Interpretation: divide jit_ms by calls and compare it with mean_ms. If JIT time is a large share of a frequent query's run time, turn JIT off for the OLTP role and keep it for reporting roles.

sql
ALTER ROLE app_oltp SET jit = off;          -- new sessions of this role
ALTER ROLE reporting SET jit = on;          -- keep it where it pays off

Interpretation: role settings apply to new sessions, so pooled connections pick them up only after the pooler reconnects. Our parallel query and JIT tuning guide covers the analytic side.

Can too many connections or LWLock contention drive CPU up?

Yes, in two ways. First, every active session is a process competing for a core, so hundreds of active sessions on a 16-core host spend much of their time queued and switching. Second, sessions contend on shared memory structures, protected by lightweight locks (LWLocks). Count sessions by state first:

sql
SELECT state, count(*)
FROM pg_stat_activity
WHERE backend_type = 'client backend'
GROUP BY state
ORDER BY count(*) DESC;

Interpretation: if active regularly sits well above the core count, put a connection pooler such as PgBouncer in transaction mode between the application and the database and size the server-side pool near what the hardware can run at once. The PgBouncer guide covers pool modes and their limits.

When LWLock waits show up in the grouped query from earlier, the event name points at the structure under pressure. The descriptions below are quoted from the wait event tables.

Wait eventDocumented meaningCommon cause to check
LWLock: LockManagerWaiting to read or update information about heavyweight locksQueries touching many partitions or indexes per statement
LWLock: BufferMappingWaiting to associate a data block with a buffer in the buffer poolWorking set larger than shared_buffers, heavy buffer churn
LWLock: BufferContent (16 to 18)Waiting to access a data page in memoryMany sessions updating the same hot rows or index pages
LWLock: ProcArrayWaiting to access shared per-process data, typically to get a snapshotVery high connection or transaction rates
LWLock: WALInsertWaiting to insert WAL data into a memory bufferWrite-heavy bursts from many sessions
Timeout: SpinDelayWaiting while acquiring a contended spinlockSevere contention on a shared structure

PostgreSQL 19 removed BufferContent and replaced it with BufferShared, BufferShareExclusive, and BufferExclusive, and renamed the BufferPin wait event type to Buffer. Update dashboards that filter on the old names before you upgrade.

Are autovacuum or parallel workers using the CPU?

Not every hot process is an application query. If step 2 showed busy autovacuum worker rows, vacuum on large tables is using the CPU. Many parallel worker rows mean parallel query is multiplying the CPU used per statement.

Autovacuum on large tables

In PostgreSQL 18, autovacuum_max_workers defaults to 3, and each worker is throttled by autovacuum_vacuum_cost_delay (2 ms) and a cost limit that falls back to vacuum_cost_limit (200), per the vacuum configuration docs. PostgreSQL 18 also lets you change autovacuum_max_workers with a reload, up to autovacuum_worker_slots. Watch what the workers are doing:

sql
SELECT p.pid, p.relid::regclass AS table_name, p.phase,
       p.heap_blks_scanned, p.heap_blks_total,
       a.query
FROM pg_stat_progress_vacuum p
JOIN pg_stat_activity a USING (pid);

Interpretation: a worker in a long scan of a large table is doing necessary work; vacuum that falls behind costs more later. If the query text ends in (to prevent wraparound), let it finish. If autovacuum CPU is a recurring problem, tune per-table thresholds rather than turning workers off. The autovacuum tuning guide covers this, and PostgreSQL 18 adds total_autovacuum_time to pg_stat_user_tables to show which tables take the most vacuum time.

Parallel query

The resource configuration docs state that "a parallel query using 4 workers may use up to 5 times as much CPU time" as the same query without workers. Defaults are max_parallel_workers_per_gather = 2 and max_parallel_workers = 8. On an OLTP server, parallel plans for frequent queries can push CPU up across the whole host.

sql
-- PostgreSQL 18+: statements that launch the most parallel workers
SELECT queryid, calls, parallel_workers_to_launch, parallel_workers_launched,
       left(query, 80) AS query
FROM pg_stat_statements
WHERE parallel_workers_launched > 0
ORDER BY parallel_workers_launched DESC
LIMIT 10;

Interpretation: frequent statements that launch workers on every call are candidates for an index, so the plan no longer needs a parallel scan, or for ALTER ROLE app_oltp SET max_parallel_workers_per_gather = 0. On 16 and 17, look for Workers Launched in the statement's EXPLAIN ANALYZE output instead.

Did a query plan change after ANALYZE?

A CPU step change with flat traffic and no deploy often means the planner switched plans. Autovacuum runs ANALYZE as data changes, new statistics change row estimates, and a statement that used an index scan yesterday uses a seq scan or a different join today. Check when each table was last analyzed:

sql
SELECT relname, last_analyze, last_autoanalyze, n_mod_since_analyze, n_live_tup
FROM pg_stat_user_tables
ORDER BY last_autoanalyze DESC NULLS LAST
LIMIT 15;

Interpretation: if a table used by a top statement was auto-analyzed just before CPU rose, compare that statement's mean_exec_time across your pg_stat_statements snapshots. A step change in mean time for one queryid at that moment is strong evidence of a plan change.

To compare against the earlier plan, you need it on record: auto_explain logs, or slow-query logs analyzed with pgBadger, gives you the earlier plan to compare. Fixes usually target the estimate rather than the plan:

sql
-- More detailed statistics for a skewed column
ALTER TABLE orders ALTER COLUMN status SET STATISTICS 1000;

-- Tell the planner two columns are correlated
CREATE STATISTICS orders_region_status (dependencies, ndistinct)
  ON region, status FROM orders;

ANALYZE orders;

Interpretation: both take effect at the next ANALYZE. Re-run EXPLAIN (ANALYZE, BUFFERS) and confirm the estimated rows on the problem node are now close to the actual rows. For prepared statements, plan_cache_mode (default auto) decides between custom and generic plans, and PostgreSQL 19 adds generic_plan_calls and custom_plan_calls to pg_stat_statements to show which one ran.

What is the runbook for a PostgreSQL CPU spike?

The stepper below is one workable order for an incident. Each step either finds the cause or rules out a class of causes.

PostgreSQL high CPU runbook

Seven steps from the hot process to the fix; none of them needs a restart

  1. Find the hot processes

    Use top -c. Note pids that stay on top and whether one process or many use the CPU.

  2. Map pids to backends

    Read backend_type: client backend, autovacuum worker, or parallel worker (follow leader_pid).

    SELECT pid, backend_type, leader_pid, state, wait_event, left(query, 80) FROM pg_stat_activity WHERE pid IN (41873);
  3. Count on-CPU sessions against cores

    Active with no wait event means executing. More than the core count means queuing.

  4. Rank statements for the spike window

    Diff two pg_stat_statements snapshots, or sort the live view by total_exec_time.

  5. Read the plan of the top statement

    Look for seq scans with large filters, estimate gaps, and inner nodes with huge loop counts.

    EXPLAIN (ANALYZE, BUFFERS) SELECT ...;
  6. Rule out JIT, parallel workers, and autovacuum

    Check the jit_* and parallel columns, and pg_stat_progress_vacuum.

  7. Check for a plan change and apply one fix

    Compare last_autoanalyze with the start of the spike. Change one thing, then re-measure.

Main risk: cancelling queries or adding hardware hides the cause. Keep the pg_stat_statements snapshot from the spike so the fix can be checked against it.

Frequently asked questions

Why is PostgreSQL using 100% CPU?

Something is executing more work than the cores can handle. The usual causes are queries scanning many rows to return few, bad row estimates leading to nested loops, more active sessions than cores, JIT compiling short queries, parallel workers on frequent queries, or autovacuum on large tables. Map the hot pid to pg_stat_activity and rank statements in pg_stat_statements to find which one applies.

How do I find which PostgreSQL query is using the most CPU?

Take the busiest pid from top and look it up in pg_stat_activity by pid to see the running query. For cumulative cost, sort pg_stat_statements by total_exec_time. That column is elapsed time, so statements with high buffer hits and few reads are the ones most likely bound by CPU.

Does a NULL wait_event mean the query is on the CPU?

For an active session, usually yes. The PostgreSQL docs say wait_event is NULL unless the backend is waiting, and that an active backend with a wait event is blocked somewhere. Wait events do not cover every code path, so treat NULL as on-CPU for most queries rather than as proof.

Should I turn off JIT in PostgreSQL to reduce CPU?

Turn it off for OLTP roles if pg_stat_statements shows frequent queries spending a large share of their time in JIT. Keep it for long analytic queries, where it can help. PostgreSQL 16 to 18 enable JIT by default; PostgreSQL 19 disables it by default because the cost-based decision proved unreliable.

Key takeaways

  • Start from the OS: the hot pid from top is the pid in pg_stat_activity, and backend_type tells you which branch of the runbook you are on.
  • Active sessions with no wait event are executing; compare their count with your cores before tuning any single query.
  • Rank statements with pg_stat_statements snapshots rather than resets, then read plans with EXPLAIN (ANALYZE, BUFFERS).
  • Check JIT, parallel workers, connection counts, and autovacuum before buying CPU; each has a targeted per-role or per-table fix.
  • When CPU steps up with flat traffic, look for a plan change after ANALYZE and fix the estimate, not the plan.

Bring PostgreSQL CPU under control with JusDB

JusDB's PostgreSQL performance tuning team can review your top statements from pg_stat_statements, read the plans behind them, and help plan index, statistics, JIT, parallelism, and pooling changes for your workload.

Bring your PostgreSQL version, a pg_stat_statements export or two snapshots from a CPU spike, and the plans of your top statements. Your team approves every production change.

Share this article

Database engineering notes

Articles like this one, in your inbox. No spam, unsubscribe anytime.

JusDB Team

Official JusDB content team

Keep reading

PostgreSQL Deadlock Troubleshooting: Read the 40P01 Log Entry and Fix the Lock Order

Read PostgreSQL's deadlock detected error and server log entry, trace the statements that formed the cycle, and fix it with consistent lock ordering and safe retries.

PostgreSQL19 minNov 24, 2026
Read

How to Fix PostgreSQL Replication Lag: Find the Stage, Then the Cause

Find which stage of PostgreSQL replication lags with pg_stat_replication LSN gaps, then fix network, standby disk, replay, recovery conflict, or logical replication causes.

PostgreSQL20 minNov 20, 2026
Read

REPACK CONCURRENTLY in PostgreSQL 19 vs pg_repack: Online Table Rebuilds

Learn what PostgreSQL 19's REPACK (CONCURRENTLY) locks, what it needs before it runs, how it compares with pg_repack, and when to keep the extension.

PostgreSQL19 minNov 9, 2026
Read