AWS Builder Center
DuckDB on AWS Lambda: Building a Serverless Analytical API

DuckDB on AWS Lambda: Building a Serverless Analytical API

Explore how to build lightweight serverless analytical APIs using DuckDB, AWS Lambda, and Amazon S3. Discover the architecture, real-world performance measurements, trade-offs, and limitations to help determine when an embedded analytical engine is the right choice.

Data Engineer
You have Parquet data in S3. An application needs a filtered aggregate from it, over HTTP, synchronously. Which engine do you put behind that endpoint?

The reflex is to reach for something familiar: Athena, a Glue job, a warehouse. For a bounded dataset and a simple query, each of those adds a service, a latency profile, or a standing cost you may not need. The alternative I explore here is smaller: run DuckDB, an embedded analytical SQL engine, inside the Lambda invocation and let it read the Parquet files directly.

My thesis is not that DuckDB replaces Spark or Athena. It is that picking the smallest appropriate compute engine is a judgment call, and that you can make it with evidence instead of instinct. This article shows the pattern, the place where it stops fitting, and the questions I use to decide.

One piece of context: on August 26, 2026, Amazon announced a definitive agreement to acquire DuckLabs, the company behind DuckDB. The open-source project remains under the independent DuckDB Foundation and stays MIT-licensed. Nothing in this article depends on that news.


The Architecture


  • API Gateway HTTP API exposes one route,  GET /sales/summary , and proxies it to Lambda.
  • Lambda runs a container image built on  public.ecr.aws/lambda/python:3.11 , with DuckDB installed as a Python dependency.
  • DuckDB runs in-process inside the invocation, as an embedded engine rather than a separate service.
  • S3 holds the source data as Parquet under a  raw/sales/  prefix.

For  GET /sales/summary?country=CA&year=2023 : API Gateway matches the route, Lambda parses and validates the parameters, a fresh DuckDB connection is created, DuckDB reads the Parquet files and aggregates, and Lambda returns the result as JSON. Each invocation is stateless: nothing is pooled or cached between requests.

Why DuckDB?

DuckDB is an embedded, in-process analytical engine, closer to SQLite in deployment model than to PostgreSQL. Three properties matter here:
  • No server to provision. The engine shares the lifecycle of the Lambda invocation.
  • Columnar, vectorized execution suited to filters and aggregations.
  • Native Parquet support, including reading directly from S3.
That is the whole argument for the engine. The rest of the article is about whether the workload fits it.

The Implementation

The core is one parameterized query:
SELECT
COUNT(DISTINCT order_id) AS total_orders,
SUM(quantity) AS units_sold,
SUM(quantity * unit_price) AS revenue
FROM read_parquet('s3://{bucket}/{prefix}/*.parquet')
WHERE country = ?
AND EXTRACT(year FROM order_date) = ?
 read_parquet()  accepts S3 paths and globs through DuckDB's  httpfs extension. The filter values are bound as parameters, never interpolated. The bucket and prefix come from environment variables set by Terraform, and the handler validates inputs before any SQL runs:  year must be an integer in a sane range, country a 2–3 letter code.
DuckDB can apply column projection and predicate pushdown on Parquet, reading only the referenced columns and skipping row groups whose statistics rule out a match. Whether that reduces what is actually read from S3 depends on file layout: row group size, sort order, filter selectivity. Treat it as an optimization the engine may exploit, not a guarantee.
The connection setup is where Lambda-specific details live:
import re
import duckdb

def configure_duckdb_s3(conn, region_name: str) -> None:
# Allowlist-style check: CREATE SECRET is DDL, so I validate
# the region instead of relying on parameter binding.
if re.fullmatch(r"[a-z]{2}(-gov)?-[a-z]+-\d", region_name) is None:
raise ValueError("AWS_REGION is invalid")

# Lambda's filesystem is read-only except /tmp
conn.execute("SET home_directory = '/tmp'")
conn.execute("SET secret_directory = '/tmp'")
conn.execute("SET extension_directory = '/tmp'")

conn.execute(
"CREATE SECRET lambda_s3 "
f"(TYPE s3, PROVIDER credential_chain, REGION '{region_name}')"
)

conn = duckdb.connect(database=":memory:")
configure_duckdb_s3(conn, os.environ["AWS_REGION"])
rows = conn.execute(query, params).fetchall()
Two details are easy to miss. First, Lambda's filesystem is read-only except tmp, and DuckDB wants a writable home directory for extensions and secrets, so those three  SET statements must run before  CREATE SECRET . Second,  PROVIDER credential_chain makes DuckDB resolve credentials through the AWS SDK credential chain, which in Lambda means the function's execution role. No access keys live in code or environment variables. The  :memory: database name only means no database file is persisted. It says nothing about how large a workload the function can handle; that depends on the constraints covered below.

