Why AI Agent Queries Could Cost Less on Athena Powered by DuckDB

Ask an AI agent “why did revenue dip last week?” and it will not run one query. It might run 40. Suppose each scans 2 GB. On Athena engine version 3, which bills by the data scanned, that is 80 GB for a single question, about $0.40. Ask a hundred questions a day and the query bill alone is $40 a day.

Amazon Athena powered by DuckDB is a preview version of Athena that runs your SQL on DuckDB, the open-source analytical database, and bills by compute time instead of data scanned. That change is why AI agent queries could cost less on it: when an agent asks many small questions, the billing unit decides the bill. This post covers what AWS announced, how the pricing works, a 40-query agent session that I ran and timed, whether you can replace Spark with DuckDB for smaller workloads, and why DuckDB for AI agents is the part AWS keeps stressing.

📌 TL;DR

Athena powered by DuckDB is in preview in five regions, with general availability planned for 2027. It is billed per millisecond of compute, not per terabyte scanned, which suits agents that ask many small questions. In my local test, a 40-query agent session over 1.8 GB of Parquet took under 50 seconds on two vCPUs. Priced at an assumed 4 DPUs, that is about six times cheaper than the per-scan estimate. Those are my assumptions, not an Athena benchmark.

Yes, this is a long read, on purpose. Along the way you will pick up the basics: what “in-process” means, how Athena is priced, how to compare two job outputs with one SQL query, and why agents change the economics. Short on time? Use the boxes below.

I have written about DuckDB while working on a validation framework, and in my last post, Is Spark Overkill for Most Pipelines?, I compared DuckDB and Polars output row by row before trusting a migration. What I keep seeing is Spark used for small jobs. If AI agents are going to understand, clean and operate on data, they will run thousands of small queries, and a cluster is the wrong shape for that bill. That is why the Athena news caught my eye.

Three-panel comic: Nikita asks an agent why revenue dipped, the agent runs forty queries, and Nikhil asks who pays for forty scans on a cluster.

By the end you’ll be able to:

  • explain what Athena powered by DuckDB is, and what is still preview or planned;
  • explain why agent workloads, which are many small queries, change how query pricing behaves;
  • price a 40-query agent session on both Athena models and find your own break-even;
  • judge whether a Spark job could move to DuckDB, and what to check first;
  • write seven data checks as plain SQL and compare two job outputs with EXCEPT.

IN A HURRY? THE WHOLE STORY IN FIVE LINES

  • An agent explores data. One question can mean 40 small queries, so the price of the next query matters more than the price of any one.
  • Athena powered by DuckDB is in preview in five regions, with general availability planned for 2027. It costs $0.35 per DPU-hour, billed per millisecond, where engine version 3 costs $5 per TB scanned.
  • In my local test, 38 of 40 queries finished in about two seconds or less. The other two, both distinct counts, took about ten seconds each.
  • AWS’s claim of up to 2x faster and up to 50% cheaper is against Athena’s old engine, not against Spark. No benchmark has been published.
  • For SQL jobs that fit one machine, DuckDB is a credible Spark replacement. Spark keeps streaming, huge shuffles and UDF-heavy code.

🧭 HOW TO READ THIS POST

Table of Contents

Why AI agent queries are a different workload for your data platform

An AI agent explores data by asking many small, throwaway queries, so the price of the next query matters more than the price of any single one. People query occasionally and think between queries. An agent asks, reads the answer, and asks again. AWS makes the same point on its analytics for agents page: agents run many small queries in parallel and expect instant answers, and cluster overhead on every small query adds up in cost.

Understanding, cleansing and operations are all loops of small queries

  • Understanding data. Profile a column, slice a metric by country, check whether last week looks like the week before.
  • Cleansing data. Find duplicates, impossible values and orphan keys, propose a fix, then run the checks again.
  • Operating on data. Compare a table before and after a change, verify a backfill, reconcile two systems.

Each one is a loop of ask, read, ask again, and most of the answers are thrown away. My view is that agents will not scale across this work until those queries are cheap, because the loop multiplies whatever one query costs. It is not the only bottleneck, and the section on what agents still need covers the others.

What DuckDB is, and why “in-process” matters

DuckDB is an open-source analytical SQL database that runs inside your own process, reads files such as Parquet directly, and needs no server or cluster. “Analytical” means it is built to scan many rows of a few columns and aggregate them, which is what reports, checks and agent questions do. “In-process” means it is a library, like a calculator on your desk, not a service you call over a network.

Spark is a distributed engine: it splits the work across many machines, which pays off when the data does not fit on one. The price of that design is fixed overhead, such as starting a cluster, planning, and moving data between machines. For a job that fits on one machine, or a query that touches a few gigabytes, that overhead can cost more than the work. I covered the numbers in my earlier post on Spark overkill.

What AWS announced about Athena powered by DuckDB at re:Invent 2026

AWS announced on 1 December 2026 that Amazon Athena, its serverless SQL service for data in S3, can now run on DuckDB, starting with a preview. According to the AWS announcement, the preview runs in US East (N. Virginia), US East (Ohio), US West (Oregon), Europe (Ireland) and Asia Pacific (Tokyo). It supports Apache Iceberg v3 and Parquet tables through the Glue Data Catalog, and you pick the engine when you create or switch a workgroup. AWS calls it the first AWS analytics service built on DuckDB.

Athena powered by DuckDB and five related announcements as six cards: Athena powered by DuckDB in preview, the DuckDB extension for Athena, DuckDB Scales, and planned support in EMR and Redshift.

Three pieces are worth separating, because they have different status.

  • The engine. Athena powered by DuckDB is in preview. AWS says it can spread a single query across many nodes and return results in seconds on tens of terabytes.
  • The laptop bridge. An open-source DuckDB extension for Athena lets you build SQL in DuckDB on your laptop, then run the same queries on Athena when the data grows.
  • DuckDB Scales. This is the extension that does the multi-node part. DuckDB.org says it is initially available in Athena, with an open-source release planned for the first half of 2027.

AWS also says DuckDB is coming to Amazon EMR and will be built into Amazon Redshift, with more services following through 2027. The goal, in AWS’s words, is for DuckDB SQL to become the common language of its analytics services. See the Amazon announcement for the details. No dates were given for EMR or Redshift.

The company behind DuckDB has joined AWS

This did not come from nowhere. In August 2026, AWS announced an agreement to acquire DuckLabs, the company behind DuckDB. AWS bought the company, not the open-source project. DuckDB stays under the MIT licence and under the independent DuckDB Foundation, and the creators, Hannes Mühleisen and Mark Raasveldt, continue to lead its technical direction.

The same AWS post says DuckDB was designed for everyday queries of about a terabyte or less. It contrasts that with older engines such as Spark, which were built for very large workloads. That framing is the heart of this post.

Athena DuckDB pricing: why the billing unit matters for agents

By default, Athena engine version 3 charges by the data a query scans, and Athena powered by DuckDB charges by compute time instead. According to the Athena pricing page, on-demand engine version 3 costs $5 per TB scanned with a 10 MB minimum per query. (If you reserve capacity on engine version 3, you pay $0.30 per DPU-hour instead.) Athena powered by DuckDB costs $0.35 per DPU-hour in preview, billed per millisecond with a 100 ms minimum. The page’s own example is a 4-DPU query that runs for 2 seconds and costs about $0.0007778. The page does not state a region, so check the rate for yours.

