Parallel Queries in PostgreSQL

Parallel Queries in PostgreSQL
Modern CPUs have many cores. For years, applications have been sending queries to databases in parallel. If this is a reporting query for multiple rows in a table, it executes faster when utilizing several CPUs, and in PostgreSQL, this has been possible since version 9.6.

It took 3 years to implement the parallel query feature — the code had to be rewritten at various stages of query execution. PostgreSQL 9.6 introduced the infrastructure for further code enhancements. In subsequent versions, other types of queries also run in parallel.

Restrictions

  • Do not enable parallel execution if all cores are already busy; otherwise, other queries will be delayed.
  • Most importantly, parallel processing with high WORK_MEM values consumes a lot of memory — each hash join or sort takes up memory equivalent to work_mem.
  • OLTP queries with low latency cannot be accelerated by parallel execution. If a query returns a single row, parallel processing will only slow it down.
  • Developers love to use the TPC-H benchmark. Perhaps you have similar queries for ideal parallel execution.
  • Only SELECT queries without predicate locking are executed in parallel.
  • Sometimes, proper indexing is better than sequentially scanning the table in parallel mode.
  • Pausing queries and cursors are not supported.
  • Window functions and aggregate functions of ordered sets are not parallel.
  • You gain nothing in I/O workload.
  • There are no parallel sorting algorithms. However, queries with sorts can be executed in parallel in certain aspects.
  • Replace CTE (WITH …) with a nested SELECT to enable parallel processing.
  • Wrappers for external data do not currently support parallel processing (but they could!)
  • FULL OUTER JOIN is not supported.
  • max_rows disables parallel processing.
  • If a query includes a function not marked as PARALLEL SAFE, it will run in single-threaded mode.
  • The SERIALIZABLE transaction isolation level disables parallel processing.

Test Environment

