Skip to main content

How Quack on Demand splits one DuckDB query across many nodes

· 21 min read
Hayssam Saleh
Starlake Core Team

Quack on Demand (QoD) can now split a single SQL query across the DuckDB nodes of a pool. On TPC-H at scale factor 1000, eight nodes ran the 22 queries 4.1 times faster than one, and every answer matched.

One query, many nodes​

Until this release, each statement ran on exactly one node: more nodes meant more queries at the same time, never one faster query.

This post walks through how the split works. It covers how QoD cuts a scan, combines the pieces, runs joins, decides whether to split at all, keeps governance intact and handles failures. It ends with the stage timeline, the view that shows where each query spent its time, and a benchmark.

Everything here ships in the open-source release, under Apache-2.0. It is written for data engineers on DuckLake whose heavier queries take tens of seconds or minutes on one node.

Why DuckLake makes this tractable​

Inside one node, DuckDB already uses every core. It cuts each scan into small chunks of rows that threads pick up one after another. Distribution applies the same idea one level up: QoD cuts the work across nodes instead of threads.

Classic parallel databases were shared-nothing. Each node owned a slice of each table on its own disks, so a query had to move rows to wherever matching rows lived. DuckLake is different. Data lives as Parquet files in one bucket, metadata lives in one SQL catalog, and every node can read any file.

Two things follow. QoD can hand any node any slice of any table. And small tables need no copying: each node reads them from the bucket itself.

Take TPC-H Q1, which scans about 600 million lineitem rows at scale factor 100. On four nodes, each node scans a quarter of the files, and only a few hundred bytes of partial results cross the network.

Cutting a scan into value ranges​

QoD gives each fragment a value-range predicate on one column, the split column. The ranges cover every possible value, NULL included, so every row lands in exactly one fragment whatever the file layout:

-- fragment 1 of 4
... AND (l_shipdate < DATE '1993-06-01' OR l_shipdate IS NULL)
-- fragment 2
... AND l_shipdate >= DATE '1993-06-01' AND l_shipdate < DATE '1995-01-01'
-- fragment 3
... AND l_shipdate >= DATE '1995-01-01' AND l_shipdate < DATE '1996-08-01'
-- fragment 4
... AND l_shipdate >= DATE '1996-08-01'

Correctness comes from the predicates. Speed comes from the statistics: DuckLake records each data file's minimum and maximum per column, so a fragment only opens files whose range touches its own.

Not every column is worth cutting on. QoD simulates the cut from the file statistics and scores each candidate by the average share of files a fragment would open. The ideal is 1/N for N fragments. A column cuts well when its score is at most 1.5/N, so that together the fragments open at most 1.5 times the files one node would.

lineitem loaded by ship date, N = 4File rangesScoreCuts well?
l_shipdatenarrow, little overlapabout 0.25yes
l_orderkeywidenear 1.0no
l_quantityevery file spans 1 to 501.0no

The boundaries are then placed on bytes, not values. QoD sorts the surviving files by minimum, adds up their sizes, and cuts each time a fragment reaches its share. A table loaded in time order usually cuts well on its time column, with no tuning.

Combining partial results​

Each task computes a partial result over its slice, and a later stage combines the partials. For TPC-H Q6, in outline:

-- each task of the first stage
SELECT sum(l_extendedprice * l_discount) AS p0
FROM lineitem AT (VERSION => 4812)
WHERE <range i> AND <Q6's filters>;

-- the final stage, on the coordinator, over the partials the tasks sent
SELECT sum(p0) AS revenue FROM <the partials>;

Only some aggregates merge this way:

AggregateFragment sendsCombine computes
SUM, COUNTthe sameSUM of the partials
MIN, MAXthe sameMIN, MAX of the partials
AVGa sum and a counttotal sum / total count
median, COUNT(DISTINCT)cannotneeds every row of a group in one place

AVG travels as two numbers for a reason. Take three nodes with 10, 20 and 5 rows and averages of 100, 125 and 100. Averaging the averages gives 108.3, but the true average is 4,000 / 35 = 114.3.

The planner treats an aggregate as two steps, a partial and a final. Each task computes the partial over its rows. Then, by cost, either a hash exchange on the GROUP BY keys sends each group to one task for the final step, or a gather brings every partial to one task. An aggregate with DISTINCT or an ORDER BY inside it does not split this way.

For ORDER BY ... LIMIT k, each task keeps its own first k rows, and one task takes the first k of those. A plain ORDER BY with no LIMIT is finished in one task. The aggregate classes come from Gray et al., Data Cube (ICDE 1996; the link is the technical report version).

Joins: three ways to make matching rows meet​