YOU MIGHT BE WONDERING

What is a DPU?

A DPU is a unit of compute capacity that you are billed for. In AWS Glue, one DPU is 4 vCPUs and 16 GB of memory. The Athena pages I read do not say what a DPU holds for Athena powered by DuckDB, so for now treat it as a billing unit and measure your own queries.

Athena powered by DuckDB pricing shown as two Athena price tags, five dollars per terabyte scanned and thirty-five cents per DPU-hour, with a break-even table from one gigabyte to five hundred gigabytes.

The break-even is simple arithmetic. If a query scans 20 GB, engine version 3 charges about $0.10 (I treat 1 TB as 1012 bytes, and column pruning in Parquet may mean you scan less). At $0.35 per DPU-hour, Athena powered by DuckDB costs less than that as long as the query uses fewer than 1,029 DPU-seconds. Eight DPUs for 129 seconds is the same money.

The back-of-envelope version of the agent session

Now apply that to the opening question. Forty queries that each scan 2 GB cost 40 × $0.01 = $0.40 on engine version 3. On the DuckDB engine, if each query used 4 DPUs for 2 seconds, it is 40 × $0.00078, about $0.03. If each needed 8 DPUs for 10 seconds, the session costs $0.31 and the advantage nearly disappears. The sizes and durations are assumptions, because AWS has not published them, so the next section replaces them with measurements. The script behind these figures is in the code section.

AWS’s headline figures need careful reading. The announcement says queries run up to 2x faster and cost up to 50% less on large datasets, compared with Athena engine version 3. In the keynote, Matt Garman tied the speed figure to TPC-DS, a standard analytics benchmark, and the cost figure to queries of roughly 100 GB or more, according to a third-party transcript. These are upper bounds against Athena’s old engine. They are not a comparison with Spark, and I could not find the benchmark details.

I ran a forty-query agent session on DuckDB: what it cost and how long it took

A 40-query agent session is a good unit of cost because it is what one question really consumes. To replace assumptions with measurements, I wrote a script that builds a synthetic orders table in Parquet and runs the 40 queries an agent might plausibly run for “why did revenue dip last week?” The results below come from DuckDB on my sandbox, not from Athena, and the section on what the test cannot tell you says why that matters.

The setup: one orders table with two planted causes

The table has 136,438,383 orders over 12 weeks, from 7 September to 29 November 2026, stored as 1.77 GB of zstd-compressed Parquet in six files. Columns are order time, country, channel, device, category, product, customer, amount, discount and a refund flag. I planted two causes, so I know the right answer in advance. In the week of 16 November, an email campaign inflates sales. From Wednesday 25 November, 75% of German paid-search orders disappear. Revenue falls 6.1% week on week.

The code in this post was written with the help of Claude to clarify the ideas. It is illustration, not production code. I ran every script on DuckDB 2.0.1 in a Linux sandbox with two vCPUs, reading files from local disk. None of it was run on Athena’s DuckDB preview.

What the forty queries found

The session runs in five phases: six queries to confirm the dip, ten to slice it by one or two dimensions, nine to drill into the suspect, nine to rule out alternatives such as refunds, discounts, duplicates and outliers, and six to size the cause. The script asserts that the largest segment it finds is German paid search, so the answer is checked and not assumed.

Bar chart of the elapsed time of each of the forty agent queries in five coloured phases, with most bars under two seconds and two distinct-count queries near ten seconds.

Here is the story the queries tell. By query 8, the change by channel shows email down 30% week on week. By query 13, the country and channel slice shows the largest single segment: German paid search, down 53%. Email, the ending of last week’s campaign, explains about three quarters of the total dip. German paid search explains about a quarter, and it is the part worth escalating, because it started on a Wednesday and is a fault, not a pattern. An agent that stopped at query 8 would have blamed the campaign and missed the fault. That is a good reason for an agent to keep asking, and a good reason for each question to be cheap.

How long it took

Across six runs, the 40 queries took between 46.6 and 49.6 seconds in total, and the last run took 48.4 seconds. The median query took 0.37 seconds. Thirty-eight of the 40 finished in about 2.1 seconds or less. The other two, “distinct customers by week” and “repeat-customer share by week”, took 9.9 and 10.9 seconds, because counting distinct values over five million customer ids is much heavier than summing an amount. Those two queries are 43% of the session time. The “rule out” phase alone took 28.6 of the 48.4 seconds, so being careful is where the time goes.

What it would cost

I need a bill for each side. Engine version 3 bills for bytes read, so I estimated that as the compressed size of every column each query touches, summed over all six files. That ignores Parquet’s row-group skipping, so it is an upper bound. The average query touched about 0.57 GB, the range was 0.27 to 0.82 GB, and none came near the 10 MB minimum. For the DuckDB engine, I priced the same elapsed times as if 1, 2, 4 or 8 DPUs were billed for that long. That is an assumption about Athena’s engine, not something AWS has published.

Bar chart of the measured forty-query agent session priced two ways: about eleven cents on Athena engine version 3 by estimated bytes read, against between half a cent and four cents on the DuckDB engine at one to eight assumed DPUs.
How the session is billed Cost of 40 queries Headroom
Athena engine version 3 (22.8 GB read, estimated) $0.114 Baseline
DuckDB engine, 1 DPU for the measured time $0.0047 24x
DuckDB engine, 2 DPUs $0.0094 12x
DuckDB engine, 4 DPUs $0.0189 6.0x
DuckDB engine, 8 DPUs $0.0378 3.0x

Headroom is how many times longer the DuckDB engine could run than my sandbox, at that DPU count, before the session costs as much as engine version 3. At 4 DPUs the engine could be six times slower than my two vCPUs and still break even. That is a comfortable margin on this data, and it is the number to test on your own queries.

There is a second lesson in the table. Under per-TB billing, the two slow distinct-count queries cost the same as every other query that touches the same columns, about $0.0036 each. Under per-millisecond billing, each costs roughly 26 to 29 times the median query. Compute billing makes heavy queries visible, which is useful, because an agent that writes a heavy query should hit a timeout or a budget before it hits your invoice.

What this test cannot tell you

  • It is not S3. Files were on local disk with a warm cache. On S3, latency and throughput matter, and the first read is slower.
  • It is not Athena. AWS’s engine may behave differently from the DuckDB library on my sandbox, and a DPU is not defined for the preview.
  • It is one agent at a time. Real agents run queries in parallel, so concurrency limits and queueing matter, and I did not test them.
  • It ignores start-up. I did not measure the cold start of a serverless workgroup.
  • It ignores the model. An agent also pays for the language model that writes and reads these queries. Measure both bills before you claim a saving.
  • The data is synthetic. Real tables have skew, messy types and wider rows.

🦆 My take:

The saving is not in doubt on the arithmetic, because per-millisecond billing rewards small queries. What I would not claim yet is how big it is on your data. Run your own 40 queries, in a test workgroup, with the DPU count and elapsed time written down for each.

Why small jobs overpay on a cluster

A small Spark job overpays because of fixed costs: cluster start-up, billing minimums and default sizes that were chosen for much larger work. The work itself is often the cheap part. This is the same pattern as the agent session, just with one job instead of forty queries.

