AWS Builder Center
Before You Put DuckDB in Front of Your Lake Formation Data, Read This

Before You Put DuckDB in Front of Your Lake Formation Data, Read This

I built a router that sent cheap queries to DuckDB instead of Athena, and I ended up deleting it.

AWS Community Builder | Cloud Native Fanatic
We run Athena over an Iceberg lake, and I had the same idea everyone has eventually. Most of what people type into a SQL workbench is small, an hour of events for one customer, or a count of errors since lunch. DuckDB reads Iceberg straight from S3, runs in-process, and doesn't bill per terabyte. So send the small queries to DuckDB and keep Athena for the big ones.
I built exactly that: a cost estimator, a routing check that defaulted to Athena whenever it was unsure, and DuckDB baked into the production container image. Then I scrapped it. In our lake, Lake Formation hides two sensitive columns from the application, but only when Athena runs the query. DuckDB needed a permission that goes right around that rule.
If you're thinking about doing the same thing, I want to save you the two weeks I spent finding that out.

The setup

Here's the setup, simplified. Application events stream through Amazon Data Firehose into Apache Iceberg tables on Amazon S3 Tables, partitioned by the hour of an event timestamp. Some of those events carry free text that can contain customer data.
The sensitive data lives in one table,  events , in two columns:  request_body  and  response_body . Everything else in the lake is safe for internal tooling to read.
An internal query service lets engineers run ad hoc queries. It runs under a single service role, and Lake Formation decides what that role can see:
  • A SELECT-only grant on each table, with no row filters.
  • The  events  grant excludes  request_body  and  response_body . That exclusion is the only fine-grained rule in the lake.
  • The service role has no  s3:  or  s3tables:  read on the table data. It holds  lakeformation:GetDataAccess , so Athena can ask Lake Formation for scoped credentials on its behalf.
Before any SQL reaches Athena, a parser-based guard ( node-sql-parser , Athena dialect) rejects anything but  SELECT ,  WITH  and  EXPLAIN . That guard is defense in depth. Lake Formation is the real permission boundary.

Estimating cost before the query runs

Athena bills for bytes scanned, at  $5 per TB . A careless query over a wide time range gets expensive, and even a tiny one pays the full round trip.
To route on cost you need the cost before the query runs, so the first piece I built was an estimator. It works in four steps:
  1. Reuse the syntax tree the SQL guard already built. Don't parse twice.
  1. Pull every predicate on the partition column ( event_ts ) into a time interval, and map that interval onto hour partitions.
  1. Read partition sizes from Iceberg metadata, not from the data. Athena exposes this as a metadata table,  "db"."table$partitions" , with a  file_count  and  total_size  per partition.  $files  is the fallback. That read is an Athena query itself, so the estimate pays a round trip of its own. I accepted that because it ran once, when the query was planned.
  1. Sum the sizes of the partitions the query can touch.
The rule I cared about most: anything the estimator can't interpret makes the estimate bigger, never smaller. An  OR  it can't reduce, a function wrapped around the timestamp, a partition value it can't parse: each one widens the range. Every estimate also carries a confidence label.  measured  means the estimator read real metadata for every partition.  upper-bound  means it widened something.  unknown  means it found no metadata at all.
An estimate that comes in too low is the dangerous kind here, because the estimate is what picks the engine.
The money is smaller than you'd think. At $5 per TB, a query that scans 1 GB costs half a cent. Moving small queries off Athena saves something, but not much. The real draw is latency.

The catch: Lake Formation lives in the engine, not in S3

When Athena queries a table that Lake Formation governs, it doesn't read S3 with your role's credentials. It asks Lake Formation for temporary credentials scoped to your grants and applies the column restrictions itself. Your role only needs permission to ask ( lakeformation:GetDataAccess ). That's why the query service role in this setup can't read a byte of table data directly.
DuckDB plays no part in that exchange. Its Iceberg and S3 extensions read Parquet files with whatever AWS credentials the process has. For DuckDB to read the lake at all, the service role needs direct read on the table data. On S3 Tables, loading a table through the  Iceberg REST endpoint  takes  s3tables:GetTableMetadataLocation  and  s3tables:GetTableData , plus catalog reads like  s3tables:GetTableBucket  and  s3tables:GetNamespace . On a plain bucket it's  s3:GetObject .
Those permissions cover a whole table or object, never a column, and a Parquet file holds every column. A role that lets DuckDB read  events  can also read  request_body  and  response_body . Athena refuses  SELECT request_body FROM events . DuckDB returns real rows for it.
Two read paths to one events table: Athena reads with Lake Formation-vended credentials and filters

Any query you send to DuckDB runs with no column-level enforcement at all. So every time the router picks DuckDB, it's also deciding that the query can't see  request_body . That's an access decision, made by my code.

The router I built