A distributed join is correct only if every pair of matching rows meets on the same node. QoD has three ways to make sure they do.

Small tables read whole. Only the big table is cut, and every fragment reads the small tables in full. For revenue by supplier nation, each node reads a quarter of lineitem and all of supplier and nation. A classic engine would broadcast the small tables over the network. With DuckLake, each node reads them from the bucket. This is safe for inner joins, for left joins with the big table on the left, and for IN or EXISTS with the big table outside.

Co-partitioned joins. Two big tables joined on a key that cuts well on both sides are cut with the same ranges on that key. Order 42 and its line items fall in the same fragment, so even outer joins stay correct, and no row moves between nodes:

orders:    o_orderkey  [0, 150M)  [150M, 300M)  [300M, 450M)  [450M, ...)
lineitem: l_orderkey [0, 150M) [150M, 300M) [300M, 450M) [450M, ...)
fragment 1 fragment 2 fragment 3 fragment 4

Hash exchange. When the key does not cut well, each fragment sends every row to the node that owns hash(key) % B, for B buckets, and each node joins its buckets locally. The rows travel as Arrow record batches over Arrow Flight, one stream per sender and partition, to the receiving node's exchange port. Receivers keep the batches in DuckDB's buffer manager and spill to local disk if needed. Rows cross the network once, and nothing is written to shared storage.

One detail matters here: keys are cast to a common type before hashing. DuckDB hashes by physical type, so equal keys typed INTEGER and BIGINT would otherwise land in different buckets.

A small intermediate result can also be broadcast: sent whole to every task that needs it, up to 1 GiB by default.

From one plan to many stages​

QoD does not plan the query itself. It asks the coordinator node for DuckDB's optimized plan of the statement, run as the caller, and keeps DuckDB's join order. Then, for each operator from the scans up, it weighs where that operator's rows can be: all in one task, whole in every task, or spread across tasks by a range cut or a hash of some keys. Where an operator needs its rows placed differently, the planner inserts an exchange. It keeps the cheapest plan the cost model finds.

Each exchange closes a stage. A stage runs as a set of tasks, each node running one at a time, and the next stage starts once every producer it reads from has answered. A plan can hold up to 32 stages. Rows travel between nodes as Arrow record batches over Arrow Flight, and the final stage runs on the coordinator, which streams the answer to the client.

The idea of the exchange operator comes from Graefe's Volcano work: parallelism lives in one operator, and every other operator runs as it would on one machine.

Deciding before running​

Splitting costs planning, extra reads and a combine, so a query that one node runs in two seconds should stay there. QoD decides before anything runs, in five steps.

  1. Recognize the query's shape. The manager turns the statement into a fingerprint, with every literal replaced by a placeholder and every list of literals collapsed into one. A dashboard that only changes its date filter keeps its shape.
  2. A cheap gate. Only a lone SELECT outside a transaction qualifies, with at least two idle nodes in the pool. Its largest table must exceed 2 GiB, and the tables' size times the shape's rate must reach 5 seconds. Everything else goes straight to one node. The gate reads table sizes from the DuckLake catalog within 50 ms.
  3. Plan and price both ways. The coordinator returns DuckDB's plan, and the planner prices one node against the best distributed plan, within 500 ms. A stage costs the bytes its busiest node reads at the shape's rate, plus a fixed 0.25 s. An exchange costs the bytes it moves at the pool's measured network rate.
  4. Split only when it pays. The query splits only when its predicted single-node time reaches 5 seconds and is at least 1.5 times the predicted distributed time. Past either time bound, the statement simply runs on one node.
  5. Learn. A shape's rate is the median of its last 20 runs that read at least 64 MiB. The network rate is the median of the pool's last 32 producer tasks that sent at least 64 MiB, and starts at 256 MiB/s. A distributed run that fails sends its shape back to one node for 60 minutes, so a bad decision is paid once, not on every query.

The idea of normalized fingerprints comes from PostgreSQL's pg_stat_statements. The thresholds are server settings, listed at the end of this post.

Same snapshot, same governance​

A distributed answer has to equal the answer one node would have given. Two things could break that: a writer committing mid-run, and policies applied differently on different nodes.

One snapshot for every fragment. Four nodes start their fragments a few milliseconds apart. If a writer commits in between, two nodes could read different versions of a table. So the coordinator reads the current DuckLake snapshot id when it plans, and every fragment reads AT (VERSION => <that id>). The run also holds a short-lived pin on the snapshot, so snapshot expiry cannot delete a file a task is still reading. Every task also runs under the clock the plan was made with, so now() and current_date read the same on every node.