Here is a nightly check priced three ways, using the list prices I quoted in my earlier post (read on 22 October 2026). In production it is about 20 GB of Parquet. Run times are assumptions, so treat the figures as illustrative.

Setup Assumed run Cost per run At 20 runs a day
Spark on Glue, default 10 DPUs 30 minutes $1.54 $11,242 a year
Spark on Glue, right-sized to 2 DPUs 12 minutes $0.12 $899 a year
DuckDB in one Fargate task (4 vCPU, 16 GB) 5 minutes $0.019 $142 a year

Two lessons sit in that table. Right-sizing Spark gets most of the saving, which is why tuning and fixing skew still matter. The engine swap gets the rest and removes the start-up minutes.

Timeline comparing a Spark cluster job with about five minutes of start-up to a DuckDB in-process job that starts in about 22 seconds, for the same nightly job.

Can you replace Spark with DuckDB for smaller workloads?

For SQL-shaped batch work that fits on one machine, or on one managed query, you can replace Spark with DuckDB, and it is usually the cheaper option. It does not cover everything Spark does. That is my reading of the evidence, and I will separate what has been measured from what has not.

What independent tests show

These are the same results I used in the Spark overkill post, so you can follow the sources there.

Who Setup Result Caveat
Digital Turbine About 40 GiB Parquet, one 16-core machine DuckDB 3.99 s vs Spark 16.39 s (4.1x) Spark used mostly default settings; they still use Spark for their larger data
Matt Martin 1,000 small JSON files on S3 DuckDB on Fargate 48.8 s vs EMR Serverless 167.5 s (3.4x) The source is paywalled; the caveats I noted are in my earlier post
Niels Claeys 100 GB TPC-DS, 8 vCPU, 32 GB DuckDB won most queries and ran out of memory on one The counterweight: 100 GB is where it gets even

Nothing independent has measured Athena powered by DuckDB yet, and AWS’s 2x figure is against Athena’s old engine. The closest real-world story so far is Atlan’s. Atlan moved its metadata pipelines from Spark to DuckDB running in-process on Parquet and Iceberg files in S3. It reports about 40% lower cost where a DuckDB service replaced StarRocks, and it gives no Spark cost figure or benchmark numbers. It is a vendor case study written with the DuckDB team, so I treat it as a data point and not as proof.

Where DuckDB is a good fit

  • nightly checks and reconciliations;
  • small and medium transformations on Parquet or Iceberg files;
  • unit and integration tests for pipelines, which can run on a laptop or in CI;
  • many short, independent queries, such as dashboards or agent lookups.

Where Spark still wins

  • shuffles and joins whose intermediate state is larger than one machine’s memory, until DuckDB Scales is open source and proven;
  • streaming and long-running stateful jobs;
  • code that depends on Python or Scala user-defined functions;
  • shared platforms where governance, lineage and tooling are already built around Spark.

Also check what your target engine can write. The Athena pages I could read describe querying Iceberg v3 and Parquet. They do not say which write operations the DuckDB engine supports, so look at the SQL reference in the Athena user guide before you plan a migration that writes tables. If your tables are Iceberg, my Iceberg post explains why the format matters here: any engine that reads the same table format can share the data.

Four steps from smaller to bigger work: DuckDB in process, Athena with the DuckDB engine, DuckDB Scales, and Spark, each with the kind of job it suits.

A checklist before you move one job

  • Measure the working set. Read input and shuffle bytes from the Spark UI. What matters is the data after pruning, not the raw table size.
  • Count the UDFs. Custom functions rarely move unchanged.
  • Confirm the writes. Make sure the target engine can write your table format.
  • Run both for a while before you replace Spark with DuckDB. Compare the outputs with EXCEPT, as in the next section.
  • Pin the version. DuckDB 2.0.1 LTS (long-term support) came out on 20 November, so use the same version on your laptop, in CI and in production.

Data cleansing with DuckDB: seven checks an agent could run

Data cleansing with DuckDB starts by writing each rule as a SQL query that counts the rows that break it, then running those queries on the same files your pipeline produces. The result is a table of failed counts you can assert on. An agent can write and run these, and the checks double as the tests that tell you whether the agent’s fix worked.

The toy job: a nightly check on an orders table

Imagine a nightly check on an orders table. In the code it is 2,001,000 rows, so you can run it anywhere. The table has defects on purpose: 1,000 duplicated order ids, 500 missing customer ids, 400 negative amounts, 200 invalid statuses, 100 timestamps in the future and 250 orders for customers that do not exist. Because I seeded them with simple rules, every expected count is exact.

tiny_check.py: duplicates, bad amounts and EXCEPT on four rows
import duckdb

# Part 1: four orders. Order 2 appears twice, order 3 has a negative amount.
duckdb.sql("""
    SELECT count(*) - count(DISTINCT order_id)  AS duplicate_rows,
           count(*) FILTER (WHERE amount <= 0)  AS bad_amounts
    FROM (VALUES (1, 20.0), (2, 35.5), (2, 35.5), (3, -4.0)) t(order_id, amount)
""").show()

# Part 2: EXCEPT on two tiny tables, once in each direction.
con = duckdb.connect()
con.sql("CREATE TABLE a AS SELECT * FROM (VALUES (1), (2), (3)) t(x)")
con.sql("CREATE TABLE b AS SELECT * FROM (VALUES (1), (2), (4)) t(x)")
print("only in A:", con.sql("SELECT x FROM a EXCEPT SELECT x FROM b").fetchall())
print("only in B:", con.sql("SELECT x FROM b EXCEPT SELECT x FROM a").fetchall())
Output:
┌────────────────┬─────────────┐
│ duplicate_rows │ bad_amounts │
│     int64      │    int64    │
├────────────────┼─────────────┤
│              1 │           1 │
└────────────────┴─────────────┘

only in A: [(3,)]
only in B: [(4,)]

Each check is a small SQL query that counts the rows that break a rule. The first query above finds one duplicated order and one negative amount in four rows, and you can verify that by eye. The second shows EXCEPT, which returns the rows in one table that are missing from the other. Run it in both directions and you have a full comparison.

Table of seven SQL data checks on a two-million-row orders table, each catching exactly the seeded number of bad rows, plus a note that EXCEPT found 96 differing rows between a legacy and a migrated output.

The full seven-check script is in the code section. It reads Parquet, a columnar format: values are stored column by column, so a query that needs two columns can skip the rest. I compared it with CSV in my post on CSV versus Parquet. All seven checks ran in about 0.2 seconds on my two-vCPU sandbox. That is a correctness demo and not a benchmark.

Three-panel comic: matching row counts are not proof of correctness, an EXCEPT query in both directions finds 96 differing rows caused by a rounding bug, and the same SQL is wanted on a laptop and in the cloud.

Row counts alone miss most bugs, which is why Nikita in the comic is right to push back. In the toy, I “migrated” a job and slipped in one rounding bug. Both versions return the same number of rows. Running EXCEPT in both directions shows that 96 rows exist only in the legacy output and 96 only in the new one. That one query is the check I would run before trusting any migration, from Spark to DuckDB or the other way round.

This is also where the Athena extension could matter. The idea in the announcement is that you write the SQL on your laptop, then run it on Athena when the data gets bigger. I have not tried the extension yet, so I cannot say how closely the two behave. If they match, you test a rule on 1 GB at your desk and run it unchanged on the lake.