What I Measured

The measurements below are from a deployed stack, not a local simulation. The dataset is deliberately small, a single 22.1 KiB Parquet file in S3, because the goal is to characterize the wrapper, not the engine. Query-side performance was measured separately, locally, against larger files.
Measurement
Value
Dataset size and file count
22.1 KiB, 1 Parquet file ( raw/sales/sample.parquet )
Lambda memory configuration
2048 MB
Warm handler duration
390–430 ms (CloudWatch  REPORT )
Warm end-to-end latency (25 requests)
p50 ≈ 594 ms, steady state 490–690 ms
Cold-start Init Duration
484 ms (first deploy), 238 ms (subsequent recycle)
First-invocation handler overhead
~12.77 s (first deploy), ~1.8 s (subsequent recycle)
Local query time (DuckDB, 140 MB)
85 ms
Local query time (DuckDB, 700 MB)
493 ms
Local connection setup (connect + SET + CREATE SECRET)
~7 ms
Three things stand out.
First, the query engine was not the bottleneck. A 140 MB Parquet file queried locally in 85 ms produces the same SQL result that takes 390–430 ms in the Lambda handler for a 22 KiB file. The engine was not the slow part in these runs; the serverless wrapper and the S3 access path dominate.
Second, Init Duration is not the expensive part of a cold start. Lambda reports 484 ms of container initialization on a fresh deploy. But the same invocation took 13.25 s end-to-end, and the CloudWatch log stream localizes the remaining ~12.77 s to a gap between request.params and query.start. The handler was running, but the DuckDB connection was not yet ready for the query. On a subsequent container recycle, the same stall appeared at ~1.8 s. It does not reproduce locally: a fresh duckdb.connect() plus  SET home_directory plus  CREATE SECRET ... PROVIDER credential_chain completes in about 7 ms on a developer machine.
Third, warm latency is not uniform. Across 25 sequential warm requests, the median was 594 ms and the steady state fell in a 490–690 ms band. But one request returned in 2.80 s and another in 2.89 s. The first coincides with a CloudWatch  REPORT line showing  Init Duration: 237.97 ms , so it was a cold start that occurred mid-run: a container was recycled even under sustained sequential traffic. The second outlier has no matching  INIT_REPORT and remains unexplained.
What this means for the pattern: the cold-start penalty people worry about in Lambda is real, but in this run it was not dominated by Lambda's  Init Duration . It was dominated by first-use setup inside the handler, most likely the AWS credential resolution DuckDB performs on a fresh container through  credential_chain , though the sub-cause was not isolated. For a synchronous API, that is the number that matters: not 484 ms, but 1.8–12.8 s on the first request after a fresh deploy or recycle. If that cost is unacceptable, the usual mitigations are provisioned concurrency, a post-deploy warm-up invocation, or reusing the DuckDB connection and secret across invocations where the runtime permits it. I did not test any of these.
What was not measured: S3 requests per query (bucket access logging was not enabled), cold-start latency on the larger local benchmark dataset (which was never uploaded to S3), the specific sub-cause of the ~12.8 s stall inside the connection setup path, and the point at which the function runs out of memory. The local and Lambda runs also differ in hardware and storage path, so the comparison between them is indicative, not controlled. These are the measurements a reader should take first on their own workload, because they define where the pattern's boundary actually lies. The Decision Boundary: When This Fits and When It Doesn't
The comparison is about architectural fit, not speed or price.

DuckDB on Lambda
Athena
Glue / Spark
Redshift
Typical consumer
An application over HTTP
Analysts, BI, ad-hoc SQL
Pipelines and ETL jobs
BI users and applications on a warehouse
Execution model
One invocation, one node
Managed serverless query service
Distributed jobs
Persistent warehouse
Data scope
Bounded set of Parquet files
Data-lake exploration
Large-scale transformation
Modeled, loaded tables
Fits when
Lightweight, synchronous, bounded
Interactive and exploratory
Heavy or multi-stage processing
Sustained, concurrent analytics
Struggles when
Workload outgrows one function
You need a low-ceremony API endpoint
You need a synchronous response
You need no standing warehouse

The measurements above give a reference point for one workload shape: 25 warm requests against a 22 KiB file, on a 2048 MB function with 390–430 ms handler durations. The interesting cost question is not per-request. It is what happens when request volume grows and the same files are read again on every invocation. Multiplying handler duration by request volume and adding S3 GET requests per query is the calculation that decides whether this pattern is the right one at scale, not a benchmark of the engine alone. I did not measure S3 request counts here, so that half of the calculation is yours to do.