Every task runs as the caller. Most distributed engines run tasks under a service identity and trust the coordinator. In QoD, every task a node runs is an ordinary SQL statement bound as the caller, so the node applies grants, row filters and masks exactly as for a statement the caller typed. Only the first tasks read tables, so later stages only see rows that already passed the policies.

A few rules follow from that promise:

  • Masked columns are never cut on. Range boundaries come from raw file statistics. If a column is masked for the caller, which fragment returns a row would hint at its raw value. An analyst with a mask on o_orderkey never gets a co-partitioned join on it, while an admin running the same query may.
  • Task SQL never reaches the caller. Boundaries computed over all rows, including rows a policy hides, could reveal something. History, profiles and errors show only the caller's own statement.
  • Every shuffle stream is authenticated for one statement. The manager mints a per-statement credential for each receiving node, a message authentication code under that node's key. A node accepts a bucket stream only for a statement it serves.
  • A refused task is not a denial. If a node refuses a task, QoD records why and reruns the statement on one node, where a refusal of what the caller actually wrote is handled as usual.

When a node fails​

If anything fails before the first result byte reaches the client, QoD ends the distributed run and reruns the statement on one node. The client loses time, never an answer. A run also has a time limit, an hour by default: past it, a run that has not started answering reruns on one node too. With the Flight shuffle, a dead node takes its buckets with it, so there is nothing partial worth saving.

QoD does not retry individual tasks in this release, on purpose. Task retries pay for themselves when a run is long or spans many nodes, because the chance that some task fails grows with both. The waste of rerunning the whole query grows roughly with the square of the node count times the run time. For a query of a minute or two on a handful of nodes, a failure is rare and a rerun is cheap. Engines built for hundreds of workers, such as MapReduce and Spark, make task retries central for exactly that reason.

The MapReduce paper (Dean and Ghemawat, OSDI 2004) is still the clearest account of re-execution as fault tolerance.

Seeing where the time went​

Every distributed query gets a stage timeline: for each stage, how long it took on each node, from the first scan to the final combine. When a query is slower than expected, the timeline shows whether one node lagged, the shuffle dominated, or the combine was the bottleneck.

TPC-H q21 on eight nodes in the QoD console: the stage graph, three stages joined by a broadcast and a gather, and the node timeline, one lane per node

Take q21 from the benchmark below, as the console shows it. Stage 0 ran 7 tasks, each reading its own range of supplier and the whole of nation; the slowest took 216 ms, and together they broadcast 24.6 MB to every task of the next stage. Stage 1 ran 8 tasks, each reading its own range of order keys from lineitem and orders and joining them locally, so no rows crossed between nodes there; the slowest took 13 s, and they gathered 98.6 MB of partial results to the coordinator. Stage 2, the final step, took 40 ms there. On one node, the same query takes 101 s.

Each distributed run keeps a profile in statement history. It holds each stage's operators with DuckDB's estimates, its cuts, each exchange's kind, keys and bytes sent, and every task's node, start, duration, rows, bytes and outcome. It holds no SQL and no row values beyond the cut bounds. In the console, a statement's drawer shows the stage graph and the node timeline side by side, linked by selection. From the command line, qod history run <id> prints the same profile for an admin, and qod profile statement-run <id> prints it for the caller's own statements.

For a caller under column or row policies, history keeps the run mode and compute time but not the stages or tasks, since those follow rows the policies hide.

Benchmark​

On eight nodes, the 22 TPC-H queries at scale factor 1000 took 251 s in total, against 1,035 s on one node: 4.1 times faster, and every answer matched.

Setup. TPC-H at SF1000 (6 billion lineitem rows) in one DuckLake database: Parquet files on S3 Standard, the catalog on RDS Postgres (db.m7g.large), all in eu-west-3. Eight m8gd.8xlarge servers (32 vCPU, 128 GiB each), one node per server, in one pool; the benchmark driver ran on a separate m8g.2xlarge. QoD 0.99.8 with default settings, except rate learning off (QOD_SPLIT_LEARN=false), so every decision used the default rates. On eight nodes, each query ran once unmeasured, then three times measured. For one node, the same pool ran with its split off, so each query ran whole on one of the same servers, three times. Times are the median of the three runs, as statement history records them. The runs took place on 2026-12-05.

Seconds per TPC-H query at SF1000 on 1 node and on 8 nodes, sorted by speed-up: 13 of 22 queries ran at least 5 times faster, q11 ran slower

Per query, the median speed-up is 5.8 times and the geometric mean 4.3 times. Thirteen queries ran at least five times faster, the best being q21 at 7.5 times (101.1 s down to 13.4 s).

