Connect any database. Ask in plain English.

Try free
← Blog

DuckDB Larger Than Memory: Spilling to Disk, memory_limit, and a 1 GB Query Run at 250 MB (2026)

How DuckDB 2.0 queries data bigger than its memory: streaming, spilling to a temp directory, and the settings that matter. We ran one 17.7-million-group GROUP BY over 973 MB of Parquet at memory limits from 250 MB to the default: it finished every time, in 2.4 s unlimited and 15.9 s at 250 MB with 2.2 GB spilled, and we show which queries still ran out of memory.

Fastero Dev TeamFastero Dev Team2026-12-02

DuckDB's docs say it can process datasets "larger than the available system memory". We tested how far that holds on DuckDB 2.0.1: 43 million invented orders in a 973 MB Parquet file, one GROUP BY with 17.7 million groups run at six memory limits from 250 MB to the default, with the time, the peak memory and the temp files DuckDB wrote each time, then a set of queries chosen to break it.

The short answer: DuckDB handles data larger than memory in two ways. It streams: files are read a chunk at a time, so a scan, a filter or a GROUP BY with few groups never holds the whole file. And when a GROUP BY, JOIN, ORDER BY or window needs more than memory_limit (80% of RAM by default), it spills to a temp directory. Our 17.7-million-group GROUP BY over 973 MB of Parquet took 2.4 seconds unlimited and 15.9 seconds at a 250 MB limit, spilling 2.2 GB. What can still fail: aggregates that keep every value of a group (median, string_agg), several blocking operators in one query, and too many threads. Checked 2 December 2026.

Fastero

Connect your database. Ask questions. Get dashboards.

Postgres, BigQuery, Snowflake, and 10+ sources — live-connected, AI-powered, no dashboard builder learning curve.

Try free →

Can DuckDB handle data larger than memory?

Yes, and nothing needs switching on. DuckDB's memory management post (Mark Raasveldt, July 2024) describes the first mechanism: "Data sources, such as tables, CSV files, or Parquet files, are never fully materialized in memory. Instead, data is read and processed one chunk at a time." It lists what streaming alone makes larger-than-memory safe:

  • an aggregation "where the total number of groups is small"
  • reading one file and writing another, such as CSV to Parquet
  • a Top-N where N is small

On our test file, revenue by region (8 groups) over all 43 million rows at a 500 MB limit took 0.18 seconds, peaked at 106 MB and wrote no temp files.

The second mechanism is spilling. Some operators can't emit a row until they have seen all their input; the docs call them blocking operators, "the most memory-intensive operators in relational database systems": GROUP BY, JOIN, ORDER BY and window functions (OVER ... (PARTITION BY ... ORDER BY ...)). The docs say "DuckDB supports larger-than-memory processing for all of these operators." When their hash tables or sort runs outgrow the limit, "Larger-than-memory intermediates are (partially) written to disk in the temporary directory when required." It spills only past the limit, keeping as much in memory as it can.

DuckDB memory settings: memory_limit, threads, temp_directory

Setting Default (DuckDB 2.0) What it does
memory_limit 80% of RAM (50.0 GiB on our 64 GB laptop) The most DuckDB's buffer manager will hold before spilling
threads One per CPU thread (16 on our 8 cores) Each thread needs memory of its own
temp_directory .tmp in in-memory mode, <database>.tmp next to a database file Where spilled data goes
max_temp_directory_size 90% of available disk space Cap on the temp directory; past it, the query fails
preserve_insertion_order true Keeps row order for queries without ORDER BY; false lets DuckDB reorder and use less memory

Set them in SQL, or in Python when you connect:

SET memory_limit = '4GB';
SET threads = 4;
SET temp_directory = 'D:/duckdb_spill/';
SET max_temp_directory_size = '50GB';
SET preserve_insertion_order = false;
SELECT current_setting('memory_limit');
import duckdb
 
con = duckdb.connect(config={"memory_limit": "500MB", "threads": 4})
print(con.sql("SELECT current_setting('memory_limit'), current_setting('threads')").fetchall())
[('476.8 MiB', 4)]

Note the units: DuckDB reads 500MB as 500 million bytes and reports it in MiB, so '500MB' shows as 476.8 MiB. On threads, DuckDB's environment page says "As a rule of thumb, DuckDB requires a minimum of 125 MB of memory per thread" and recommends "Aim for 1-4 GB memory per thread." Our 250 MB limit on 16 threads was far under that minimum, and the query still finished.

DuckDB 2.0 also lists operator_memory_limit, unset by default, for "query intermediates (sorts, hash tables) per connection". We didn't test it.

Demo: a 1 GB Parquet file at a 250 MB memory limit

We made the test data with DuckDB itself: 43 million orders with an order ID, one of 20 million possible customer IDs, a region, one of 5,000 products, an amount and a timestamp, all invented. The core of the script, run once:

con.execute(f"""
COPY (
  SELECT i AS order_id,
    (hash(i * 7919) % 20000000)::INTEGER AS customer_id,
    ['North','South','East','West','Central','Online','Partner','Export'][1 + (hash(i * 31) % 8)::INTEGER] AS region,
    'product-' || lpad(((hash(i * 131) % 5000))::VARCHAR, 4, '0') AS product,
    round(5 + random() * 495, 2) AS amount,
    TIMESTAMP '2024-01-01' + to_seconds((hash(i * 17) % 63072000)::BIGINT) AS order_ts
  FROM range(43000000) t(i)
) TO 'orders.parquet' (FORMAT parquet)""")
rows 43,000,000  row groups 350  file 973,472,607 bytes  uncompressed 1,318,440,676 bytes  in 25.6s

The file is 973 MB on disk and 1.32 GB uncompressed by its own metadata. Loaded whole, it would be about 2.3 GB as an Arrow table and 2.6 GB as a pandas DataFrame (we measured a 1-million-row sample, 54.0 MB and 61.5 MB, and multiplied by 43, so treat those as estimates).

The query asks for the five biggest customers. It is the hard case for memory, because the hash table needs a slot for each of the 17,672,152 customers who placed an order. This is the script we ran, with a second cursor reading DuckDB's own list of temp files while the query works:

import os, threading, time
import duckdb
 
con = duckdb.connect()                       # in-memory database
con.execute("SET memory_limit = '250MB'")
con.execute("SET temp_directory = 'spill/'")
 
# a second cursor watches DuckDB's own list of temp files while the query runs
peak, done = {}, False
def watch():
    cur = con.cursor()
    while not done:
        for path, size in cur.sql("SELECT path, size FROM duckdb_temporary_files()").fetchall():
            peak[path] = max(peak.get(path, 0), size)
        time.sleep(0.1)
threading.Thread(target=watch, daemon=True).start()
 
t = time.perf_counter()
top = con.sql("""
    SELECT customer_id, count(*) AS orders, round(sum(amount), 2) AS revenue
    FROM 'data/orders.parquet'
    GROUP BY customer_id
    ORDER BY revenue DESC, customer_id
    LIMIT 5
""").fetchall()
done = True
print(top)
print(f"{time.perf_counter() - t:.1f} s, {len(peak)} temp files, {sum(peak.values()) / 1e9:.2f} GB at their largest")
for path in sorted(peak)[:3]:
    print(path, peak[path])
print("temp files DuckDB lists now:", con.execute("SELECT count(*) FROM duckdb_temporary_files()").fetchone()[0])
print("left in spill/:", [(f, os.path.getsize("spill/" + f)) for f in os.listdir("spill")])
[(843124, 12, 4412.77), (9009216, 11, 4167.59), (19855054, 12, 4127.34), (11427866, 12, 3987.11), (656387, 12, 3983.17)]
13.0 s, 7 temp files, 2.22 GB at their largest
spill/duckdb_temp_9828_0_storage_DEFAULT-0.tmp 1048576000
spill/duckdb_temp_9828_0_storage_DEFAULT-1.tmp 117440512
spill/duckdb_temp_9828_0_storage_S128K-0.tmp 307101696
temp files DuckDB lists now: 0
left in spill/: [('duckdb_temp_9828_0_owner', 0)]

A 250 MB limit, a 973 MB file, 2.22 GB of temp files, and the right answer in 13 seconds. Once the query returned, DuckDB had deleted its spill files; only an empty owner marker stayed until the process exited.

For the table, we ran the query in a fresh process per setting, five times each, measuring peak memory with psutil and polling the temp directory every 20 ms. Every run returned the same five customers:

memory_limit Time (median of 5) Peak process memory Temp files at the peak
250 MB 15.9 s 353 MB 2.2 GB
500 MB 12.9 s 610 MB 1.0 GB
1 GB 3.7 s 1.15 GB 687 MB
2 GB 2.4 s 2.11 GB 88 MB
4 GB 2.4 s 2.14 GB none
Default (50 GiB) 2.4 s 2.08 GB none

Three bar charts for one DuckDB GROUP BY over 43 million rows at six memory limits: time rises from 2.4 seconds with no limit to 3.7 s at 1 GB, 12.9 s at 500 MB and 15.9 s at 250 MB; peak memory falls from 2.08 GB to 353 MB, slightly above each limit; temp files grow from none to 88 MB at 2 GB, 687 MB at 1 GB, 1.0 GB at 500 MB and 2.2 GB at 250 MB

The same query at six memory limits: lower limits trade memory for temp files and time. Invented data, one laptop, medians of 5 runs.