PostgreSQL developers attempted to cut down the response time for the TPC-H benchmark queries. Download the benchmark and adapt it to PostgreSQLThis unofficial use of the TPC-H benchmark is not intended for comparing databases or hardware.

  1. Download TPC-H_Tools_v2.17.3.zip (or a newer version) from the TPC website.
  2. Rename makefile.suite to Makefile and modify as described here: https://github.com/tvondra/pg_tpch Compile the code with the command make.
  3. Generate the data: ./dbgen -s 10 creates a database of 23 GB. This is enough to see the performance difference between sequential and parallel queries.
  4. Convert the files tbl downward API support (simultaneously with this in csv with for and sed.
  5. Clone the repository pg_tpch and copy the files csv downward API support (simultaneously with this in pg_tpch/dss/data.
  6. Create the queries with the command qgen.
  7. Load the data into the database with the command ./tpch.sh.

Parallel sequential scan

It may be faster not due to parallel reading, but because the data is spread across many CPU cores. In modern operating systems, PostgreSQL data files are well cached. With pre-fetching, it's possible to retrieve more blocks from storage than the PG daemon requests. Thus, query performance is not limited by disk I/O. It consumes CPU cycles to:

  • read rows one by one from table pages;
  • compare row values and conditions WHERE.

Let's execute a simple query select:

tpch=# explain analyze select l_quantity as sum_qty from lineitem where l_shipdate <= date '1998-12-01' - interval '105' day;
QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------
Seq Scan on lineitem (cost=0.00..1964772.00 rows=58856235 width=5) (actual time=0.014..16951.669 rows=58839715 loops=1)
Filter: (l_shipdate <= '1998-08-18 00:00:00'::timestamp without time zone)
Rows Removed by Filter: 1146337
Planning Time: 0.203 ms
Execution Time: 19035.100 ms

Sequential scan returns too many rows without aggregation, so the query is executed by a single CPU core.

If you add SUM(), it's clear that two worker processes will help speed up the query:

explain analyze select sum(l_quantity) as sum_qty from lineitem where l_shipdate  Gather (cost=1589701.91..1589702.12 rows=2 width=32) (actual time=8553.241..8555.067 rows=3 loops=1)
Workers Planned: 2
Workers Launched: 2
-> Partial Aggregate (cost=1588701.91..1588701.92 rows=1 width=32) (actual time=8547.546..8547.546 rows=1 loops=3)
-> Parallel Seq Scan on lineitem (cost=0.00..1527393.33 rows=24523431 width=5) (actual time=0.038..5998.417 rows=19613238 loops=3)
Filter: (l_shipdate <= '1998-08-18 00:00:00'::timestamp without time zone)
Rows Removed by Filter: 382112
Planning Time: 0.241 ms
Execution Time: 8555.131 ms

Parallel aggregation

The node 'Parallel Seq Scan' produces rows for partial aggregation. The node 'Partial Aggregate' truncates these rows using SUM(). At the end, the SUM counter from each worker process is collected by the node 'Gather'.

The final result is calculated by the node 'Finalize Aggregate'. If you have your aggregation functions, remember to mark them as 'parallel safe'.

Number of worker processes

The number of worker processes can be increased without restarting the server:

explain analyze select sum(l_quantity) as sum_qty from lineitem where l_shipdate  Gather (cost=1589701.91..1589702.12 rows=2 width=32) (actual time=8553.241..8555.067 rows=3 loops=1)
Workers Planned: 2
Workers Launched: 2
-> Partial Aggregate (cost=1588701.91..1588701.92 rows=1 width=32) (actual time=8547.546..8547.546 rows=1 loops=3)
-> Parallel Seq Scan on lineitem (cost=0.00..1527393.33 rows=24523431 width=5) (actual time=0.038..5998.417 rows=19613238 loops=3)
Filter: (l_shipdate <= '1998-08-18 00:00:00'::timestamp without time zone)
Rows Removed by Filter: 382112
Planning Time: 0.241 ms
Execution Time: 8555.131 ms

What is happening here? The number of worker processes has doubled, and the query has become only 1.6599 times faster. The calculations are interesting. We had 2 worker processes and 1 leader. After the change, it became 4+1.

Our maximum speedup from parallel processing is 5/3 = 1.66(6) times.

Initially, a check is performed: does the client device support power via PoE? A voltage of 2.8 to 10 volts is supplied, and the input resistance is determined. If the results obtained are satisfactory for powering via PoE, the power device proceeds to the next stage.

Processes

Query execution always starts with the leader process. The leader does all non-parallel work and part of the parallel processing. Other processes executing the same queries are called worker processes. Parallel processing uses the infrastructure of dynamic background worker processes (from version 9.4). Since other parts of PostgreSQL use processes rather than threads, a query with 3 worker processes could be up to 4 times faster than traditional processing.

Interaction

Worker processes communicate with the leader via a message queue (based on shared memory). Each process has 2 queues: for errors and for tuples.

How many worker processes are needed?

The minimum limit is set by the parameter max_parallel_workers_per_gather. Then the query executor takes worker processes from the pool limited by the parameter max_parallel_workers size. The last limit is max_worker_processes, which is the total number of background processes.

If a worker process cannot be allocated, processing will be single-threaded.

The query planner can reduce the number of worker processes depending on the size of the table or index. There are parameters for this: min_parallel_table_scan_size and min_parallel_index_scan_size.

set min_parallel_table_scan_size='8MB' 
8MB table => 1 worker 
24MB table => 2 workers 
72MB table => 3 workers 
x => log(x / min_parallel_table_scan_size) / log(3) + 1 worker

Each time the table is 3 times larger than min_parallel_(index|table)_scan_size, Postgres adds a worker process. The number of worker processes is not based on costs. Circular dependencies complicate complex implementations. Instead, the planner uses simple rules.

In practice, these rules do not always apply to production, so you can change the number of worker processes for a specific table: ALTER TABLE … SET (parallel_workers = N).

Why is parallel processing not used?

In addition to the long list of limitations, there are also cost checks:

parallel_setup_cost — to avoid parallel processing for short queries. This parameter estimates the time required for memory setup, process launch, and initial data exchange.

parallel_tuple_cost: the communication between the leader and workers can be prolonged proportionally to the number of tuples from the worker processes. This parameter calculates the data exchange costs.

Nested Loop Join

PostgreSQL 9.6+ can execute nested loops in parallel — this is a simple operation.

explain (costs off) select c_custkey, count(o_orderkey)
from customer left outer join orders on
c_custkey = o_custkey and o_comment not like '%specialposits%'
group by c_custkey;
QUERY PLAN
--------------------------------------------------------------------------------------
Finalize GroupAggregate
Group Key: customer.c_custkey
-> Gather Merge
Workers Planned: 4
-> Partial GroupAggregate
Group Key: customer.c_custkey
-> Nested Loop Left Join
-> Parallel Index Only Scan using customer_pkey on customer
-> Index Scan using idx_orders_custkey on orders
Index Cond: (customer.c_custkey = o_custkey)
Filter: ((o_comment)::text !~~ '%specialposits%'::text)

Collection occurs at the final stage, so Nested Loop Left Join is a parallel operation. Parallel Index Only Scan was introduced only in version 10. It works similarly to parallel sequential scanning. The condition c_custkey = o_custkey reads one order for each customer row. So it is not parallel.

Hash Join

Each worker process creates its own hash table up to PostgreSQL 11. And if there are more than four of these processes, performance will not improve. In the new version, the hash table is shared. Each worker process can use WORK_MEM to create a hash table.

select
        l_shipmode,
        sum(case
                when o_orderpriority = '1-URGENT'
                        or o_orderpriority = '2-HIGH'
                        then 1
                else 0
        end) as high_line_count,
        sum(case
                when o_orderpriority  '1-URGENT'
                        and o_orderpriority  '2-HIGH'
                        then 1
                else 0
        end) as low_line_count
from
        orders,
        lineitem
where
        o_orderkey = l_orderkey
        and l_shipmode in ('MAIL', 'AIR')
        and l_commitdate < l_receiptdate
        and l_shipdate = date '1996-01-01'
        and l_receiptdate   Finalize GroupAggregate  (cost=1964755.66..1966196.11 rows=7 width=27) (actual time=7579.590..7579.591 rows=1 loops=1)
         Group Key: lineitem.l_shipmode
         ->  Gather Merge  (cost=1964755.66..1966195.83 rows=28 width=27) (actual time=7559.593..7922.319 rows=6 loops=1)
               Workers Planned: 4
               Workers Launched: 4
               ->  Partial GroupAggregate  (cost=1963755.61..1965192.44 rows=7 width=27) (actual time=7548.103..7564.592 rows=2 loops=5)
                     Group Key: lineitem.l_shipmode
                     ->  Sort  (cost=1963755.61..1963935.20 rows=71838 width=27) (actual time=7530.280..7539.688 rows=62519 loops=5)
                           Sort Key: lineitem.l_shipmode
                           Sort Method: external merge  Disk: 2304kB
                           Worker 0:  Sort Method: external merge  Disk: 2064kB
                           Worker 1:  Sort Method: external merge  Disk: 2384kB
                           Worker 2:  Sort Method: external merge  Disk: 2264kB
                           Worker 3:  Sort Method: external merge  Disk: 2336kB
                           ->  Parallel Hash Join  (cost=382571.01..1957960.99 rows=71838 width=27) (actual time=7036.917..7499.692 rows=62519 loops=5)
                                 Hash Cond: (lineitem.l_orderkey = orders.o_orderkey)
                                 ->  Parallel Seq Scan on lineitem  (cost=0.00..1552386.40 rows=71838 width=19) (actual time=0.583..4901.063 rows=62519 loops=5)
                                       Filter: ((l_shipmode = ANY ('{MAIL,AIR}'::bpchar[])) AND (l_commitdate < l_receiptdate) AND (l_shipdate = '1996-01-01'::date) AND (l_receiptdate   Parallel Hash  (cost=313722.45..313722.45 rows=3750045 width=20) (actual time=2011.518..2011.518 rows=3000000 loops=5)
                                       Buckets: 65536  Batches: 256  Memory Usage: 3840kB
                                       ->  Parallel Seq Scan on orders  (cost=0.00..313722.45 rows=3750045 width=20) (actual time=0.029..995.948 rows=3000000 loops=5)
 Planning Time: 0.977 ms
 Execution Time: 7923.770 ms

Query 12 from TPC-H clearly illustrates a parallel hash join. Each worker process contributes to creating a shared hash table.

Merge Join

Merge Join is inherently non-parallel. Don't worry if this is the last step of the query — it can still execute in parallel.

-- Query 2 from TPC-H
explain (costs off) select s_acctbal, s_name, n_name, p_partkey, p_mfgr, s_address, s_phone, s_comment
from part, supplier, partsupp, nation, region
where
        p_partkey = ps_partkey
        and s_suppkey = ps_suppkey
        and p_size = 36
        and p_type like '%BRASS'
        and s_nationkey = n_nationkey
        and n_regionkey = r_regionkey
        and r_name = 'AMERICA'
        and ps_supplycost = (
                select
                        min(ps_supplycost)
                from partsupp, supplier, nation, region
                where
                        p_partkey = ps_partkey
                        and s_suppkey = ps_suppkey
                        and s_nationkey = n_nationkey
                        and n_regionkey = r_regionkey
                        and r_name = 'AMERICA'
        )
order by s_acctbal desc, n_name, s_name, p_partkey
LIMIT 100;
                                                QUERY PLAN
----------------------------------------------------------------------------------------------------------
 Limit
   -&gt;  Sort
         Sort Key: supplier.s_acctbal DESC, nation.n_name, supplier.s_name, part.p_partkey
         -&gt;  Merge Join
               Merge Cond: (part.p_partkey = partsupp.ps_partkey)
               Join Filter: (partsupp.ps_supplycost = (SubPlan 1))
               -&gt;  Gather Merge
                     Workers Planned: 4
                     -&gt;  Parallel Index Scan using <strong>part_pkey</strong> on part
                           Filter: (((p_type)::text ~~ '%BRASS'::text) AND (p_size = 36))
               -&gt;  Materialize
                     -&gt;  Sort
                           Sort Key: partsupp.ps_partkey
                           -&gt;  Nested Loop
                                 -&gt;  Nested Loop
                                       Join Filter: (nation.n_regionkey = region.r_regionkey)
                                       -&gt;  Seq Scan on region
                                             Filter: (r_name = 'AMERICA'::bpchar)
                                       -&gt;  Hash Join
                                             Hash Cond: (supplier.s_nationkey = nation.n_nationkey)
                                             -&gt;  Seq Scan on supplier
                                             -&gt;  Hash
                                                   -&gt;  Seq Scan on nation
                                 -&gt;  Index Scan using idx_partsupp_suppkey on partsupp
                                       Index Cond: (ps_suppkey = supplier.s_suppkey)
               SubPlan 1
                 -&gt;  Aggregate
                       -&gt;  Nested Loop
                             Join Filter: (nation_1.n_regionkey = region_1.r_regionkey)
                             -&gt;  Seq Scan on region region_1
                                   Filter: (r_name = 'AMERICA'::bpchar)
                             -&gt;  Nested Loop
                                   -&gt;  Nested Loop
                                         -&gt;  Index Scan using idx_partsupp_partkey on partsupp partsupp_1
                                               Index Cond: (part.p_partkey = ps_partkey)
                                         -&gt;  Index Scan using supplier_pkey on supplier supplier_1
                                               Index Cond: (s_suppkey = partsupp_1.ps_suppkey)
                                   -&gt;  Index Scan using nation_pkey on nation nation_1
                                         Index Cond: (n_nationkey = supplier_1.s_nationkey)

The Merge Join node is above the Gather Merge. So, merging does not use parallel processing. However, the Parallel Index Scan node still assists with the segment. part_pkey.

Partitioned Join

In PostgreSQL 11 partitioned join is disabled by default due to its costly planning. Tables with similar partitioning can be joined section by section. Thus, Postgres will use smaller hash tables. Each partition join can be parallel.

tpch=# set enable_partitionwise_join=t;
tpch=# explain (costs off) select * from prt1 t1, prt2 t2
where t1.a = t2.b and t1.b = 0 and t2.b between 0 and 10000;
                    QUERY PLAN
---------------------------------------------------
 Append
   ->  Hash Join
         Hash Cond: (t2.b = t1.a)
         ->  Seq Scan on prt2_p1 t2
               Filter: ((b >= 0) AND (b   Hash
               ->  Seq Scan on prt1_p1 t1
                     Filter: (b = 0)
   ->  Hash Join
         Hash Cond: (t2_1.b = t1_1.a)
         ->  Seq Scan on prt2_p2 t2_1
               Filter: ((b >= 0) AND (b   Hash
               ->  Seq Scan on prt1_p2 t1_1
                     Filter: (b = 0)
tpch=# set parallel_setup_cost = 1;
tpch=# set parallel_tuple_cost = 0.01;
tpch=# explain (costs off) select * from prt1 t1, prt2 t2
where t1.a = t2.b and t1.b = 0 and t2.b between 0 and 10000;
                        QUERY PLAN
-----------------------------------------------------------
 Gather
   Workers Planned: 4
   ->  Parallel Append
         ->  Parallel Hash Join
               Hash Cond: (t2_1.b = t1_1.a)
               ->  Parallel Seq Scan on prt2_p2 t2_1
                     Filter: ((b >= 0) AND (b   Parallel Hash
                     ->  Parallel Seq Scan on prt1_p2 t1_1
                           Filter: (b = 0)
         ->  Parallel Hash Join
               Hash Cond: (t2.b = t1.a)
               ->  Parallel Seq Scan on prt2_p1 t2
                     Filter: ((b >= 0) AND (b   Parallel Hash
                     ->  Parallel Seq Scan on prt1_p1 t1
                           Filter: (b = 0)

Crucially, a partitioned join can be parallel only if these partitions are sufficiently large.

Parallel Append

Parallel Append can be used instead of different blocks in different worker processes. This usually occurs with UNION ALL queries. The downside is less parallelism since each worker process handles only one query.

Here, 2 worker processes are running, although 4 are enabled.

tpch=# explain (costs off) select sum(l_quantity) as sum_qty from lineitem where l_shipdate <= date '1998-12-01' - interval '105' day union all select sum(l_quantity) as sum_qty from lineitem where l_shipdate   Parallel Append
         ->  Aggregate
               ->  Seq Scan on lineitem
                     Filter: (l_shipdate   Aggregate
               ->  Seq Scan on lineitem lineitem_1
                     Filter: (l_shipdate <= '1998-08-18 00:00:00'::timestamp without time zone)

The most important variables

  • WORK_MEM limits the amount of memory for each process, not just for queries: work_mem processes connections = a lot of memory.
  • max_parallel_workers_per_gather — how many worker processes the executing program will use for parallel processing from the plan.
  • max_worker_processes — adjusts the total number of worker processes to the number of CPU cores on the server.
  • max_parallel_workers — the same, but for parallel worker processes.

Summary

Starting with version 9.6, parallel processing can significantly improve the performance of complex queries that scan many rows or indexes. In PostgreSQL 10, parallel processing is enabled by default. Remember to disable it on servers with a high OLTP workload. Sequential scans or index scans consume a lot of resources. If you are not running a report on the entire dataset, queries can be made more efficient simply by adding missing indexes or using proper partitioning.

Links

Source: habr.com

Buy reliable website hosting with DDoS protection, VPS VDS servers 🔥 Buy reliable website hosting with DDoS protection, VPS VDS servers | ProHoster