Five queries stayed under 2.5 times, in two groups. q09 and q17 are long on both sides: 46.0 s and 43.1 s on eight nodes, 1.8 and 1.5 times faster, and together they account for 89 of the 251 seconds. q02, q11 and q22 take under 10 s even on one node, so planning and exchanging weigh more. The run profiles of q09 and q17 point at the exchange: q09 sent 350 GB between nodes and q17 104 GB, against 25 GB for q13, the next largest, and 0.1 GB for q21. q11 is the one loss: 6.4 s on eight nodes against 6.0 s on one. The planner predicted a gain of at least 1.5 times and got 0.9; with learning off, it priced the query from the default rate rather than from its own past runs.

Eight servers are eight times the hardware for 4.1 times the speed in total, so this is not linear scaling. The gain is largest on the long scans and joins, which is where a split is meant to help.

Correctness. Each of the 66 measured runs on eight nodes was compared with the matching run on one node: row count first, then every cell exactly, doubles within a relative difference of 1e-9. All 66 matched, and no run failed or reached the one-node time limit.

Every query's stage graph and node timeline can be browsed in the live demo.

Limits, and where DuckDB Scales goes further​

This release is built for a few nodes up to a few dozen, inside your own network. It does not:

  • distribute anything but a lone SELECT over the pool's DuckLake catalog: writes, transactions and queries that span catalogs run on one node,
  • split a correlated subquery that DuckDB plans as a dependent join; it stays on one node,
  • send an ENUM column across an exchange; such a query stays on one node,
  • retry a failed task; the whole statement reruns on one node,
  • run on Windows nodes, which carry no distributed engine. Linux and macOS nodes do.

One risk is known: DuckDB cannot count distinct values on a DuckLake table, so a GROUP BY on a nearly unique key can be distributed and shuffle every row, which may take longer than one node would.

On December 1, DuckLabs announced DuckDB Scales, an extension that scales DuckDB out for workloads beyond 100 TB. It is in preview in Amazon Athena, with an open-source release planned for H1 2027. Its design makes different trade-offs:

DuckDB ScalesQoD distributed queries
Where it runsAmazon Athena (preview)your own servers or cloud account
Largest reported run256 workers, TPC-H at 100 TB8 nodes, TPC-H at SF1000 (this post)
Data exchangefiles in object storageArrow Flight streams between nodes
Failed taskretried alonestatement reruns on one node
Single-node fallbackraces one node against the distributed plandecides before running, from a learned rate
Per-caller policiesnot described in the announcementevery task runs as the caller

Exchanging through storage costs a second network crossing per row, but it lets stages run independently and makes task retries cheap. That is the right call at hundreds of workers. Streaming between nodes is simpler and faster at the size QoD targets today. We plan to add a storage-based shuffle and task retries for long runs; this release does not include them.

Try it​

To see it without installing anything, open the live demo: the QoD console over TPC-H at SF1000, the 22 queries on one node and on eight, and the stages and tasks of each.

To run it yourself, start from the quickstart and give a pool two or more nodes on Linux or macOS. Distributed queries are off by default and switched on per pool:

qod pool set-split --tenant <tenant> --db <database> --pool <pool> --split

The same switch is --split on qod pool create, and POST /api/pool/setSplit over REST. Then run a query that takes more than five seconds on one node, and open its stage timeline. The server settings below have working defaults:

SettingDefaultWhat it controls
QOD_SPLIT_ENABLEDtrueturns every distributed plan off at once, on every replica
QOD_SPLIT_MIN_BYTES2 GiBsize the largest table must exceed
QOD_SPLIT_MIN_SECONDS5predicted single-node seconds before a split is considered
QOD_SPLIT_MIN_GAIN1.5predicted speed-up a split must reach
QOD_SPLIT_MAX_OVERLAP1.5file overlap a cut column may have
QOD_SPLIT_SMALL_TABLE_BYTES1 GiBsize under which a table is read whole by every task
QOD_SPLIT_COOLDOWN_MIN60minutes a shape stays on one node after a failed run
QOD_SPLIT_LEARNtruelearn rates from past runs, or use the configured ones
QOD_ENGINE_MAX_STAGES32most stages in a plan
QOD_ENGINE_BROADCAST_MAX_BYTES1 GiBlargest result broadcast to every task
QOD_ENGINE_TARGET_PARTITION_BYTES512 MiBtarget size of an exchange partition
QOD_ENGINE_RUN_TIMEOUT_SEC3600time limit of a run

QoD is open source under Apache-2.0 on GitHub. If a distributed answer ever differs from the single-node answer, that is a bug: please open an issue with the query, or tell us on Discord.

References​

Quack on Demand

DuckDB, DuckLake and DuckDB Scales

Techniques