Athena powered by DuckDB workflow, from a laptop running DuckDB with the Athena extension, to an Athena workgroup on the DuckDB engine, to S3 data in Parquet and Iceberg v3, with results streaming as Arrow to an agent or notebook.

DuckDB for AI agents: what AWS is building, and what is still missing

DuckDB for AI agents is AWS’s bet that the next big analytics user is software, and that software needs cheap, fast, embeddable SQL. The engine is one part of that bet. The tooling around it is the other, and it is where the rest of this section goes.

Tools built for agents

AWS’s agents page lists an AWS extension for DuckDB that handles credentials, attaches resources by ARN, and works as an embedded library, from the command line or as an agent tool. Athena adds a streaming API and an Arrow Database Connectivity (ADBC) driver, so results stream into data science tools as they arrive in Apache Arrow, a columnar in-memory format. AWS says one SQL dialect across services gives agents fewer errors. I would call that plausible and unmeasured.

Cheap queries are necessary, not sufficient

My view is that cheap queries remove the first bottleneck, not all of them. A lot has to be built before agents take over most data work, and this announcement is one step forward at enterprise level. These are the pieces I would want next.

  • Context. An agent needs to know what a column means, which table is the source of truth and what “revenue” includes.
  • Guardrails. A read-only role, a limit per workgroup and a log of every query it ran.
  • Verification. Deterministic checks, like the seven above, that run on the data an agent reads and on the fix it proposes.
  • Evaluation. A way to score whether the agent’s answer was right, not only whether the query ran.

In my post on AI agent platforms and data platforms, I argued that the model should propose and deterministic code should decide, and that an agent with SQL access should start read-only. Cheap queries make that easier to follow, because the checks themselves are cheap. They apply to the data that feeds AI systems as much as to reports. Run them on a training set, an evaluation set or the documents behind a retrieval system before an agent reads them.

🦆 My take:

Cheap queries invite more queries. If an agent can ask 40 questions for a few cents, it will, so put a budget on it the way you would on a job: a read-only role, a limit per workgroup and a log of what it asked. Check what the preview supports for limits before you rely on them.

What is still unknown about Athena powered by DuckDB

  • Status. It is a preview in five regions. AWS plans general availability for 2027. I would not run production jobs on it.
  • Pricing. Athena DuckDB pricing is published as a rate, but the pages I read do not say how many DPUs a query uses, so your cost per query is unknown until you test.
  • Benchmarks. The 2x and 50% figures are AWS’s, against Athena engine version 3. I could not find the benchmark details.
  • Agent numbers. My 40-query session is a local DuckDB run on synthetic data. It shows the shape of the bill, not Athena’s bill.
  • SQL coverage and writes. The overview page does not list unsupported features or write support. Read the SQL reference.
  • DuckDB Scales. AWS says Athena powered by DuckDB returns results on tens of terabytes in seconds. DuckDB.org says it is for workloads beyond 100 TB. Its internals are not documented yet, and the open-source release is planned for 2027.
  • EMR and Redshift. Planned, with no dates.
  • The download chart. In the keynote, AWS showed a chart in which DuckDB passed Spark in monthly PyPI downloads. DuckDB’s own August post reported more than 50 million monthly downloads. Downloads include CI traffic and measure installs, not production workloads.

Try it: the agent session, the validation script and the cost calculator

All three scripts are in the download bundle. agent_demo.py builds the synthetic orders table and runs the 40 queries; pass a smaller row count, such as 20000000, for a lighter run. The validation script builds the toy table, runs the seven checks and compares two outputs. The cost script prints the pricing arithmetic. Each block below is collapsed, so open the one you need.

agent_demo.py, part 1 of 3: build the synthetic orders table (two planted causes)
"""Forty exploratory queries an AI agent might run to answer
"why did revenue dip last week?", on synthetic orders data in Parquet.

Usage:  python3 agent_demo.py [rows]      (default 100,000,000 rows, about 2 GB on disk)
A smaller number such as 20000000 runs in about a minute on a laptop.
Everything is synthetic and seeded by a hash, so the result is repeatable.
"""
import duckdb, os, re, sys, json, time, glob, statistics

ROWS = int(sys.argv[1]) if len(sys.argv) > 1 else 100_000_000
DATA = f"agent_data_{ROWS}"
START = "2026-09-07"          # a Monday; 12 weeks of data end on Sunday 2026-11-29
SPAN_US = 84 * 86400 * 1_000_000

con = duckdb.connect()
con.execute("PRAGMA threads=2")

# ---------- 1) synthetic orders, with two planted effects ----------
if not glob.glob(f"{DATA}/orders_*.parquet"):
    os.makedirs(DATA, exist_ok=True)
    chunk = 25_000_000
    for n, lo in enumerate(range(0, ROWS, chunk)):
        hi = min(lo + chunk, ROWS)
        con.execute(f"""
        COPY (
          WITH b AS (
            SELECT range AS i,
                   TIMESTAMP '{START}' + to_microseconds(CAST(CAST(range AS HUGEINT) * {SPAN_US} // {ROWS} AS BIGINT)) AS ts,
                   hash(range) AS h1, hash(range + 1000003) AS h2, hash(range + 2000003) AS h3,
                   hash(range + 3000017) AS h4, hash(range + 4000037) AS h5, hash(range + 5000011) AS h6,
                   hash(range + 6000041) AS h7, hash(range + 7000003) AS h8, hash(range + 8000009) AS h9,
                   hash(range + 9000011) AS h10
            FROM range({lo}, {hi})
          ), c AS (
            SELECT i AS order_id, ts AS order_ts,
              CASE WHEN h1 % 100 < 30 THEN 'US' WHEN h1 % 100 < 45 THEN 'GB' WHEN h1 % 100 < 57 THEN 'DE'
                   WHEN h1 % 100 < 67 THEN 'FR' WHEN h1 % 100 < 77 THEN 'IN' WHEN h1 % 100 < 86 THEN 'BR'
                   WHEN h1 % 100 < 94 THEN 'JP' ELSE 'CA' END AS country,
              CASE WHEN h2 % 100 < 30 THEN 'organic' WHEN h2 % 100 < 55 THEN 'paid_search'
                   WHEN h2 % 100 < 70 THEN 'email' WHEN h2 % 100 < 82 THEN 'social'
                   WHEN h2 % 100 < 94 THEN 'direct' ELSE 'referral' END AS channel,
              CASE WHEN h3 % 100 < 50 THEN 'web' WHEN h3 % 100 < 80 THEN 'ios' ELSE 'android' END AS device,
              list_element(['books','toys','home','garden','beauty','sports','grocery','pets',
                            'office','music','auto','fashion'], 1 + CAST(h4 % 12 AS INTEGER)) AS category,
              1 + CAST(h5 % 50000 AS INTEGER) AS product_id,
              1 + CAST(h6 % 5000000 AS INTEGER) AS customer_id,
              CAST(round(5 + (h7 % 40000) / 100.0 * (1 + (h4 % 12) * 0.1), 2) AS DECIMAL(10,2)) AS amount,
              CAST(h8 % 30 AS TINYINT) AS discount_pct,
              (h9 % 100) < 4 AS is_refunded,
              h10 % 1000 AS keep_roll
            FROM b
          )
          SELECT * EXCLUDE (keep_roll) FROM c
          WHERE
            -- weekends are quieter than weekdays
            keep_roll < CASE dayofweek(order_ts) WHEN 6 THEN 850 WHEN 0 THEN 800 ELSE 1000 END
            -- email volume is normal except during one campaign week (16-22 Nov)
            AND NOT (channel = 'email' AND order_ts NOT BETWEEN TIMESTAMP '2026-11-16' AND TIMESTAMP '2026-11-22 23:59:59'
                     AND keep_roll % 10 >= 7)
            -- planted cause: from Wednesday 25 Nov, 75% of German paid-search orders vanish
            AND NOT (country = 'DE' AND channel = 'paid_search' AND order_ts >= TIMESTAMP '2026-11-25'
                     AND keep_roll % 4 != 0)
        ) TO '{DATA}/orders_{n}.parquet'
        (FORMAT parquet, ROW_GROUP_SIZE 1000000, COMPRESSION zstd)
        """)