What the numbers say:

  • Unconstrained, this query wants about 2.1 GB. At 4 GB and the default it never spilled; at 2 GB it spilled 88 MB at no measurable cost.
  • Down to 1 GB, spilling is cheap: about 1.6 times the unlimited time. At 500 MB and 250 MB it was 5 to 7 times slower, and the runs varied more (11.3 to 18.2 seconds at 500 MB, 14.1 to 19.1 at 250 MB) on a laptop other work was also using.
  • Peak memory sat 100 to 150 MB above the limit. The limit governs DuckDB's buffer manager, not the whole process: the docs warn that "some of DuckDB's operations circumvent the database's buffer manager and thus they can reserve more memory than allowed by the memory limit." Leave headroom when you size a container.
  • The temp files were bigger than the memory they replaced: 2.2 GB of spill at 250 MB. Budget disk, not only RAM.
  • At a tight limit, fewer threads was faster. At 250 MB, 4 threads took 11.3 seconds (median of 3) and spilled 1.6 GB, against 15.9 seconds on the default 16 threads. One thread took 19.9 seconds.

Connect any database. Ask in plain English.

Start free →

Which DuckDB operators spill, and which can still fail

We ran eight more queries over the same 43 million rows at a 500 MB limit and 16 threads, one run each, then without a limit (our harness stops any process past 3.2 GB):

Query At 500 MB Without a limit
Revenue by region (8 groups) 0.18 s, no spill
Repeat buyers: GROUP BY, JOIN back to all 43 million rows, then aggregate 12.7 s, 2.3 GB spilled 3.2 s, 2.7 GB of memory
Window: lag() over each customer's orders in time order 8.8 s, 1.3 GB spilled 5.1 s, 2.2 GB
mode(product) per customer 24.7 s, 2.3 GB spilled over the 3.2 GB cap
string_agg(product, ',') per customer Out of Memory after 7.7 s 2.3 s, 2.2 GB
median(amount) per customer Out of Memory after 2.6 s over the 3.2 GB cap
list(amount ORDER BY order_ts) per customer Out of Memory after 32 s over the 3.2 GB cap
COPY three columns to a 550 MB Parquet file 1.6 s, 300 MB peak, no spill 1.5 s, 675 MB

Every blocking operator we tried spilled and finished, including the query with a GROUP BY and a JOIN in it. DuckDB's docs warn that "If multiple blocking operators appear in the same query, DuckDB may still throw an out-of-memory exception due to the complex interplay of these operators", so a deeper query can still fail where this one didn't.

The failures were the aggregates that keep every value of a group, which matches the docs' limitations: "Some aggregate functions, such as string_agg(), do not support offloading to disk", and aggregates that sort, like median and list(... ORDER BY ...), "are holistic, i.e., they need all inputs before the aggregation can start." Here the sources disagree a little. DuckDB 2.0's preview post says "aggregations now spill to disk when they outgrow memory", and the pull request behind it tests string_agg among the aggregate states that now spill, while histogram and mode "keep the current behavior". In our runs mode finished at 500 MB and string_agg didn't. Test your own query rather than trusting either list.

What fixed them, and what didn't:

  • string_agg finished at 500 MB on 1 thread, in 20.8 seconds. On 4 threads it still failed, and at 1 GB on 16 threads too.
  • median failed at every setting we tried under the cap: at 500 MB on 4 threads after writing 6.2 GB of temp files, on 1 thread after 13.2 GB and 40 seconds, and at 1 GB on 16 threads. Per-group medians over 17.7 million groups needed more than 3.2 GB of memory here.
  • preserve_insertion_order = false cut the COPY's peak from 300 MB to 258 MB at 500 MB (single runs). The docs recommend it for imports and exports "which are much larger than the available memory"; a three-column copy streams anyway, so the gain was small.

How to fix "Out of Memory Error" in DuckDB

The error names the limit it hit. Ours read (we left out its last line, a link to the docs):

OutOfMemoryException: Out of Memory Error: failed to pin block of size 256.0 KiB (476.8 MiB/476.8 MiB used)
 
Possible solutions:
* Reducing the number of threads (SET threads=X)
* Disabling insertion-order preservation (SET preserve_insertion_order=false)
* Increasing the memory limit (SET memory_limit='...GB')

In order of what to try:

  1. Lower threads. DuckDB's out-of-memory guide puts this first: "Reduce the number of threads using the SET threads = ... command."
  2. Set preserve_insertion_order = false for big imports and exports (CSV to Parquet, COPY, CREATE TABLE AS) when row order doesn't matter.
  3. If the operating system kills DuckDB (Killed on Linux, or a container restart), lower memory_limit. The guide says to "set the memory limit to just 50-60% of the total system memory", because some allocations happen outside the limit.
  4. Point temp_directory at a fast disk with room, and raise max_temp_directory_size if the temp directory fills. DuckDB's disk-based mode "is designed to work best with SSD and NVMe disks".
  5. Split the query. Save the first aggregate with CREATE TABLE ... AS, then query that, so one blocking operator runs at a time.
  6. Use smaller types and drop indexes. Small values in large types "will take up more memory during processing", and indexes "are currently not buffer-managed".
  7. Give it more memory. When a hash table needs to sit in RAM to be fast, an hour on a bigger machine costs less than an afternoon of tuning.

