man duckdb/group-by
How DuckDB runs GROUP BY: vectorised, parallel hash aggregation
Here is a top-N query, the kind people write in their first week of SQL:
SELECT user_id, count(*) AS n
FROM visits
GROUP BY user_id
ORDER BY n DESC
LIMIT 3;
SQLite answers the GROUP BY by sorting every row and counting runs of equal
keys (How SQLite runs GROUP BY and ORDER BY … LIMIT). DuckDB builds hash tables, several of them, and says it does so in
parallel. How many tables, how many threads, and what changes when the
table is small? This article reads the DuckDB 2.0.1 source (tag v2.0.1,
commit 8d78114e90) and checks it against the duckdb 2.0.1 CLI from
Homebrew on an Apple M2 Pro with 12 cores.
There are two test tables. art.duckdb has 100,000 rows and 37,485
distinct users, big.duckdb has 10 million rows and 3,742,308 users. Both
come from the same formula:
CREATE TABLE visits AS
SELECT ((i * 7919 % 100003) * (i * 104729 % 99991) % 50000)::INTEGER AS user_id
FROM range(1, 100001) t(i);
-- big.duckdb: % 5000000 and range(1, 10000001)
Below, SELECT ... LIMIT 3 in a command stands for the query above.
The plan
$ duckdb art.duckdb -c "EXPLAIN SELECT user_id, count(*) AS n FROM visits
GROUP BY user_id ORDER BY n DESC LIMIT 3;"
╭─ Top N ────────────────────────────╮
│ Top: 3 │
│ Order By: n DESC │
│ ~3 rows │
╰──────────────────┬─────────────────╯
╭─ Projection ─────┴─────────────────╮
│ Projections: CAST(#0 AS INTEGER), │
│ #1 │
│ ~31,114 rows │
╰──────────────────┬─────────────────╯
╭─ Hash Group By ──┴─────────────────╮
│ Groups: #0 │
│ Aggregates: count_star() │
│ ~31,114 rows │
╰──────────────────┬─────────────────╯
╭─ Projection ─────┴─────────────────╮
│ Projections: user_id │
│ ~100,000 rows │
╰──────────────────┬─────────────────╯
╭─ Projection ─────┴─────────────────╮
│ Projections: CAST(#0 AS USMALLINT) │
│ ~100,000 rows │
╰──────────────────┬─────────────────╯
╭─ Seq Scan ───────┴─────────────────╮
│ Table: art.main.visits │
│ Type: Sequential Scan │
│ Projections: user_id │
│ ~100,000 rows │
╰────────────────────────────────────╯
Two things stand out before the hash table. The planner cast the
INTEGER column to USMALLINT before grouping and back to INTEGER
afterwards. That is the compressed_materialization optimizer. The column
statistics say every value is between 0 and 49,999, which fits in 2 bytes,
so the hash table stores 2-byte keys. GetIntegralCompress() gives up when
the smaller type would be the same size as the original. The other is the
Top N at the end, which is the subject of another post. This one is about
Hash Group By.
Vectors of 2,048 values
DuckDB’s operators don’t pass rows to each other. They pass a DataChunk, a
set of column vectors, each holding up to STANDARD_VECTOR_SIZE values:
//! The default standard vector size
#define DEFAULT_STANDARD_VECTOR_SIZE 2048U
//! The vector size used in the execution engine
#ifndef STANDARD_VECTOR_SIZE
#define STANDARD_VECTOR_SIZE DEFAULT_STANDARD_VECTOR_SIZE
#endif
The same header refuses to compile if the size is not a power of two. The hash aggregate takes one chunk at a time. It hashes all the group keys of the chunk, then finds or creates the groups for the whole chunk, then updates the aggregate states. The loop over rows sits inside each of those steps, over plain arrays, which is what “vectorised” means here.
One hash table per thread
RadixPartitionedHashTable::Sink() is called by every thread that runs the
scan pipeline, and each thread fills its own GroupedAggregateHashTable.
The header describes it as “a linear probing HT”. It has two parts:
pointer table (power-of-two slots, 8 bytes each) row storage (partitioned)
+-----------+---------------------------+ +------------------------+
| salt (16) | pointer to row (48 bits) | -------> | key | hash | count_star |
+-----------+---------------------------+ +------------------------+
Each slot is an ht_entry_t: the upper 16 bits of the group’s hash (the
“salt”) and a 48-bit pointer to the row. A lookup compares salts first and
only follows the pointer and compares keys when the salt matches. The probe
sequence steps by more than one slot. SaltIncrementAndWrap() takes the top 5 bits of the
salt, sets the lowest bit so the step is odd, and adds that, so two groups
that land on the same slot usually walk different paths. An odd step over a
power-of-two table visits every slot.
The load factor is 1.5: before adding a chunk, the table doubles if the
count plus the chunk would pass capacity / 1.5. A table created without a
size gets 4,096 slots (InitialCapacity() is twice the vector size), but
the per-thread tables are created bigger, as below. The rows behind the
pointers are stored in partitions chosen by the hash’s radix bits. With 12
threads, InitialSinkRadixBits() picks 4 bits, 16 partitions; the formula
is the bits of the thread count rounded up to a power of two, capped at
MAXIMUM_INITIAL_SINK_RADIX_BITS (4).
What happens when a thread’s table fills depends on the thread count. With
one or two threads (GROW_STRATEGY_THREAD_THRESHOLD = 2), the local table
starts at 262,144 slots and keeps growing. With more, it starts at 32,768
and, when full, RadixHTAdaptivity::TryGrow() decides between growing and
abandoning. It grows only when a HyperLogLog sketch of the groups says many
rows would otherwise be stored twice. Abandoning clears the pointer table
and keeps the stored rows in their partitions, in the source’s words “Keep
the materialized rows and clear only the local pointer table”. The thread
then starts over with an empty pointer table, so the same user may now
exist in several places. That is fine, because the next phase merges them.
Partitions merge in parallel
When every thread has finished, all the stored rows for partition 7, from
every thread, belong to the same set of hash values and to no other
partition. So each partition can be merged on its own. In the source phase,
RadixHTLocalSourceState::Finalize() takes one partition, combines its
rows into a thread-local table (adding up the count_star states of equal
keys), and then scans it out. RadixPartitionedHashTable::MaxThreads()
allows the smaller of the thread count and the number of partitions, and
fewer if the memory reservation can’t hold that many partitions at once.
thread 1: scan chunks -> local HT -> rows in partitions 0..15 --+
thread 2: scan chunks -> local HT -> rows in partitions 0..15 --+--> partition 0 -> task -> combine, scan
... +--> partition 1 -> task -> combine, scan
thread 12: ... +--> ...
No two threads share a hash table during the build, and no two tasks share a partition during the merge.
How parallel is it on a small table?
The scan decides how many threads build. DataTable::MaxThreads() is:
idx_t parallel_scan_vector_count = row_group_size / STANDARD_VECTOR_SIZE;
...
idx_t parallel_scan_tuple_count = STANDARD_VECTOR_SIZE * parallel_scan_vector_count;
...
return total_rows / parallel_scan_tuple_count + 1;
The row group size is 122,880 rows (DEFAULT_ROW_GROUP_SIZE), so a task is
one row group. The 100,000-row table is one row group and gets one scanning
thread. The 10-million-row table has 82, and EXPLAIN ANALYZE says
Row Groups Scanned: 82 / 82. The CLI’s .timer on shows the difference
between wall time and CPU time:
$ duckdb big.duckdb -c "SET threads=1;" -c ".timer on" -c "SELECT ... LIMIT 3;"
Run Time (s): real 0.401 user 0.371389 sys 0.029548
$ duckdb big.duckdb -c ".timer on" -c "SELECT ... LIMIT 3;"
Run Time (s): real 0.061 user 0.552538 sys 0.053567
That is 0.40 s on one thread and 0.06 s on 12, for about 50% more CPU time in total. On the 100,000-row table, one thread took 4 ms of wall time and 3.5 ms of CPU, and 12 threads took 5 ms of wall time and 6.8 ms of CPU.
EXPLAIN ANALYZE adds up the threads
On the big table:
$ duckdb big.duckdb -c "EXPLAIN ANALYZE SELECT ... LIMIT 3;"
╭─ Summary ───────────╮
│ Total Time: 0.0606s │
│ Data Read: 31.9 MB │
╰─────────────────────╯
...
╭─ Hash Group By ─────────────╮
│ Groups: #0 │
│ Aggregates: count_star() │
│ 3,742,308 rows 610.0ms │
╰──────────────┒┎─────────────╯
610 ms inside an operator, in a query that took 61 ms. Each thread keeps
its own operator timings, and QueryProfiler::Flush() merges them into the
plan with OperatorMetrics::MergeInternal(), which does time += other.time. The per-operator figure is CPU time summed over threads, and
the docs warn that the total “may be lower than the sum of all the times
spent on the individual operators”. The thick ┒┎ connectors carry
data too. The renderer draws an edge heavier when it carries
more than 33% or 66% of the plan’s peak row flow.
Ties come out in a different order
Users 30000 and 0 both have 30 visits, and the query asks for three rows. Which one is third?
$ for t in 1 12; do for r in $(seq 1 20); do
duckdb -list -noheader art.duckdb -c "SET threads=$t;" -c "SELECT ... LIMIT 3;" | tail -1
done | sort | uniq -c; done
20 30000|30
13 0|30
7 30000|30
With one thread, 30000 every time. With 12, 0 in 13 runs and 30000 in 7.
The building was single-threaded both times (one row group), so the
difference comes from the merge. The partitions are finalized and scanned
by several tasks, the groups reach Top N in the order those tasks finish,
and Top N keeps the first of equal counts it sees. SQL promises no order
among ties. An ORDER BY n DESC, user_id is the only fix.
When there is no hash at all
For integer keys with a small known range, DuckDB skips hashing. The
planner’s CanUsePerfectHashAggregate() takes each group column’s min and
max from the statistics, adds 2 (one slot for NULL, one to make the range
inclusive), and counts the bits needed. If the total over all group columns
is at most perfect_ht_threshold, default 12, the operator computes each
row’s slot directly as the key minus the minimum plus one (slot 0 is NULL),
with no hashing and no probing:
$ duckdb -c "CREATE TABLE s AS SELECT (i % 4000)::INTEGER AS id FROM range(100000) t(i);" \
-c "EXPLAIN SELECT id, count(*) FROM s GROUP BY id;" | grep 'Group By'
╭─ Perfect Hash Group By ───────────╮
$ duckdb -c "CREATE TABLE s AS SELECT (i % 5000)::INTEGER AS id FROM range(100000) t(i);" \
-c "EXPLAIN SELECT id, count(*) FROM s GROUP BY id;" | grep 'Group By'
╭─ Hash Group By ─┴─────────────────╮
4,000 values need 4,001 slots, which fit in 12 bits. 5,000 need 13 bits, and the plan goes back to the hash table.
Curious facts
- The setting’s description says “Threshold in bytes for when to use a perfect hash table”, but the code compares it with a number of bits. The default 12 means 4,096 slots.
- The
INTEGERcolumn of the 100,000-row table, whose values run from 0 to 49,999, is grouped asUSMALLINT. The cast shows up inEXPLAINas two projections around the aggregate. - The probe step is an odd number between 1 and 31 taken from the hash. Odd steps visit every slot of a power-of-two table.
- On Android,
ht_entry.hppdefinesDUCKDB_DISABLE_POINTER_SALT, and the slot holds a full 64-bit pointer with no salt. The comment above it reads “Google, why does Android need 18446744 TB of address space?” - In
EXPLAIN ANALYZE, an operator’s time can exceed the query’s total time by ten times, because it is summed over threads.
History
- 0.2.0 to 0.5.0:
STANDARD_VECTOR_SIZEis 1024 invector_size.hppat each of those tags. From 0.6.0 (2022-11-14) it is 2048. - 2022-03-07: the DuckDB blog post “Parallel Grouped Aggregation in DuckDB” describes thread-local tables radix-partitioned on the group hash, merged per partition, and the salt bits in the pointer array.
- 0.9.0 (2023-09-26): the aggregate was redesigned so that each thread has one hash table whose data is partitioned, and a full table is reset instead of grown, which lets it spill to disk (described in “External Aggregation in DuckDB”, 2024-03-29).
Sources
src/include/duckdb/common/vector_size.hppat v2.0.1: STANDARD_VECTOR_SIZEsrc/include/duckdb/storage/storage_info.hpp: DEFAULT_ROW_GROUP_SIZEsrc/storage/data_table.cpp: DataTable::MaxThreadssrc/execution/radix_partitioned_hashtable.cpp: InitialSinkRadixBits, SinkCapacity, Sink and Abandon, source MaxThreads, per-partition Finalizesrc/include/duckdb/execution/radix_ht_sink_state.hpp: constants;src/execution/radix_ht_adaptivity.cpp: TryGrowsrc/include/duckdb/execution/aggregate_hashtable.hpp: linear probing HT, LOAD_FACTOR;src/execution/aggregate_hashtable.cpp: InitialCapacity and ResizeThreshold, SaltIncrementAndWrap, resize before a chunksrc/include/duckdb/execution/ht_entry.hpp: salt and pointer maskssrc/execution/physical_plan/plan_aggregate.cpp: CanUsePerfectHashAggregate;src/include/duckdb/main/settings.hpp: perfect_ht_threshold;src/execution/perfect_aggregate_hashtable.cpp: ComputeGroupLocationsrc/optimizer/compressed_materialization.cpp: GetIntegralCompresssrc/main/query_profiler.cpp: MergeInternal, Flush;src/common/tree_renderer/text_tree_renderer.cpp: connector tiers- Docs: EXPLAIN ANALYZE, release calendar
- Blog: Parallel Grouped Aggregation in DuckDB, External Aggregation in DuckDB
vector_size.hppat v0.5.0 and v0.6.0
grep -rl /lib/duckdb/group-by/
ls duckdb/
- draft ORDER BY ... LIMIT in DuckDB: the TOP_N operatorHow DuckDB 2.0.1 answers ORDER BY ... LIMIT n without sorting: a heap of n sort keys per thread, a shared boundary that lets threads and the table scan skip data, the 5,000-row rule for when it sorts anyway, and the optimizer that turns QUALIFY row_number() <= n into the same idea.