con.execute(f"CREATE VIEW o AS SELECT * FROM read_parquet('{DATA}/orders_*.parquet')")
size_bytes = sum(os.path.getsize(f) for f in glob.glob(f"{DATA}/orders_*.parquet"))
n_rows = con.execute("SELECT count(*) FROM o").fetchone()[0]
col_bytes = dict(con.execute(f"""SELECT path_in_schema, sum(total_compressed_size)
    FROM parquet_metadata('{DATA}/orders_*.parquet') GROUP BY 1""").fetchall())
agent_demo.py, part 2 of 3: the forty queries an agent might run
# ---------- 2) the forty queries ----------
W11 = "order_ts >= TIMESTAMP '2026-11-16' AND order_ts < TIMESTAMP '2026-11-23'"
W12 = "order_ts >= TIMESTAMP '2026-11-23' AND order_ts < TIMESTAMP '2026-11-30'"
LAST2 = "order_ts >= TIMESTAMP '2026-11-16'"

def compare(dim, extra="", limit=5):
    return (f"SELECT {dim}, sum(amount) FILTER (WHERE {W11}) AS w11, sum(amount) FILTER (WHERE {W12}) AS w12, "
            f"w12 - w11 AS change FROM o WHERE {LAST2} {extra} GROUP BY ALL ORDER BY change LIMIT {limit}")

DE_PS = "country = 'DE' AND channel = 'paid_search'"
Q = [
 # confirm the dip
 ("confirm", "weekly revenue, 12 weeks", "SELECT date_trunc('week', order_ts) w, sum(amount) FROM o GROUP BY 1 ORDER BY 1"),
 ("confirm", "daily revenue, last 21 days", "SELECT order_ts::DATE d, sum(amount) FROM o WHERE order_ts >= TIMESTAMP '2026-11-09' GROUP BY 1 ORDER BY 1"),
 ("confirm", "orders and average order value by week", "SELECT date_trunc('week', order_ts) w, count(*), avg(amount) FROM o GROUP BY 1 ORDER BY 1"),
 ("confirm", "revenue after refunds by week", "SELECT date_trunc('week', order_ts) w, sum(amount) FILTER (WHERE NOT is_refunded) FROM o GROUP BY 1 ORDER BY 1"),
 ("confirm", "orders per day, last two weeks", f"SELECT order_ts::DATE d, count(*) FROM o WHERE {LAST2} GROUP BY 1 ORDER BY 1"),
 ("confirm", "revenue by weekday, last two weeks", f"SELECT dayname(order_ts) dn, sum(amount) FILTER (WHERE {W11}) w11, sum(amount) FILTER (WHERE {W12}) w12 FROM o WHERE {LAST2} GROUP BY 1"),
 # slice by one dimension at a time
 ("slice", "change by country", compare("country")),
 ("slice", "change by channel", compare("channel")),
 ("slice", "change by device", compare("device")),
 ("slice", "change by category", compare("category")),
 ("slice", "change by discount band", compare("discount_pct // 10 AS band")),
 ("slice", "change by order size band", compare("CAST(amount // 50 AS INTEGER) AS band")),
 ("slice", "change by country and channel", compare("country, channel", limit=8)),
 ("slice", "change by country and device", compare("country, device", limit=8)),
 ("slice", "change by channel and device", compare("channel, device", limit=8)),
 ("slice", "change by category and country", compare("category, country", limit=8)),
 # drill into the suspect
 ("drill", "German revenue by day", f"SELECT order_ts::DATE d, sum(amount) FROM o WHERE country = 'DE' AND {LAST2} GROUP BY 1 ORDER BY 1"),
 ("drill", "German revenue by channel and day", f"SELECT order_ts::DATE d, channel, sum(amount) FROM o WHERE country = 'DE' AND {LAST2} GROUP BY ALL ORDER BY 1, 2"),
 ("drill", "German paid-search orders by day", f"SELECT order_ts::DATE d, count(*) FROM o WHERE {DE_PS} AND {LAST2} GROUP BY 1 ORDER BY 1"),
 ("drill", "German paid-search orders by hour, 24-26 Nov", f"SELECT date_trunc('hour', order_ts) h, count(*) FROM o WHERE {DE_PS} AND order_ts >= TIMESTAMP '2026-11-24' AND order_ts < TIMESTAMP '2026-11-26' GROUP BY 1 ORDER BY 1"),
 ("drill", "German paid search by device", f"SELECT device, count(*) FILTER (WHERE {W11}) w11, count(*) FILTER (WHERE {W12}) w12 FROM o WHERE {DE_PS} AND {LAST2} GROUP BY 1"),
 ("drill", "German paid search by category", f"SELECT category, count(*) FILTER (WHERE {W11}) w11, count(*) FILTER (WHERE {W12}) w12 FROM o WHERE {DE_PS} AND {LAST2} GROUP BY 1 ORDER BY 1"),
 ("drill", "German paid-search average order value by day", f"SELECT order_ts::DATE d, avg(amount) FROM o WHERE {DE_PS} AND {LAST2} GROUP BY 1 ORDER BY 1"),
 ("drill", "paid-search orders by country and day", f"SELECT order_ts::DATE d, country, count(*) FROM o WHERE channel = 'paid_search' AND order_ts >= TIMESTAMP '2026-11-21' GROUP BY ALL ORDER BY 1, 2"),
 ("drill", "other German channels by day", f"SELECT order_ts::DATE d, channel, count(*) FROM o WHERE country = 'DE' AND channel != 'paid_search' AND order_ts >= TIMESTAMP '2026-11-21' GROUP BY ALL ORDER BY 1, 2"),
 # rule out the alternatives
 ("rule out", "refund rate by week", "SELECT date_trunc('week', order_ts) w, avg(is_refunded::INT) FROM o GROUP BY 1 ORDER BY 1"),
 ("rule out", "average discount by week", "SELECT date_trunc('week', order_ts) w, avg(discount_pct) FROM o GROUP BY 1 ORDER BY 1"),
 ("rule out", "distinct customers by week", "SELECT date_trunc('week', order_ts) w, count(DISTINCT customer_id) FROM o GROUP BY 1 ORDER BY 1"),
 ("rule out", "email revenue by week (campaign check)", "SELECT date_trunc('week', order_ts) w, sum(amount) FROM o WHERE channel = 'email' GROUP BY 1 ORDER BY 1"),
 ("rule out", "top products, change between the two weeks", f"SELECT product_id, count(*) FILTER (WHERE {W11}) w11, count(*) FILTER (WHERE {W12}) w12, w12 - w11 AS change FROM o WHERE {LAST2} GROUP BY 1 ORDER BY change LIMIT 10"),
 ("rule out", "largest orders, last two weeks", f"SELECT order_id, amount, country, channel FROM o WHERE {LAST2} ORDER BY amount DESC LIMIT 20"),
 ("rule out", "duplicate order ids, last two weeks", f"SELECT count(*) - count(DISTINCT order_id) FROM o WHERE {LAST2}"),
 ("rule out", "null or non-positive amounts", "SELECT count(*) FROM o WHERE amount IS NULL OR amount <= 0"),
 ("rule out", "repeat-customer share by week", "SELECT date_trunc('week', order_ts) w, 1 - count(DISTINCT customer_id) * 1.0 / count(*) FROM o GROUP BY 1 ORDER BY 1"),
 # size the cause
 ("size it", "biggest negative contributors, country and channel", compare("country, channel", limit=3)),
 ("size it", "German paid search, Wed-Sun, against the previous four weeks", f"SELECT sum(amount) FILTER (WHERE order_ts >= TIMESTAMP '2026-11-25' AND order_ts < TIMESTAMP '2026-11-30') AS wk12_wed_sun, sum(amount) FILTER (WHERE order_ts < TIMESTAMP '2026-11-23' AND order_ts >= TIMESTAMP '2026-10-26' AND dayofweek(order_ts) IN (3,4,5,6,0)) / 4 AS usual_wed_sun FROM o WHERE {DE_PS}"),
 ("size it", "total change with German paid search excluded", f"SELECT sum(amount) FILTER (WHERE {W11}) w11, sum(amount) FILTER (WHERE {W12}) w12 FROM o WHERE NOT ({DE_PS})"),
 ("size it", "total change including German paid search", f"SELECT sum(amount) FILTER (WHERE {W11}) w11, sum(amount) FILTER (WHERE {W12}) w12 FROM o"),
 ("size it", "German paid search revenue by week", f"SELECT date_trunc('week', order_ts) w, sum(amount) FROM o WHERE {DE_PS} GROUP BY 1 ORDER BY 1"),
 ("size it", "last check: German paid search share of revenue, by day", f"SELECT order_ts::DATE d, sum(amount) FILTER (WHERE {DE_PS}) / sum(amount) FROM o WHERE {LAST2} GROUP BY 1 ORDER BY 1"),
]
assert len(Q) == 40, len(Q)
agent_demo.py, part 3 of 3: run, time and price the session
# ---------- 3) run them, time them, estimate what Athena v3 would bill ----------
COLS = list(col_bytes)
rows = []
for phase, what, sql in Q:
    used = [c for c in COLS if re.search(rf"\b{c}\b", sql)]
    t = time.perf_counter()
    res = con.execute(sql).fetchall()
    secs = time.perf_counter() - t
    est_scan = sum(col_bytes[c] for c in used)       # upper bound: columns read, no row-group skipping
    rows.append(dict(phase=phase, what=what, secs=secs, scan_bytes=est_scan, cols=used, nrows=len(res)))
    if what == "change by channel":
        by_channel = res
    if what.startswith("biggest negative"):
        top = res
    if what.startswith("German paid search, Wed-Sun"):
        sized = res[0]
    if what.startswith("total change with German"):
        ex = res[0]
    if what.startswith("total change including"):
        inc = res[0]