DuckDB vs pandas when the data is bigger than RAM

pandas has no spill path: read_parquet builds the whole DataFrame in memory, about 2.6 GB for our file, before a groupby starts. Our guides to pandas running out of memory and reading a large CSV in pandas cover chunking and dtypes. Often it's simpler to let DuckDB reduce the data and hand pandas the result with .df(), as our DuckDB Python tutorial times; DuckDB vs pandas covers when each fits, and Spark vs pandas the point where one machine isn't enough.

When the notebook machine is the limit

Fastero is an AI and data platform where people and AI agents work together on a team's data, and its notebooks run on a server nobody on the team has to set up. What matters for a memory problem, from our pricing page on 2 December 2026:

  • The standard machine is 1 CPU and 2 GB, included on every plan, Free too. Our test query wanted about 2.1 GB to run without spilling, and the file as a pandas DataFrame would be about 2.6 GB, so a job like it streams and spills there or moves up a size.
  • On Pro, a notebook can move to a bigger machine: 2 CPUs and 8 GB at $0.20 an hour, 4 CPUs and 16 GB at $0.40, or 8 CPUs and 32 GB at $0.80, charged by the second from money added to the balance. Pro's $20 a month doesn't cover them.
  • SQL cells run the query in your database (Postgres, MySQL, SQL Server, Redshift, Oracle or BigQuery, on a saved connection), and only the result lands in Python, as a pandas DataFrame named after the cell. Aggregate in SQL and the notebook never holds the raw rows.
  • Python 3.11 with pandas, SQLAlchemy and seaborn is installed. A cron schedule runs the notebook on the server with no browser open, and colleagues sign in to read it for free.

A Fastero notebook titled Solar output against forecast, with a pandas cell that builds a DataFrame of twelve invented solar sites inline and prints them sorted by output against forecast

A Fastero notebook running pandas. Sample data, defined inline in the cell.

FAQ

Does DuckDB load the whole file into memory?

No. DuckDB reads CSV and Parquet files a chunk at a time and keeps only what the query needs: in our test, a GROUP BY with 8 groups over a 973 MB file peaked at 106 MB. Only blocking operators such as a GROUP BY with millions of groups, a join, a sort or a window build large state, and those spill to disk past the memory limit.

What is DuckDB's default memory limit?

80% of the machine's RAM. On our 64 GB laptop, SELECT current_setting('memory_limit') returned 50.0 GiB. In a container, set it yourself below the container's limit, because DuckDB can use somewhat more than memory_limit in total.

How do I set the DuckDB memory limit in Python?

Run SET memory_limit = '4GB' with con.execute(), or pass config={"memory_limit": "4GB"} to duckdb.connect(). RESET memory_limit restores the default, and current_setting('memory_limit') shows the value in force.

Where does DuckDB write temporary files?

For an in-memory database, to a .tmp folder in the working directory; for a database file, to <database>.tmp next to it. Change it with SET temp_directory = '...'. DuckDB deletes the files once the query finishes; ours peaked at 2.2 GB for one query at a 250 MB limit.

Why does DuckDB use more memory than memory_limit?

The limit governs DuckDB's buffer manager, and some operations allocate outside it. Our runs peaked 100 to 150 MB above the limit. DuckDB's guide suggests setting the limit to 50-60% of system memory if the operating system is killing the process.

Can DuckDB still run out of memory?

Yes. Several blocking operators in one query, aggregates that keep every value of a group, and too many threads for a small limit can all end in Out of Memory Error. In our tests a per-customer string_agg failed at 500 MB on 16 threads but finished on one, and a per-customer median failed even at 1 GB.

How big a dataset can DuckDB handle on a laptop?

Data well beyond RAM, if the query streams or spills: what bounds it is free disk for temp files and the time you'll wait. Our 973 MB file at a 250 MB limit wrote 2.2 GB of temp files, about 2.3 times the file. If your query spills in that proportion, a 10 GB file at a similarly tight limit wants 20 GB or more of free disk; that is an estimate, not a measurement.

Sources

Read on 2 December 2026:


Try Fastero free: run your notebooks on a server your team can read, and rent 16 GB on Pro by the hour when a job outgrows 2 GB. No credit card required.

Ready to try it yourself?

Connect your database, ask questions in plain English, and get live dashboards — in under 2 minutes. No credit card required.

Follow Fastero on LinkedIn for new articles and examples.