Video in progress

When does PostgreSQL run a single query in parallel workers, and why does it sometimes not?

For queries that do a Seq Scan of a big table, a big Hash Join or an aggregation, the planner starts several workers under a Gather. But small tables, FOR UPDATE, writing queries, parallel-unsafe functions and worker limits all switch parallelism off.

📖 Answer

In EXPLAIN it looks like this:

Finalize Aggregate
  -> Gather  (Workers Planned: 4, Workers Launched: 2)
       -> Partial Aggregate
            -> Parallel Seq Scan on orders

If Workers Launched is less than Planned, the server ran out of free workers.

The main settings:

max_worker_processes = 16              # all background processes
max_parallel_workers = 8               # how many of them can serve parallel queries
max_parallel_workers_per_gather = 4    # for a single node
min_parallel_table_scan_size = 8MB     # a table smaller than this isn't read in parallel

Frequent reasons for not going parallel:

  • the table is small, or the planner thinks the result is small;
  • the query writes data (INSERT, UPDATE, DELETE don't go parallel; the SELECT part of CREATE TABLE AS and REFRESH MATERIALIZED VIEW can) or uses FOR UPDATE;
  • the query has a function marked PARALLEL UNSAFE, which is the default for functions you write yourself;
  • reading through a cursor: a query read with fetchSize in JDBC often doesn't go parallel.

In OLTP, parallelism isn't always good: one report can take 4 cores and leave no room for ordinary queries. That's why I set max_parallel_workers_per_gather small for the API role and larger for the reporting role.