# ---------- 4) checks: the planted cause must be what the agent finds ----------
assert top[0][0] == "DE" and top[0][1] == "paid_search", top
assert top[0][4] < 0
assert float(sized[0]) < 0.55 * float(sized[1]), sized          # roughly a 70%+ shortfall against the usual Wed-Sun
assert float(ex[1]) > 0.9 * float(ex[0]), ex                    # without it, revenue is within about 10% of the week before
drop = float(inc[1] - inc[0]) / float(inc[0])
total_change = float(inc[1] - inc[0])
email_share = float(by_channel[0][3]) / total_change          # the campaign week ending
de_share = float(top[0][4]) / total_change                    # the planted fault
assert by_channel[0][0] == "email" and 0.70 < email_share < 0.80, by_channel[0]
assert 0.20 < de_share < 0.30, de_share
email_pct = float(by_channel[0][2] / by_channel[0][1] - 1) * 100
de_pct = float(top[0][3] / top[0][2] - 1) * 100

# ---------- 5) cost arithmetic ----------
V3_PER_TB, DUCK_PER_DPU_HR = 5.00, 0.35
def v3_cost(b): return max(b, 10_000_000) / 1e12 * V3_PER_TB            # 10 MB minimum per query
def duck_cost(secs, dpus): return max(secs, 0.1) * dpus * DUCK_PER_DPU_HR / 3600   # 100 ms minimum

tot_secs = sum(r["secs"] for r in rows)
tot_scan = sum(r["scan_bytes"] for r in rows)
v3_total = sum(v3_cost(r["scan_bytes"]) for r in rows)
summary = dict(
    rows=n_rows, size_gb=size_bytes / 1e9, total_secs=tot_secs,
    median_secs=statistics.median(r["secs"] for r in rows), max_secs=max(r["secs"] for r in rows),
    avg_scan_gb=tot_scan / 40 / 1e9, total_scan_gb=tot_scan / 1e9, v3_total=v3_total,
    duck={d: sum(duck_cost(r["secs"], d) for r in rows) for d in (1, 2, 4, 8)},
    revenue_drop_pct=drop * 100, email_share=email_share * 100, de_share=de_share * 100,
    email_pct=email_pct, de_pct=de_pct,
    breakeven_dpu_secs_per_query=v3_total / 40 / (DUCK_PER_DPU_HR / 3600),
    queries=rows,
)
json.dump(summary, open(f"agent_results_{ROWS}.json", "w"), indent=1)
print(f"{n_rows:,} rows, {size_bytes/1e9:.2f} GB Parquet; revenue change week 12 vs 11: {drop*100:.1f}%")
print(f"40 queries: {tot_secs:.1f} s total, median {summary['median_secs']:.2f} s, slowest {summary['max_secs']:.2f} s")
print(f"estimated bytes read (columns only): {tot_scan/1e9:.1f} GB total, {tot_scan/40/1e9:.2f} GB per query")
print(f"Athena v3 on-demand estimate: ${v3_total:.3f} for the session")
for d, c in summary["duck"].items():
    print(f"DuckDB engine if {d} DPU(s) ran at this speed: ${c:.3f}")
print(f"largest single segment: {top[0][:2]} ({de_share*100:.0f}% of the change, {de_pct:.0f}% week on week)")
print(f"email, campaign week ending: {email_share*100:.0f}% of the change ({email_pct:.0f}% week on week)")
validation_demo.py, part 1 of 3: build the toy orders table
"""Tiny data-validation demo with DuckDB (tested with DuckDB 2.0.1).

It builds a synthetic `orders` table with known defects, writes it to Parquet,
then runs validation rules as plain SQL and compares two outputs with EXCEPT.
The defects are injected with modulo rules, so every expected count is exact.
Timings are for the machine you run it on. This is a correctness demo, not a benchmark.
"""
import os
import tempfile
import time

import duckdb