Questions I ask before choosing this pattern:
  1. Is the consumer an application that needs a synchronous HTTP response?
  1. Is the dataset bounded and known, rather than an open-ended lake?
  1. Is the query a filter and an aggregate, not a multi-way join or window-heavy analysis?
  1. Does it finish with margin inside the timeout? HTTP APIs cap integrations at 30 seconds.
  1. Is traffic sporadic or moderate, rather than sustained against the same data?
  1. Can I live without persistent state, modeling, and high-concurrency semantics?

Yes to all six: this pattern is a candidate. A no on questions 2, 3, or 5 sends me to Athena, Glue/Spark, or Redshift, depending on which answer failed. Failure Modes and Constraints
Suitability depends on Lambda memory, temporary storage, function timeout, query complexity, the number and size of Parquet files, S3 access, and request volume. I do not quote a dataset-size ceiling, because it would depend on all of those at once.
  • First request on a fresh container. When the function is invoked on a fresh container, the first query can take 1.8–12.8 s of handler time beyond what  Init Duration reports. The stall is localized to the connection setup path (before query.start), not to SQL execution. On a warm container, the same request completes in 390–430 ms. A synchronous client can therefore see multi-second latency on the first request after a deploy or container recycle, even when Lambda reports a sub-500 ms init.
  • Startup. Without the tmp settings above, DuckDB fails at startup rather than at query time. It surfaces as an error about the home directory.
  • Timeout. A query that exceeds the timeout is terminated, and the client sees a gateway timeout rather than a useful message.
  • Opaque errors. The handler returns a generic 500 and logs the exception to CloudWatch. Access-denied, corrupted Parquet, and engine errors look identical to the caller.
  • Repeated reads. Every request may make DuckDB read the relevant Parquet data again. There is no cache and no persistent index between invocations. In this measurement, a 22 KiB Parquet file in S3 took 390–430 ms of handler time, while the same SQL against a 140 MB Parquet file locally took 85 ms. The time appears to go to the serverless wrapper, the connection setup, and the S3 access path rather than to query execution, and every request pays it again. For bounded, low-to-moderate traffic that is a reasonable simplicity trade. For sustained traffic against the same data, repeated scanning and aggregation stops being the right strategy: each invocation consumes Lambda compute and generates S3 requests, so evaluate cost against request volume and query frequency. Alternatives include caching results, precomputing aggregates into a serving layer such as DynamoDB, or moving that traffic to Athena or Redshift. This is not a claim that S3 reads are expensive. It is a claim that this design recomputes by default.

Security and Deployment Notes

Terraform provisions the stack: ECR, Lambda, the HTTP API and route, an S3 bucket, a scoped IAM role, and a CloudWatch log group. Lambda needs the image in ECR before it can be created, so deployment runs in two passes:

make generate-data
make bootstrap-ecr
make build
make push-image
make deploy
make upload-sample-data
curl "$API_URL/sales/summary?country=CA&year=2023"
An illustrative response shape (not a measured result):

{"filters": {"country": "CA", "year": "2023"},
"result": {"total_orders": 10, "units_sold": 50, "revenue": 1234.5}}
The repository's baseline is deliberately narrow: read-only access scoped to the data prefix, no hardcoded credentials, a private bucket with server-side encryption, bound SQL parameters, and CloudWatch logging. It ships without authentication, so treat it as a demo until you add:
  • Authentication and authorization. HTTP APIs support IAM authorization, JWT authorizers (for example with Cognito), and Lambda authorizers. Pick based on who calls the API.
  • Throttling. Configure stage or route-level throttling on the API, and consider reserved concurrency on the function to cap how much S3 traffic a burst can generate.
  • Monitoring. Alarms on errors, duration approaching the timeout, and throttles.

Conclusion

The smallest appropriate compute engine is a judgment call. For one class of problems, a bounded Parquet dataset behind a synchronous API with simple aggregations, an embedded engine inside ephemeral compute can be enough, and it removes a service from the architecture.

But "can be enough" has to be measured. In this deployment, query execution was not the bottleneck. Instead, the serverless overhead and connection setup dominated the observed latency, including a first-invocation delay of 1.8–12.8 seconds that was not reflected in Lambda's reported  Init Duration .
This is the kind of boundary you need to identify for your own workload before adopting this pattern. The questions above help determine which tool to consider; measurements tell you whether it is actually the right fit.

GitHub

The complete implementation, including the Lambda container, DuckDB integration, Dockerfile, Terraform infrastructure, tests, and deployment instructions, is available on GitHub:  https://github.com/aarigonimi/duckdb-aws-lambda 

References

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