The router asks "can I prove this query can't reach the excluded columns?" first and "is it cheap?" second. A query goes to DuckDB only if all six of these hold:
  1. The estimate is  measured . An  upper-bound  or  unknown  figure is no basis for a decision.
  1. The estimate is under the threshold. The threshold comes from config, with no default in code, because a default threshold would be a hidden policy decision.
  1. Every table is a known lake table. Anything else, Athena.
  1. No  *  appears anywhere. That includes  SELECT * ,  e.* , a star inside a CTE, and even  count(*) . I didn't try to decide which stars are safe.
  1. No excluded column name appears anywhere. I check twice: once by walking the syntax tree, and once by scanning the raw SQL text. Either match is enough to deny.
  1. Only syntax both engines share. The guard parses SQL in Athena's dialect, but DuckDB runs it, and DuckDB has its own ways to reach a column without typing its name:  COLUMNS('.*_body')  selects by regex, and  SELECT e FROM events e  returns the whole row as a struct. So every column reference has to resolve to a real column of a table on the list. A bare alias like  e  doesn't, so it goes to Athena. Table functions like  read_parquet('s3://...')  and  iceberg_scan(...)  skip the table list completely. Anything outside the shared dialect goes to Athena, and table functions are outside it.
Rule 5 is deliberately too broad. A query that mentions  request_body  in a comment or a string literal goes to Athena. I'm fine paying a few extra cents for false positives.
Everything in the module fails closed:
  • Every branch returns Athena except one. There's a single  return { engine: "duckdb" }  in the module, reached only after all six checks pass.
  • Missing config, an unfamiliar parser node, an estimator that gave up: all of them land on Athena.
  • The decision is made once, when the query is planned, and stored with the plan, keyed to a hash of the normalized SQL. At run time the stored decision is read back, so the engine that runs is the one chosen for exactly that text. A stale or edited plan runs on Athena.
I also shipped DuckDB in the production container, as a musl-native CLI on Alpine with its Iceberg and S3 extensions installed at build time. That way a task never needs outbound access to download extensions.

Why I never turned it on

The router itself worked. The problem was the permission it needed.
To route even one query, the service role needs  s3tables:GetTableData  on  events . That permission doesn't go to the router. It goes on the task's IAM role, and every process in the container can use it. From then on, every line of code in that process can read  request_body  and  response_body : the router, every other API route, every dependency, and anything an attacker gets to run there. The Lake Formation exclusion would still be in place, but only Athena would honor it. For everything else in the process, the only protection left would be our parser's analysis.
I wrote the router to keep that analysis small and strict. I wasn't willing to make it the only thing between the application and the most sensitive columns in the lake.
There was a second, plainer problem. DuckDB runs inside the process. One heavy scan in the API container can exhaust its memory or CPU and take down every route it serves.
So routing stayed behind a config flag that no deployed environment set. When I later removed the query service's separate planning step, the stored routing decision had nowhere to live, and the router went with it.
One caveat: the Athena  $partitions  reader was only tested against fakes. There's no local Athena, so it was written to fall back to the worst-case estimate on any surprise, not tuned against real responses.

If you still want to route queries

A column-level rule can only be enforced by the engine, so every safe design either moves the sensitive data out of DuckDB's reach or keeps Lake Formation involved in the credentials.
1. Move the sensitive columns into their own table. Split  events  into a safe table and an  event_bodies  table keyed by event ID. Now nothing in the safe table needs a column filter.
For S3 Tables, the way in is the  AWS Glue Iceberg REST endpoint . Turn on Lake Formation's  full table access  setting, and Glue will vend short-lived credentials to an external engine, but only for tables its role has full permissions on. That's exactly what the split buys you. DuckDB attaches to that endpoint with  ENDPOINT_TYPE glue , and its role needs Glue read actions plus  lakeformation:GetDataAccess , never raw  s3tables:  read. Test that DuckDB actually picks up the vended credentials before you build on it.
One catch: Lake Formation grants go to a role, not an engine. If DuckDB's role can read  event_bodies  through Athena, it can get credentials for that table too, so the bodies need a second role. You also pay for a second Firehose destination and a join whenever someone really needs the bodies. This is still the option I'd pick.
2. Register your service as a trusted third-party engine. Lake Formation can vend credentials to an engine that promises to enforce the filters itself. That puts your parser back in charge of the boundary, which is the design I already rejected.
3. Run DuckDB in its own worker. A separate task or function with its own role and its own memory limit fixes the blast-radius problem, and it pairs well with option 1. On its own it changes nothing about the permissions: the worker's role would still read whole tables.
4. Make Athena feel faster instead. If latency is what you're really after, look at Athena  query result reuse  for repeated queries and at compacting small Iceberg files, before adding a second engine.

Wrapping up

If you're about to put a second engine in front of a Lake Formation-governed lake, write down which engine enforces which permission before you write any routing code. Mine would have been two lines: Athena enforces the column rule, DuckDB enforces nothing. I wrote it as a long comment at the top of the routing module after the router was done, and most of this post came from it.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article