N = 2_000_000
tmp = tempfile.mkdtemp()
orders_pq = os.path.join(tmp, "orders.parquet")
customers_pq = os.path.join(tmp, "customers.parquet")
legacy_pq = os.path.join(tmp, "daily_revenue_legacy.parquet")
new_pq = os.path.join(tmp, "daily_revenue_new.parquet")

con = duckdb.connect()                      # in-process: no cluster, no server
con.execute("SET threads = 4")

# 1) customers: ids 1..200000
con.execute(f"""
COPY (SELECT i AS customer_id, 'cust_' || i AS name
      FROM range(1, 200001) t(i)) TO '{customers_pq}' (FORMAT parquet)
""")

# 2) orders with injected defects (rules are modulo-based, so counts are exact)
con.execute(f"""
COPY (
  WITH base AS (
    SELECT
      i AS order_id,
      CASE WHEN i % 4000 = 1 THEN NULL
           WHEN i % 8000 = 4 THEN 999999999
           ELSE 1 + (i * 7919) % 200000 END                            AS customer_id,
      CASE WHEN i % 5000 = 2 THEN -5.0
           ELSE round(5 + ((i * 31) % 9500) / 100.0, 2) END            AS amount,
      CASE WHEN i % 10000 = 3 THEN 'unknown'
           WHEN i % 3 = 0 THEN 'paid' WHEN i % 3 = 1 THEN 'shipped'
           ELSE 'refunded' END                                         AS status,
      CASE WHEN i % 20000 = 5 THEN TIMESTAMP '2099-01-01 00:00:00'
           ELSE TIMESTAMP '2026-11-30 00:00:00' + to_seconds(i % 86400) END AS order_ts
    FROM range(1, {N + 1}) t(i)
  )
  SELECT * FROM base
  UNION ALL
  SELECT * FROM base WHERE order_id % 2000 = 6          -- 1,000 duplicated order_ids
) TO '{orders_pq}' (FORMAT parquet)
""")
validation_demo.py, part 2 of 3: seven checks as plain SQL
rules = {
    "row_count_in_expected_range":
        f"SELECT CASE WHEN count(*) BETWEEN 1900000 AND 2100000 THEN 0 ELSE 1 END FROM read_parquet('{orders_pq}')",
    "order_id_is_unique":
        f"SELECT count(*) - count(DISTINCT order_id) FROM read_parquet('{orders_pq}')",
    "customer_id_not_null":
        f"SELECT count(*) FROM read_parquet('{orders_pq}') WHERE customer_id IS NULL",
    "amount_is_positive":
        f"SELECT count(*) FROM read_parquet('{orders_pq}') WHERE amount <= 0",
    "status_in_allowed_set":
        f"SELECT count(*) FROM read_parquet('{orders_pq}') WHERE status NOT IN ('paid','shipped','refunded')",
    "order_ts_not_in_future":
        f"SELECT count(*) FROM read_parquet('{orders_pq}') WHERE order_ts > TIMESTAMP '2026-12-01 00:00:00'",
    "customer_exists (referential)":
        f"""SELECT count(*) FROM read_parquet('{orders_pq}') o
            WHERE o.customer_id IS NOT NULL
              AND NOT EXISTS (SELECT 1 FROM read_parquet('{customers_pq}') c WHERE c.customer_id = o.customer_id)""",
}

expected = {            # exact, from the modulo rules above
    "row_count_in_expected_range": 0,
    "order_id_is_unique": 1000,
    "customer_id_not_null": 500 + 0,        # 500 NULLs (plus 1,000 dup rows hit none of them)
    "amount_is_positive": 400 + 0,
    "status_in_allowed_set": 200,
    "order_ts_not_in_future": 100,
    "customer_exists (referential)": 250,
}

print(f"{'rule':<34}{'failed rows':>12}{'expected':>10}{'seconds':>9}")
t_all = time.perf_counter()
for name, sql in rules.items():
    t0 = time.perf_counter()
    failed = con.execute(sql).fetchone()[0]
    dt = time.perf_counter() - t0
    print(f"{name:<34}{failed:>12,}{expected[name]:>10,}{dt:>9.3f}")
    # duplicates also repeat any defective row whose order_id % 2000 == 6 (none of the other rules use 6)
    assert failed == expected[name], (name, failed, expected[name])
print(f"all 7 rules: {time.perf_counter() - t_all:.2f}s on this machine\n")
validation_demo.py, part 3 of 3: compare two outputs with EXCEPT
# 3) compare a legacy output with a migrated output (the check I run before trusting a migration)
agg = f"""
SELECT date_trunc('hour', order_ts) AS hr, status, count(*) AS orders, round(sum(amount), 2) AS revenue
FROM (SELECT DISTINCT * FROM read_parquet('{orders_pq}'))
WHERE amount > 0 AND order_ts < TIMESTAMP '2026-12-01' AND customer_id IS NOT NULL
GROUP BY ALL
"""
con.execute(f"COPY ({agg}) TO '{legacy_pq}' (FORMAT parquet)")
# the 'migrated' job: same logic, but one bug (rounds revenue per row before summing)
buggy = agg.replace("round(sum(amount), 2)", "sum(round(amount, 0))")
con.execute(f"COPY ({buggy}) TO '{new_pq}' (FORMAT parquet)")

only_legacy = con.execute(
    f"SELECT count(*) FROM (SELECT * FROM read_parquet('{legacy_pq}') EXCEPT SELECT * FROM read_parquet('{new_pq}'))"
).fetchone()[0]
only_new = con.execute(
    f"SELECT count(*) FROM (SELECT * FROM read_parquet('{new_pq}') EXCEPT SELECT * FROM read_parquet('{legacy_pq}'))"
).fetchone()[0]
rows = con.execute(f"SELECT count(*) FROM read_parquet('{legacy_pq}')").fetchone()[0]
print(f"legacy rows: {rows:,} | rows only in legacy: {only_legacy:,} | rows only in new: {only_new:,}")
assert only_legacy > 0 and only_new > 0, "the seeded bug should be caught"
same = con.execute(
    f"SELECT count(*) FROM (SELECT * FROM read_parquet('{legacy_pq}') EXCEPT SELECT * FROM read_parquet('{legacy_pq}'))"
).fetchone()[0]
assert same == 0
print("seeded rounding bug caught; identical files compare clean")
cost_calc.py: the pricing arithmetic from this post
"""Cost arithmetic for the post. Prices are the ones quoted in the post (see the notes).

Athena engine v3:      $5 per TB scanned (10 MB minimum per query)        -- AWS Athena pricing page, Dec 2026
Athena DuckDB engine:  $0.35 per DPU-hour, billed per millisecond,
                       100 ms minimum (preview)                           -- same page
Glue 6.0:              $0.308 per DPU-hour                                -- AWS price list read 22 Oct 2026
Fargate:               $0.04048 per vCPU-hour, $0.004445 per GB-hour      -- AWS price list read 22 Oct 2026

How many DPUs the DuckDB engine uses for a given query is not published, so every
DPU count and duration below is an assumption you should replace with your own query history.
"""
TB = 1e12                      # decimal TB, close enough for this arithmetic
V3_PER_TB = 5.00
DUCK_PER_DPU_HR = 0.35
DUCK_PER_DPU_SEC = DUCK_PER_DPU_HR / 3600


def v3_cost(gb_scanned):
    return max(gb_scanned * 1e9 / TB * V3_PER_TB, 10e6 / TB * V3_PER_TB)


def duck_cost(dpus, seconds):
    return dpus * max(seconds, 0.1) * DUCK_PER_DPU_SEC


def break_even_dpu_seconds(gb_scanned):
    """DPU-seconds the DuckDB engine can use before it costs more than engine v3 for the same scan."""
    return v3_cost(gb_scanned) / DUCK_PER_DPU_SEC


print("1) The pricing page's own example: 4 DPUs for 2 s")
print(f"   = ${duck_cost(4, 2):.7f} per query\n")        # page says about $0.0007778

print("2) Break-even DPU-seconds vs engine v3 (same bytes scanned)")
for gb in (1, 10, 20, 100, 500):
    be = break_even_dpu_seconds(gb)
    print(f"   scan {gb:>4} GB: v3 = ${v3_cost(gb):.4f}   DuckDB engine is cheaper below {be:,.0f} DPU-seconds"
          f"  (e.g. 8 DPUs for {be / 8:,.0f} s)")
print()

print("3) A scan-heavy day: 40 exploratory queries by an agent, each scanning 2 GB (assumed)")
n, gb = 40, 2
print(f"   engine v3:  {n} x ${v3_cost(gb):.4f} = ${n * v3_cost(gb):.3f}")
for dpus, secs in ((4, 2), (4, 5), (8, 10)):
    print(f"   DuckDB engine at {dpus} DPUs x {secs:>2} s per query: {n} x ${duck_cost(dpus, secs):.5f} = ${n * duck_cost(dpus, secs):.4f}")
print()

print("4) The toy nightly job from my earlier post (list prices read 22 Oct 2026; durations are assumptions)")
glue_default = 10 * 0.308 * 0.5
glue_right = 2 * 0.308 * (12 / 60)
fargate = (4 * 0.04048 + 16 * 0.004445) * (5 / 60)
print(f"   Glue default 10 DPU x 30 min : ${glue_default:.2f} per run")
print(f"   Glue right-sized 2 DPU x 12 m: ${glue_right:.2f} per run")
print(f"   DuckDB on Fargate 4 vCPU/16 GB x 5 min: ${fargate:.3f} per run")
print(f"   at 20 runs/day: ${glue_default*20*365:,.0f} / ${glue_right*20*365:,.0f} / ${fargate*20*365:,.0f} per year")

Summary: what I would do this week

Athena powered by DuckDB is a preview, and I would treat it that way. The pricing model is the real change: you pay for compute time, not bytes scanned, which suits the many-small-queries pattern that agents create, and is why AI agent queries could cost less on it. In my local test, a 40-query session ran in under 50 seconds on two vCPUs, and the headroom against the per-scan estimate was between 3x and 24x depending on the DPUs you assume. For jobs that fit on one machine, you can replace Spark with DuckDB today. The piece to watch in 2027 is DuckDB Scales, because it decides how far that ceiling moves.

  • Write down 40 queries an agent or an analyst would run for one real question.
  • Run them on your laptop with DuckDB 2.0.1 and note the time for each.
  • If you are in a preview region, run the same SQL in a test Athena workgroup on the DuckDB engine and compare cost and time per query.
  • Compare the outputs of old and new jobs with EXCEPT in both directions before you switch anything.

Which of the questions your team asks every week would you let an agent ask 40 times? I would like to hear what you find in the comments.


Frequently asked questions

What is Amazon Athena powered by DuckDB?

It is a preview version of Amazon Athena that runs SQL on DuckDB, the open-source analytical database, instead of Athena engine version 3. AWS announced it on 1 December 2026. It runs in five preview regions and queries Apache Iceberg v3 and Parquet tables through the Glue Data Catalog.

Why do AI agents run so many queries?

An agent explores data by trying a hypothesis, reading the result and trying the next one, so a single business question can turn into dozens of small queries. AWS says agents run many small queries in parallel and expect fast answers. In my test session for one revenue question, the 40 queries split into confirming the dip, slicing it, drilling into a suspect, ruling out alternatives and sizing the cause.

Could AI agent queries cost less on Athena powered by DuckDB?

They could. Engine version 3 bills by data scanned, at $5 per TB. The DuckDB engine bills $0.35 per DPU-hour per millisecond with a 100 ms minimum, which favours many short queries. In my local test of 40 queries, which is not an Athena benchmark, the estimated engine version 3 bill was $0.114, against $0.005 to $0.038 for the DuckDB engine at 1 to 8 assumed DPUs. AWS has not published how many DPUs a query uses, so test your own queries.

How much does Athena powered by DuckDB cost?

The pricing page lists $0.35 per DPU-hour for the DuckDB engine in preview, billed per millisecond with a 100 ms minimum. On-demand engine version 3 costs $5 per TB scanned. The page's example, a 4-DPU query running 2 seconds, costs about $0.0007778. AWS has not published how many DPUs a given query uses.

Is Athena powered by DuckDB generally available?

No. It is in preview, and AWS and DuckDB.org both say general availability is planned for 2027. Treat it as something to test, not something to put production jobs on.

Can DuckDB replace Spark?

For SQL-shaped batch jobs that fit on one machine or one managed query, often yes, and usually at lower cost. It does not replace streaming, shuffles larger than memory, UDF-heavy code or platforms built around Spark governance. Measure your working set and compare outputs before you move a job.

Is DuckDB faster than Spark?

In two independent single-machine tests, DuckDB was 3.4x and 4.1x faster. In a 100 GB test it won most queries and ran out of memory on one. AWS's 2x figure for Athena compares the new engine with Athena engine version 3, not with Spark.

What is DuckDB Scales?

It is a DuckDB extension that spreads one query across many machines. It is initially available in Athena. AWS says it returns results in seconds on tens of terabytes, and DuckDB.org says it targets workloads beyond 100 TB. An open-source release is planned for the first half of 2027.

Why does AWS say DuckDB suits AI agents?

AWS argues that agents run many small queries in parallel and expect fast answers, so per-query overhead adds up on a cluster. It also points to one SQL dialect and Arrow-based streaming. These are AWS's claims and I have not seen them measured independently.

Are cheap queries enough for agents to take over data work?

No. In my view cheap queries remove one bottleneck, not all of them. Agents also need context about what columns and metrics mean, guardrails such as read-only roles and budgets, deterministic checks on the data they read and the fixes they propose, and a way to evaluate whether their answers are right.

Does AWS own DuckDB now?

AWS agreed in August 2026 to acquire DuckLabs, the company that builds DuckDB. The open-source project stays under the MIT licence and under the independent DuckDB Foundation.

Can I run the same SQL on my laptop and on Athena?

That is the aim of the open-source DuckDB extension for Athena, which lets you build SQL in DuckDB locally and run it on Athena when the data grows. Check the SQL reference for differences before you rely on it.

When should I still use Spark?

Use Spark for streaming and long-running stateful jobs, shuffles whose state exceeds one machine, code that depends on user-defined functions, and platforms where governance and lineage are built around it. Also check that the target engine can write your table format.

Nikhil Aggarwal

Written by Nikhil Aggarwal

Nikhil Aggarwal is an ML engineer with 15+ years in data engineering, distributed systems and cloud. He builds ML and GenAI capabilities for enterprise data platforms, and writes DataForGeeks to explain complex topics through real production problems.

About me · LinkedIn · Newsletter