Amazon S3 Tables, a capability of Amazon Simple Storage Service (Amazon S3), deliver a cloud object store with built-in Apache Iceberg support and streamline storing tabular data at scale. When you integrate them with dbt and AWS Glue, you can run SQL-based data transformations with the reliability and performance of a modern lakehouse, bringing software engineering best practices to the data space.
This post demonstrates how to configure and implement dbt transformations using Amazon S3 Tables with the dbt-glue adapter. Starting with version 1.12.4, the dbt-glue adapter adds incremental merge support for S3 Tables, which the patterns in this post build on. We cover the specific configuration requirements for the dbt-glue adapter and practical implementation patterns built on S3 Tables incremental models: the merge strategy to keep the latest state per record and the append strategy to build an audit-friendly change history.
Example scenario
In this walkthrough, we simulate an ecommerce system that tracks customer profiles and their orders. We first run the pipeline against an initial dataset, then simulate an update to the upstream source data and run it again to demonstrate incremental updates.
Our example scenario follows a data pipeline architecture that uses S3 Tables throughout. Raw ecommerce data (customers.csv and orders.csv) lands in a regular S3 bucket as comma-separated values (CSV). dbt then transforms it through two layers of S3 Tables. A staging layer cleanses and standardizes each source, and a mart layer produces analytics-ready dimension and fact tables. You can query the resulting mart data from a variety of analytics and business intelligence (BI) tools such as Amazon Athena and Amazon Quick Sight. In this post, we query it from Athena.
The mart layer demonstrates two incremental strategies side by side: the fact_orders model uses merge to keep the latest state per order, while fact_order_history uses append to accumulate a full change history.
The data pipeline flow looks like the following chart:
Source Data (Regular S3 - CSV)
└─ customers.csv, orders.csv
↓
Staging Models (S3 Tables)
├─ stg_customers
└─ stg_orders
↓
Mart Models (S3 Tables)
├─ dim_customers
├─ fact_orders (incremental with merge --- latest state per order)
└─ fact_order_history (incremental with append --- change history)
↓
Consumption Layer (Athena, Quick Sight, BI tools)
The following diagram shows the architecture behind this pipeline: dbt-glue submits each model as a Spark SQL statement to an AWS Glue interactive session, which reads from the raw S3 bucket and writes the staging and mart tables as S3 Tables within the same data lake.
Figure 1: Architecture of the dbt transformation pipeline on Amazon S3 Tables with AWS Glue
Prerequisites
Before you begin, make sure that you have the following prerequisites:
In this section, you set up the AWS infrastructure that dbt-glue needs: an S3 table bucket and namespace to hold your dbt models, and an AWS Glue database for your source data.
First, set your environment variables. Replace YOUR_ACCOUNT_ID, YOUR-REGULAR-BUCKET, and YOUR_Glue_Role_ARN with your data:
Note that the S3 Tables namespace is where the S3 Tables corresponding to your dbt models will be created. This is different from regular S3 buckets. Because the “Integration with AWS analytics services” option for S3 Tables is enabled, creating the namespace automatically creates a corresponding AWS Glue database. Verify that it exists in the next step:
In this section, you create sample ecommerce data to transform with dbt: two CSV files (customers and orders), upload them to a general purpose S3 bucket, and register them as AWS Glue tables that your dbt models can read from.
Note: All sample data in this post is synthetic. It was generated to mimic realistic patterns for demonstration purposes only and doesn’t represent any real individuals or transactions.
Complete following steps to create a sample dataset:
Create a directory for sample data and save the following two CSV files: customers.csv:
Create the bucket for source data if it doesn’t exist, and upload the CSV files to the S3 bucket. Replace YOUR-SOURCE-DATA-BUCKET with your bucket name.
The dbt CLI is a command-line interface for running dbt projects. It’s free to use and available as an open source project. Before installing dbt-core, make sure your Python version is 3.10, 3.11, or 3.12.
Install dbt and the dbt CLI with the following code:
Install the dbt-glue adapter with the following code:
$ pip3 install --no-cache-dir dbt-glue
Note that you need to install dbt-glue 1.12.4 or higher, which adds support for incremental append and merge models on S3 Tables.
Create a dbt project
In this section, you create a new dbt project using dbt init, which generates the standard directory structure (such as models, macros, and tests) that you will populate with the S3 Tables models in the next sections.
Run the dbt init command to create and initialize a new empty dbt project.
$ dbt init
For a project name, enter dbt_glue_s3_tables.
For a database, choose [1] glue.
Please ignore dbt_project.yml file [ERROR not found] message as we are going to create it in the next step.
Configure dbt profile
The dbt profile configuration is critical for S3 Tables integration. In this section, you create a dbt profile that connects to AWS Glue Interactive Sessions and configures Spark to read and write S3 Tables through the Iceberg catalog, then validate the connection with dbt debug.
Create ~/.dbt/profiles.yml with the following structure:
Run the following command to validate the configurations:
cd dbt_glue_s3_tables
dbt debug --profiles-dir ~/.dbt/
Expected output is Connection test: [OK connection ok].
Configure dbt project
The dbt_project.yml configuration determines which models use S3 Tables. Create or update dbt_glue_s3_tables/dbt_project.yml with the following structure:
name: 'dbt_glue_s3_tables'
version: '1.0.0'
config-version: 2
profile: 'dbt_glue_s3_tables'
model-paths: ["models"]
test-paths: ["tests"]
macro-paths: ["macros"]
models:
dbt_glue_s3_tables:
# S3 Tables for staging
staging:
+materialized: table
+file_format: 's3tables' # S3 Tables for staging
+table_properties:
'format': 'iceberg'
'write.format.default': 'parquet'
'write.parquet.compression-codec': 'snappy'
# S3 Tables for marts
marts:
+materialized: table
+file_format: 's3tables' # S3 Tables for marts
+table_properties:
'format': 'iceberg'
'write.format.default': 'parquet'
'write.parquet.compression-codec': 'snappy'
Create dbt models
In this section, you build out the full model layer: a sources.yml that registers your raw AWS Glue tables, two staging models that clean and prepare the customer and order data, and three mart models that turn those staged data into a dimension table and two fact tables, one using incremental merge and one using incremental append.
First, create sources.yml defines your raw data tables:
Delete the example folder under dbt_glue_s3_tables/models. This is an example folder created by default and unnecessary now.
Define source tables in models/sources.yml with the following structure:
This sources.yml defines your raw data tables, so you can reference them with the {{ source() }} function in your models. With this file, you can also define data tests like unique, not_null, and referential integrity checks in one central place.
Second, create the staging and mart models. Staging models are where you unpack and transform raw data. Mart models are what downstream consumers actually query.
Create models/staging/stg_customers.sql:
-- Staging model as S3 Tables with incremental merge
{{ config(
materialized='incremental',
incremental_strategy='merge',
unique_key='customer_id',
on_schema_change='sync_all_columns',
file_format='s3tables'
) }}
SELECT
customer_id,
LOWER(TRIM(email)) AS email,
first_name,
last_name,
CAST(registration_date AS DATE) AS registration_date,
customer_segment
FROM spark_catalog.{{ source('raw_ecommerce', 'customers') }}
WHERE customer_id IS NOT NULL
stg_customers.sql reads from the raw customers source, applies light cleansing (email normalization, date casting, null filtering), and writes to S3 Tables using an incremental merge on customer_id to update existing records rather than duplicating them.
Create models/staging/stg_orders.sql:
-- Staging model as S3 Tables with incremental merge
{{ config(
materialized='incremental',
incremental_strategy='merge',
unique_key='order_id',
on_schema_change='sync_all_columns',
file_format='s3tables'
) }}
SELECT
order_id,
customer_id,
CAST(order_date AS DATE) AS order_date,
CASE
WHEN LOWER(TRIM(order_status)) = 'completed' THEN 'completed'
WHEN LOWER(TRIM(order_status)) = 'shipped' THEN 'shipped'
WHEN LOWER(TRIM(order_status)) = 'processing' THEN 'processing'
WHEN LOWER(TRIM(order_status)) = 'cancelled' THEN 'cancelled'
ELSE 'unknown'
END AS status,
CAST(order_amount AS DECIMAL(10,2)) AS total_amount,
EXTRACT(YEAR FROM CAST(order_date AS DATE)) AS order_year,
EXTRACT(MONTH FROM CAST(order_date AS DATE)) AS order_month,
CAST(updated_at AS TIMESTAMP) AS updated_at
FROM spark_catalog.{{ source('raw_ecommerce', 'orders') }}
WHERE order_id IS NOT NULL
stg_orders.sql reads from the raw orders source, normalizes status to a fixed set of values (defaulting to unknown for anything unexpected), casts order_date, total_amount, and updated_at to their proper types, and derives order_year and order_month for downstream partitioning.
Create models/marts/dimensions/dim_customers.sql:
-- Dimension table using S3 Tables
{{ config(
materialized='table',
file_format='s3tables',
partition_by=['registration_year'],
table_properties={
'format': 'iceberg',
'write.format.default': 'parquet'
}
) }}
SELECT
customer_id,
email,
first_name,
last_name,
registration_date,
YEAR(registration_date) as registration_year,
customer_segment,
CASE
WHEN customer_segment = 'Premium' THEN 1
WHEN customer_segment = 'Regular' THEN 2
ELSE 3
END as segment_priority,
CURRENT_TIMESTAMP() as dbt_updated_at
FROM {{ ref('stg_customers') }}
Create models/marts/facts/fact_orders.sql:
-- Fact table using S3 Tables with incremental merge
{{ config(
materialized='incremental',
file_format='s3tables',
incremental_strategy='merge',
unique_key='order_id',
partition_by=['order_year', 'order_month'],
table_properties={
'format': 'iceberg',
'write.format.default': 'parquet'
}
) }}
SELECT
o.order_id,
o.customer_id,
o.order_date,
YEAR(o.order_date) AS order_year,
MONTH(o.order_date) AS order_month,
o.status,
o.total_amount,
c.customer_segment,
c.segment_priority,
CURRENT_TIMESTAMP() AS dbt_updated_at
FROM {{ ref('stg_orders') }} o
LEFT JOIN {{ ref('dim_customers') }} c
ON o.customer_id = c.customer_id
Create models/marts/facts/fact_order_history.sql:
-- Fact table using S3 Tables with incremental append
{{ config(
materialized='incremental',
file_format='s3tables',
incremental_strategy='append',
partition_by=['event_year', 'event_month'],
table_properties={
'format': 'iceberg',
'write.format.default': 'parquet'
}
) }}
SELECT
order_id,
customer_id,
status,
order_date,
total_amount,
updated_at,
CURRENT_TIMESTAMP() AS recorded_at,
YEAR(updated_at) AS event_year,
MONTH(updated_at) AS event_month
FROM {{ ref('stg_orders') }}
{% if is_incremental() %}
WHERE updated_at > (SELECT MAX(updated_at) FROM {{ this }})
{% endif %}
Run the dbt project
Now it’s time to run the dbt project. Complete following steps:
To run the project dbt, you should be in the project folder:
cd dbt_glue_s3_tables
Run the dbt command:
dbt run --profiles-dir ~/.dbt/ --full-refresh
This command starts an AWS Glue interactive session, compiles the dbt models, and materializes all five tables (stg_customers, stg_orders, dim_customers, fact_orders, and fact_order_history) in your S3 Tables namespace. The --full-refresh flag rebuilds the incremental models from scratch, so it’s the right choice for the first run.
Query using Amazon Athena
Before testing the incremental merge and append behavior in the next section, confirm what the initial --full-refresh run loaded into the mart tables. Query the target tables.
In the Athena console, choose the data source and database that correspond to your S3 Tables catalog:
Run the following query to view the data loaded into the fact_orders table:
SELECT * FROM dbt_glue_s3_tables.fact_orders ORDER BY order_id;
The result returns the five order records:
# order_id customer_id order_date order_year order_month status total_amount customer_segment segment_priority dbt_updated_at
1 1001 1 2024-06-01 2024 6 completed 150.00 Premium 1 2026-10-16 09:41:46.590373 UTC
2 1002 2 2024-06-02 2024 6 completed 75.50 Standard 3 2026-10-16 09:41:46.590373 UTC
3 1003 1 2024-06-03 2024 6 completed 200.00 Premium 1 2026-10-16 09:41:46.590373 UTC
4 1004 3 2024-06-04 2024 6 unknown 125.75 Premium 1 2026-10-16 09:41:46.590373 UTC
5 1005 4 2024-06-05 2024 6 completed 89.99 Standard 3 2026-10-16 09:41:46.590373 UTC
Run the following query to view the data loaded into the fact_order_history table:
SELECT * FROM dbt_glue_s3_tables.fact_order_history ORDER BY updated_at;
The result returns the five order history records.
# order_id customer_id status order_date total_amount updated_at recorded_at event_year event_month
1 1001 1 completed 2024-06-01 150.00 2024-06-01 10:00:00.000000 UTC 2026-10-16 09:41:22.801835 UTC 2024 6
2 1002 2 completed 2024-06-02 75.50 2024-06-02 10:00:00.000000 UTC 2026-10-16 09:41:22.801835 UTC 2024 6
3 1003 1 completed 2024-06-03 200.00 2024-06-03 10:00:00.000000 UTC 2026-10-16 09:41:22.801835 UTC 2024 6
4 1004 3 unknown 2024-06-04 125.75 2024-06-04 10:00:00.000000 UTC 2026-10-16 09:41:22.801835 UTC 2024 6
5 1005 4 completed 2024-06-05 89.99 2024-06-05 10:00:00.000000 UTC 2026-10-16 09:41:22.801835 UTC 2024 6
Incremental merge and append on Iceberg table
After the initial --full-refresh run succeeds, verify that the merge and append incremental strategies behave as expected when the source data changes. This demonstrates the row-level update capability that Iceberg on S3 Tables provides.
Update the sample source data
To simulate a real-world scenario where upstream source data changes over time (for example, a customer updating their profile, or new customers signing up), modify customers.csv to include both an update to an existing record and a new record.
order_id=1004: status updated from pending to completed with a later updated_at (to test the merge UPDATE).
order_id=1006: new record added with a later updated_at, associated with the new customer customer_id=6 (to test both the merge INSERT in fact_orders and the append in fact_order_history).
By running without --full-refresh, dbt runs its normal incremental logic instead of rebuilding the tables from scratch. In the staging layer, stg_customers and stg_orders apply the changes with a MERGE INTO statement that updates customer_id=1 and order_id=1004 in place and inserts customer_id=6 and order_id=1006. Downstream, fact_orders (merge) reflects the 1004 update and the 1006 insert as the latest state, while fact_order_history (append) records both 1004 and 1006 as new history rows.
Verify the results in Amazon Athena
After the re-run completes, use Athena to confirm that the merge and append strategies behaved as expected.
Run the following query to view the updated data in the fact_orders table:
SELECT * FROM dbt_glue_s3_tables.fact_orders ORDER BY order_id;
fact_orders returns 6 rows (one per order), with 1004 now completed and 1006 added.
# order_id customer_id order_date order_year order_month status total_amount customer_segment segment_priority dbt_updated_at
1 1001 1 2024-06-01 2024 6 completed 150.00 Premium 1 2026-10-16 10:06:55.944983 UTC
2 1002 2 2024-06-02 2024 6 completed 75.50 Standard 3 2026-10-16 10:06:55.944983 UTC
3 1003 1 2024-06-03 2024 6 completed 200.00 Premium 1 2026-10-16 10:06:55.944983 UTC
4 1004 3 2024-06-04 2024 6 completed 125.75 Premium 1 2026-10-16 10:06:55.944983 UTC
5 1005 4 2024-06-05 2024 6 completed 89.99 Standard 3 2026-10-16 10:06:55.944983 UTC
6 1006 6 2024-07-02 2024 7 completed 45.00 Premium 1 2026-10-16 10:06:55.944983 UTC
Run the following query to view the updated data in the fact_order_history table:
SELECT * FROM dbt_glue_s3_tables.fact_order_history ORDER BY updated_at;
fact_order_history grows from 5 rows to 7 rows on the second run (the 2 rows whose updated_at advanced: 1004 and 1006). Order 1004 now has two history rows: the original unknown status and the new completed status.
# order_id customer_id status order_date total_amount updated_at recorded_at event_year event_month
1 1001 1 completed 2024-06-01 150.00 2024-06-01 10:00:00.000000 UTC 2026-10-16 09:41:22.801835 UTC 2024 6
2 1002 2 completed 2024-06-02 75.50 2024-06-02 10:00:00.000000 UTC 2026-10-16 09:41:22.801835 UTC 2024 6
3 1003 1 completed 2024-06-03 200.00 2024-06-03 10:00:00.000000 UTC 2026-10-16 09:41:22.801835 UTC 2024 6
4 1004 3 unknown 2024-06-04 125.75 2024-06-04 10:00:00.000000 UTC 2026-10-16 09:41:22.801835 UTC 2024 6
5 1005 4 completed 2024-06-05 89.99 2024-06-05 10:00:00.000000 UTC 2026-10-16 09:41:22.801835 UTC 2024 6
6 1004 3 completed 2024-06-04 125.75 2024-06-11 09:30:00.000000 UTC 2026-10-16 10:06:35.291993 UTC 2024 6
7 1006 6 completed 2024-07-02 45.00 2024-07-02 10:00:00.000000 UTC 2026-10-16 10:06:35.291993 UTC 2024 7
Clean up
To avoid ongoing charges, clean up the resources you created during this walkthrough. Complete these steps in the specified order to facilitate proper resource deletion.
Drop the tables dbt created in the S3 Tables namespace.
Delete the data this walkthrough wrote to your S3 bucket: the dbt warehouse data under s3://<YOUR-REGULAR-BUCKET>/glue/data/ and the sample CSV files under s3://<YOUR-REGULAR-BUCKET>/raw/. Leave the bucket itself in place if you use it for other workloads.
(Optional) Remove the local dbt project directory (dbt_glue_s3_tables) and the sample customers.csv / orders.csv files.
Conclusion
In this post, we showed how to build an end-to-end dbt transformation pipeline on Amazon S3 Tables with AWS Glue 6.0, using a staging and mart architecture. At the core of this pipeline are incremental models on S3 Tables, which let us transform and maintain data incrementally with SQL. We demonstrated two incremental strategies working together: the merge strategy to keep the latest state per order in fact_orders, and the append strategy to build an audit-friendly change history in fact_order_history.
S3 Tables support in the dbt-glue adapter is currently experimental (as of version 1.12.4) and will continue to evolve in upcoming releases. As with any experimental feature, we recommend thoroughly testing it in your own environment before use.
Many organizations run their Apache Spark pipelines on AWS Glue and each new AWS Glue release means another round of version upgrades. New versions bring better performance and new features, but upgrading takes work. For every job, an engineer reviews breaking changes across Spark, Python, and libraries, then runs the job on the new version and confirms that it produces the same results. Many jobs turn out to need no changes, but the team learns that only after doing the work. Across hundreds of jobs, upgrading becomes a project that keeps coming back, so many jobs stay on older versions.
Today, we’re announcing automatic version upgrades for AWS Glue jobs (auto upgrade). When you set a job’s version to auto, AWS Glue analyzes the job, asks for your approval, and moves the job to the latest stable version. Instead of planning, testing, and tracking each upgrade, your team reviews and approves it.
In this post, you learn how auto upgrade works and how to:
Turn on auto upgrade for a job and approve the upgrade in the AWS Glue console.
Use an AI agent to assess a fleet of jobs, turn on auto upgrade with email notifications, approve the upgrades, and check the results.
How auto upgrade works
Set a job’s GlueVersion to auto to turn on auto-upgrade. The job keeps running as usual on its current version while AWS Glue checks the job for known breaking changes. AWS Glue doesn’t modify your script. When AWS Glue determines that the job needs no code changes, AWS Glue sends you an eligibility summary with the compatibility results for application code, configuration, and dependencies, and requests your approval. The job stays on its current version until you approve. After you approve, AWS Glue runs the job on the new version and checks the upgraded runs against the job’s earlier runs. AWS Glue then sends you an auto upgrade evaluation summary with the results for correctness, performance, and cost. If the upgraded runs pass the checks, AWS Glue completes the upgrade, and all subsequent runs use the new version. If an upgraded run fails, AWS Glue retries the run on the previous version, so your pipeline keeps running, and then reverts the job. For details, see How an auto upgrade evaluation works in the AWS Glue User Guide.
One or more AWS Glue jobs that meet the following requirements:
The job is a Spark ETL job (glueetl) on AWS Glue 2.0 or later.
The job’s MaxRetries parameter is set to 1 or higher, and job run queuing is turned off.
The job is safe to retry.
For the AI agent walkthrough, you also need the following:
An AI agent that supports skills and MCP servers, such as Kiro or Claude Code, with the managing-glue-jobs skill from the AWS Glue samples repository on GitHub.
The latest version of the AWS Command Line Interface (AWS CLI) version 2.
The spark-upgrade MCP server from Amazon SageMaker Unified Studio, which runs the compatibility assessment. To connect the server, see the skill’s README.
For email notifications, the Amazon Simple Notification Service (Amazon SNS) and Amazon EventBridge permissions in the skill’s permissions.md file.
To install the skill, copy the skill folder into your agent’s skills folder.
Choose the job, and then choose the Job details tab.
For AWS Glue version, choose Auto, and for Number of retries, enter 1 or higher.
Choose Save.
Figure 1: The Job details tab for orders-daily, with AWS Glue version set to Auto
Approve or decline the upgrade
When AWS Glue finishes the compatibility checks and finds no blocking issues, the job waits for your approval.
Choose the job, and then choose the Upgrade analysis tab. The analysis status shows Waiting for consent.
In the Upgrade consent required banner, choose eligibility summary, and review the summary.
Choose Approve to upgrade the job, or choose Decline to keep the job on its current version.
Figure 2: The Upgrade analysis tab for orders-daily, waiting for your approval
The eligibility summary shows the job, the AWS Glue versions, and the compatibility results.
Figure 3: The eligibility summary for orders-daily
Check the result
After the evaluation ends, the Upgrade analysis tab shows the auto upgrade evaluation summary. The summary shows the result for performance, correctness, and cost, with the expected range and each upgraded run’s value for every check.
Figure 4: The auto upgrade evaluation summary for orders-daily
Walkthrough: Upgrade a fleet of jobs with an AI agent
When you manage many jobs, an AI agent with the managing-glue-jobs skill assesses, turns on, and approves auto upgrade across your jobs from a few prompts. The agent shows each change and asks for your confirmation before it makes the change.
Figure 5: The auto upgrade journey for existing jobs
In this walkthrough, you assess your jobs, turn on auto upgrade, approve the upgrade, and check the result. Between these steps, AWS Glue observes and checks each job, and then upgrades and validates the job. Amazon SNS emails you the eligibility summary and the evaluation summary. The steps that follow match the numbers in Figure 5.
A data team runs three Spark ETL jobs in the US West (Oregon) Region and they want to use AWS Glue version 6.0. The jobs orders-daily and clickstream-agg run on AWS Glue 4.0 and write to Amazon Simple Storage Service (Amazon S3). The job customer-profiles runs on AWS Glue 3.0.
Step 1: Assess your jobs
Ask the agent which of your jobs can use auto upgrade. The assessment does not change anything in your environment, so it’s safe to try first. The agent checks each job against the requirements and runs a compatibility assessment. The agent then lists the jobs that can move to AWS Glue 6.0 and asks you to confirm that each job is safe to retry.
Figure 6: The agent assesses the jobs
To see which job isn’t ready and why, ask the agent. The agent names the setting that blocks the upgrade and the fix.
Figure 7: The agent explains why a job isn’t ready
Step 2: Turn on auto upgrade and set up email notifications
Ask the agent to turn on auto upgrade and set up email notifications in one prompt. The agent sets up the email notifications and sets GlueVersion to auto for each job. The jobs keep running on AWS Glue 4.0 until you approve an upgrade. To get the email notifications, confirm the subscription as the reply describes.
Figure 8: The agent turns on auto upgrade and sets up email notifications
Step 3: Review and approve the upgrade
AWS Glue observes and checks each job in the background, and then you review and approve the upgrade.
Step 3a: AWS Glue observes and checks
You keep running the jobs on their usual schedule. In the background, AWS Glue observes the runs and analyzes each job without changing it. How long this takes depends on how often each job runs.
When a job is ready, AWS Glue emails you and requests your approval. The email names the job and the AWS Glue versions, and links to the job in the AWS Glue console. You have seven days to approve or decline.
Figure 9: The approval request email
Step 3b: Review and approve the upgrade
Ask the agent which upgrades are waiting. The agent reads the eligibility summary of each job, and then shows the jobs, their write paths, and what to confirm before you approve.
Figure 10: The agent shows the upgrades that wait for your approval
Before you approve, confirm that the reply lists every path that each job writes to. Then approve the jobs in one prompt, and name each job that you approve.
Figure 11: The agent approves the named jobs
The agent approves only the jobs that you name, and only jobs from the review that it showed you.
Step 4: Check the result
AWS Glue upgrades and validates each job, and then you check the result.
Step 4a: AWS Glue upgrades and validates
After you approve, subsequent runs of each job use AWS Glue 6.0, and AWS Glue validates the upgraded runs. If an upgraded run fails, AWS Glue retries the run on AWS Glue 4.0 and reverts the job. You don’t need to act in this step.
Step 4b: Check the result
When the evaluation of a job ends, AWS Glue emails you the result. Ask the agent for the result of orders-daily. The agent shows the result of each validation check.
Figure 12: The agent shows the result for orders-daily
Ask the agent about the other job. The agent shows the check that failed and suggests a fix.
Figure 13: The agent explains why clickstream-agg didn’t upgrade
Your pipeline continues to run on AWS Glue 4.0. The auto upgrade evaluation summary shows what changed, so you can fix the job before you try again.
Conclusion
In this post, we showed how automatic version upgrades for AWS Glue jobs keep your Apache Spark jobs on the latest stable AWS Glue version. You used an AI agent to assess your jobs and turn on auto upgrade with email notifications. You then reviewed the eligibility summary, approved the upgrades, and checked the results in the auto upgrade evaluation summary.
With auto upgrade, your team no longer needs to plan and run an upgrade project for each job. AWS Glue analyzes each job and checks the upgraded runs against the job’s earlier runs. Your team reviews and approves each upgrade. This way you keep your whole fleet of AWS Glue jobs current instead of upgrading one job at a time.
Some jobs need code changes before they can move to a new version. For those jobs, use generative AI upgrades for Apache Spark in AWS Glue, which proposes and validates the code changes for the new version. After you update the code, set the job’s GlueVersion to auto so that AWS Glue keeps the job current from then on.
Auto upgrade is available today in all commercial AWS Regions. For the list of Regions, see Considerations and limitations in the AWS Glue User Guide. To get started, ask an AI agent with the managing-glue-jobs skill to assess the AWS Glue jobs in your account. Try auto upgrade, and share your feedback in the comments.
Special thanks
A special thanks to everyone who contributed from Engineering and Science to the launch of automatic version upgrades: Ezgi Maden, Akshara Ganapathi, Tina Shao, Raghavendhar Thiruvoipadi Vidyasagar, Shoukat Ghouse, David Zhang, Suthan Phillips, Prasad Nadig, Syed Mahmood, Karthik Seshadri, Pradeep Kumar Nalluri, Adam Rohrscheib, Eric Zhang, Tayo Adedokun, Weston Dunn, Kartik Panjabi, Shubham Mehta, Bryan Liles, Steffen Rochel, Kinshuk Pahare, Paul Meighan, and Rick Sears
With Amazon EMR Serverless and AWS Glue ETL, you can run Apache Spark applications without provisioning or managing clusters. You submit jobs, the service allocates the compute, scales it during execution, and releases it when the job finishes. Both services deliver a balanced performance profile by default. However, because of different datasets and transformations, customers who want to push further on cost or performance still need to tune Spark settings. Investigating why a specific job is slow or expensive often requires deep Spark expertise: analyzing Spark History Server timelines, shuffle metrics, executor sizes, and task distributions. That work falls to the few Spark experts on the team, and their time is often the bottleneck.
Today we are announcing the general availability of the Apache Spark optimization agent for Amazon EMR Serverless and AWS Glue ETL. The agent analyzes completed Spark job runs and delivers optimization recommendations in minutes, replacing hours of manual analysis by Spark experts. Any engineer can select a cost or performance goal and receive specific configuration changes grounded in evidence from the job’s own Spark telemetry. The agent supports single job-run analysis as well as comparison against a known-good baseline job run.
The Apache Spark optimization agent is available at no additional charge.
In this post, we explain what the agent does, how it works, and how to use it.
What the Apache Spark optimization agent does
The optimization agent analyzes Spark jobs and recommends changes that reduce cost, improve performance, or both. You can access the agent from the EMR Studio UI, AWS Glue Studio UI, or through the Amazon SageMaker Unified Studio MCP Server using any MCP-compatible client such as Kiro. You point it at a completed job run, choose either cost or performance as the intent, and receive recommendations that cite the specific metrics from that run. Often tuning for faster performance also lowers resource usage and cost, but in some cases a faster job requires more resources, which increases cost. The agent optimizes for the goal you choose, cost or performance, and makes sure the one you did not pick does not get noticeably worse. For example, a cost recommendation can make a job run slightly longer, but no more than the normal variation between runs. For larger and more expensive jobs, the agent tightens the threshold further.
There are two ways to analyze a Spark job:
Single job-run analysis. The agent examines one completed run and identifies common sources of inefficiency: data skew, memory pressure, excessive shuffle and disk spill, undersized or oversized workers, suboptimal join strategies, and input layout issues such as small files. Each recommendation shows the Spark properties to change, the current and proposed values, and the telemetry evidence behind the suggestion.
Baseline comparison. When a job that used to meet its targets starts running longer or costing more, compare it against a run that performed well. Provide the current run and the earlier baseline, and the agent compares their configuration, metrics, and stage behavior to pinpoint what changed.
The agent is read-only. It does not change your code or job settings. You decide which recommendations to apply.
How the Apache Spark optimization agent works
The following diagram shows how a request flows from the AWS console or your MCP-compatible client to the remote MCP server, through feature extraction and the recommendation engine, and back to you as recommendations.
Figure 1: How a request flows from the console or MCP client through the recommendation engine and back as recommendations
The workflow consists of the following steps:
State your intent in plain language, such as performance or cost for a completed job run.
Your MCP client or the AWS console sends the job run to the remote MCP server.
The agent reads the run’s Spark History Server telemetry, configuration, logs, and cost through existing APIs, over TLS-encrypted connections, and uses them for feature extraction and context building.
A recommendation engine combines rule-based investigations, intent-based deterministic models, and a knowledge base to find the bottleneck and determine the fix.
You get back labeled recommendations, each with the evidence behind it.
The agent approaches each request with the objective to optimize either performance or cost. It then uses read-only access through AWS APIs and the Persistent Spark History Server or AWS Glue Apache Spark Web UI to gather the Spark configuration and telemetry. Additionally, the configuration inspector collects the job’s settings and compares them against a baseline run when one is provided.
The investigation and recommendation engine looks at these artifacts together to find what is driving runtime and cost. A slow stage may stem from too little parallelism, a skewed join key, memory pressure that forces spill, or a slow upstream read. High cost might come from idle executors or capacity well beyond what the job uses.
Rule-based investigations and an intent-based deterministic model calculate the recommended values. An AI model combines the findings with a knowledge base of the settings most often tuned across millions of Spark jobs on AWS. The agent only recommends changing a setting when the evidence supports it. When cost and runtime trade off against each other, the agent optimizes for the metric you choose and keeps any impact on the other within defined limits.
Note: The agent does not use customer data to train or build the knowledge base.
The Spark optimization agent includes built-in guardrails for personally identifiable information (PII), sensitive data, security, and cost thresholds to make sure recommendations are safe.
Each recommendation is labeled with what it changes:
[infra]: the compute resources your job runs on, such as the EMR Serverless application’s pre-initialized and maximum capacity, the worker vCPU and memory size, or the AWS Glue worker type and number of workers.
[config]: Spark configuration, such as spark.sql.shuffle.partitions, spark.executor.memory, or an Adaptive Query Execution (AQE) setting.
[data]: a change to the underlying data’s physical layout, such as repartitioning a table on a different key or compacting small files.
Each category needs a different level of review. A [config] change can typically be validated in the next run without any code change. A [data] change modifies the job’s actual behavior, or the data it depends on, and should go through the same review and testing discipline as any other production change before it ships.
How to use the Apache Spark optimization agent
You can run the optimization agent from the AWS console or from any MCP-compatible client, such as Kiro, Claude Code, or Codex, through the analyze_spark_workload tool on the Amazon SageMaker Unified Studio remote MCP server. From an MCP client, ask in plain language, and words like “faster” or “cheaper” set the goal. For setup steps, see Use Spark Optimization Agent.
The following steps show how to use the agent in the AWS console.
EMR Serverless
In EMR Studio, select your Application, and choose the Batch job that you want to optimize.
Choose Analyze with AI.
Figure 2: Choosing Analyze with AI for a batch job in EMR Studio
You can select to optimize for Performance or Cost. If you have a previous job run that was faster, you can also choose to Compare with a baseline job. Then, choose View Recommendations.
Review the recommendations in the AI Analysis tab and apply them to the next run.
Figure 3: AI Analysis tab in EMR Studio showing the agent’s recommendations
AWS Glue
Go to the AWS Glue console.
Under ETL jobs, choose the AWS Glue ETL job that you want to optimize.
Choose the Runs tab, select the succeeded job run and choose Analyze with AI.
Figure 4: Selecting a succeeded run on the AWS Glue console Runs tab and choosing Analyze with AI
You can select to optimize for Performance or Cost. If you have a previous job run that was faster, you can also choose to Compare with a baseline job.
Once the AI Analysis has completed, you can view the recommendations, apply the changes, and perform the next run.
Figure 5: Reviewing the agent’s recommendations in the AI Analysis tab on the AWS Glue console
Use cases
The agent works across many situations. The following table shows sample prompts for each goal. In an MCP-compatible client, include the job run ID, and for a comparison, the baseline run ID.
Goal
Sample prompts
Performance
“My job is slow. How do I make this job faster?”
Cost
“My bill is too high.” / “Reduce spend without impacting reliability.”
Baseline comparison
“Why is my job running slowly today?” / “My job used to finish in 10 minutes but now it takes an hour.”
The following three use cases are common situations that data teams run into. Each one describes a scenario, the Spark issues that the agent looks for, and what you get back. They apply to both Amazon EMR Serverless and AWS Glue ETL.
My job is missing its SLA. How do I make it finish sooner?
A nightly orders pipeline that feeds an 8 AM dashboard takes longer as time goes on, and adding more compute power is not always a good practice. You ask the agent to optimize the run for performance. It identifies the bottleneck and then recommends the exact settings to change for that stage so the job finishes sooner.
How can I make this job cheaper?
The bill keeps rising, but every job finishes on time, so the jobs rarely get reviewed for optimization. You ask the agent to optimize the run for cost without significantly affecting the runtime. It compares the executors a job held with what its stages kept busy, exposing over-provisioning, such as a minimum executor count set too high or dynamic allocation left uncapped. It then sizes capacity to actual use. Before you apply these changes, it shows the runtime trade-off between cost and performance. For example, reducing the number of executors can improve resource utilization and lower cost but can also increase the job’s runtime.
Why is this run slower than my baseline run?
A job now takes several times as long on the same datasets compared to previous runs. This is a baseline comparison scenario. You give the agent the slow run and an earlier run that finished on time. Instead of tuning the slow run in isolation, the agent compares the two runs side by side, covering their configuration, metrics, and stage behavior. It isolates the differences that explain the regression, and tells you which settings to restore to get back to baseline performance.
Optimization results
The agent tunes every recommendation to the specified goal and checks to confirm it does not regress the other dimension beyond tolerance.
We tested the Apache Spark optimization agent across hundreds of workloads on Amazon EMR Serverless and AWS Glue ETL. The tests included industry benchmarks (derived from TPC-DS and TPC-H) at various scale factors, along with customer-representative workloads shared by enterprise AWS Glue and Amazon EMR customers.
The evaluation set is made up of Spark workloads that follow common patterns from multiple different industries such as ecommerce, industrial telemetry, manufacturing, and more. Each workload copies the structure of a typical production job, including its join strategies, shuffle sizes, and skew, so the agent’s recommendations can be checked against realistic performance. Together, the workloads cover most production ETL patterns: ingestion, multi-way joins, upserts, slowly changing dimensions, rollups, and full query benchmarks. They run on several open table formats and on standard columnar storage.
The following table shows the ranges of cost improvement observed when invoking the agent with the cost intent and the performance improvement observed with the performance intent. Across hundreds of workloads, the agent reduced cost by 24-31% with the cost intent and improved performance by 23-49% with the performance intent.
Workload
Cost improvement
Performance improvement
Aggregate (across 100+ workloads)
24–31%
23–49%
TPC-DS 3 TB
30–78%
32–44%
TPC-H 3 TB
10–64%
19–33%
The ranges in the table reflect testing across different versions of Amazon EMR Serverless and AWS Glue ETL.
Note: The cost or performance improvement you see depends on your workload, its current configuration, and the version of Amazon EMR Serverless or AWS Glue ETL you are running.
Conclusion
In this post, we introduced the Apache Spark optimization agent for Amazon EMR Serverless and AWS Glue ETL. We showed how the agent analyzes successful Spark runs and recommends changes that reduce cost and improve runtime, how it explains why a run regressed against earlier faster runs, and how each recommendation points back to the measurement behind it. We also walked through how the agent works and different ways to use it.
If a job run fails, the Apache Spark troubleshooting agent under the same MCP endpoint analyzes the run’s logs and Spark event data, identifies the root cause, and explains it in plain language.
To get started, pick a job that you run often or that you want to optimize, and ask the agent how to optimize it for cost or performance. Validate the recommendations in a test run before you apply them in production. If you already use the Apache Spark troubleshooting agent, you can start right away because both agents use the same MCP server.
Finance teams want to allocate AI spend to the business units that use it. Engineering leaders want to know what that spend delivers. Security teams want to know who owns each API key and whether any belong to former employees. Anthropic gives administrators detailed visibility into usage and cost through Claude Code usage analytics and the Anthropic Admin API. Many enterprises want to take the next step and analyze that data alongside the business data they already manage in AWS. Until now that has meant building and maintaining a custom integration with the Admin API.
AWS Glue now offers a native connector for Anthropic. AWS Glue is a serverless data integration service that helps you discover, prepare, move, and integrate data from multiple sources for analytics, artificial intelligence and machine learning (AI/ML), and application development. The connector for Anthropic is one of 100 new native connectors that AWS Glue added for popular software as a service (SaaS) applications. It works like other AWS Glue connectors and requires no custom code. You store an Anthropic API key in AWS Secrets Manager and create an AWS Glue connection that references it. The connector handles the API calls and schema mapping for you so your team can focus on analyzing the data instead of maintaining the integration.
The connector makes AI usage another domain in your data lakehouse. With Amazon S3 Tables, fully managed Apache Iceberg tables in Amazon Simple Storage Service (Amazon S3), you can store your transformed Anthropic and business data in an open and interoperable format that AWS analytics services can read natively and other Iceberg engines can query.
In this post, we follow the fictional retailer AnyCompany Retail as it brings Anthropic data into Amazon S3 Tables and joins it with its own business data using AWS Glue materialized views stored as Apache Iceberg tables. The team uses Amazon Athena to query the data with SQL and answer leadership’s three questions about spend, value, and API key ownership. It then publishes the results to an AWS Quick dashboard that leadership reviews every week.
Solution overview
The following diagram shows the solution architecture.
Figure 1: Solution architecture for analyzing Anthropic usage data with AWS Glue, Amazon S3 Tables, Amazon Athena, and AWS Quick
The workflow consists of the following steps:
You store your Anthropic API keys in AWS Secrets Manager, where the AWS Glue connection references them.
An AWS Glue extract, transform, and load (ETL) job uses the Glue connector for Anthropic to read entities such as usage and cost reports, users, and workspaces.
The job transforms the data into fact and dimension tables like daily usage, daily cost, and writes them to Amazon S3 Tables as Apache Iceberg tables.
The job joins the Anthropic data with business data that you own like workspace-to-business-unit mapping, outcome metrics, and an employee directory. In our example, this data is stored in Amazon S3.
Amazon Athena queries the tables to answer the spend, value, and access questions, and AWS Quick presents the results through natural language prompting or dashboards.
Supported entities
Anthropic uses two kinds of API keys, and each provides access to different sets of data. An Admin API key reads organization-level data. A workspace API key reads data inside a single workspace. You create one AWS Glue connection for each key.
Entity
API key
Description
users
Admin
Organization members with their email, name, and role
invites
Admin
Pending and accepted organization invites
workspaces
Admin
Workspaces in the organization, including the default and archived workspaces
workspace_members
Admin
Members of each workspace with their workspace role
api_keys
Admin
API keys with status, scope, workspace, and creator
usage_report
Admin
Token usage per time bucket, optionally grouped by workspace, API key, model, and more
cost_report
Admin
Cost per daily bucket, optionally grouped by workspace and cost description
models
Workspace
Claude models available to the workspace
message_batches
Workspace
Message Batches API jobs with status and request counts
files
Workspace
Files uploaded to the workspace
Example scenario
The retailer uses Claude across five business units, each with its own Anthropic workspace: Customer Service, Engineering, Document Processing, Marketing, and Data Science. Every week, leadership reviews AI spend across the business units and asks three questions:
Which business units are driving AI spend?
Is the spend paying off, for example in cost per resolved customer case?
Are any active API keys owned by employees who have left the company?
Throughout this post, the Anthropic data comes from a demo organization. The reference datasets (business-unit mapping, support outcomes, and employee directory) are illustrative samples.
Prerequisites
To follow along, you need the following:
An Anthropic organization (Admin API features aren’t available for individual accounts).
An Anthropic Admin API key, created by an organization admin.
A workspace API key for each workspace you want to analyze.
An AWS account with AWS Identity and Access Management (IAM) permissions to use AWS Glue, Amazon Athena, Amazon S3, Amazon S3 Tables, AWS Secrets Manager, and AWS Quick.
An IAM role for AWS Glue with access to the secrets, your S3 bucket, and your S3 table bucket (see Part 2).
An S3 bucket for job scripts and reference data.
Part 1: Set up the AWS Glue connector for Anthropic
In this part, you store your Anthropic API keys in AWS Secrets Manager and create the AWS Glue connections that read your organization’s data.
Store your Anthropic API keys
Store each API key in AWS Secrets Manager as a secret with the key apiKey:
{ "apiKey": "<your-anthropic-api-key>" }
Create one secret for the Admin API key and one for each workspace API key you plan to use.
Open AWS Secrets Manager.
Choose Store a new secret and enter your API key.
Figure 2: Storing an Anthropic API key in AWS Secrets Manager
Choose Next and name your new secret.
Optionally, configure automatic rotation.
Afterwards, choose Next and then Store.
Create the connections
On the AWS Glue console, choose Data connections, then Create connection.
For Data source, choose Anthropic.
Figure 3: Choosing Anthropic as the data source in AWS Glue
For Authentication, choose the secret that contains your Admin API key.
Figure 4: Selecting the secret that holds the Admin API key
Name the connection, for example anthropic-admin, and create it.
Repeat the steps with a workspace API key to create a second connection, for example anthropic-workspace.
After you create a connection, choose Test connection to validate the API key. Both Admin and workspace API keys can be validated.
Figure 5: Validating an Anthropic connection with Test connection
Explore and preview data
In the AWS Glue console, you can browse the entities that each connection exposes and preview records and the schema for all the data available through the AWS Glue connector for Anthropic. The following screenshot showcases synthetic data.
Figure 6: Previewing Anthropic entities and schema in the AWS Glue console
Part 2: Build an AI usage lakehouse with Amazon S3 Tables and AWS Glue materialized views
In this part, you turn the Anthropic data from Part 1 into answers to leadership’s three questions. An AWS Glue ETL job reads Anthropic data through the connector, combines it with your business data, and writes Apache Iceberg tables to Amazon S3 Tables. A second AWS Glue job maintains AWS Glue materialized views in the AWS Glue Data Catalog, one for each question, and you query the views with Amazon Athena.
The table bucket organizes the data in four namespaces:
Namespace
Contents
Written by
raw
Anthropic entities, as the connector returns them
ETL job
reference
Business data that you own, loaded from CSV files in Amazon S3
ETL job
curated
Daily fact tables and dimension tables, built from the raw data
ETL job
mart
Materialized views, one for each business question
Materialized view job
To build the pipeline, you complete the following steps.
Create the table bucket and namespaces
Create a table bucket, and then create one namespace for each layer:
aws s3tables create-table-bucket --name amzn-s3-demo-table-bucket
for ns in raw curated reference mart; do
aws s3tables create-namespace \
--table-bucket-arn arn:aws:s3tables:<region>:<account-id>:bucket/amzn-s3-demo-table-bucket --namespace "$ns"
done
On the Amazon S3 console, choose Table buckets and enable Integration with AWS analytics services. The integration adds your table buckets to the AWS Glue Data Catalog under the s3tablescatalog catalog, so AWS Glue and Athena can address this bucket as s3tablescatalog/amzn-s3-demo-table-bucket. This walkthrough uses IAM access control for the integration.
Figure 7: Turning on AWS analytics integration for the table bucket
Upload your business data to Amazon S3
Anthropic data shows what each workspace and API key spends. It doesn’t show which business unit owns a workspace, what the spend produced, or whether the creator of a key still works at the company. That context lives in your own systems, so you create these datasets from your organization’s data. The datasets you need depend on the questions you want to answer. This post uses the following three sample datasets:
Save each dataset as a CSV file with a header row. In your S3 bucket, upload each file to its own folder under a common prefix, and name each folder after its dataset:
Pass itself to AWS Glue. Grant iam:PassRole on the role’s own ARN for glue.amazonaws.com, because AWS Glue stores the role with each materialized view and uses it to refresh the view.
Review the ETL script
The ETL job runs the script anthropic_usage_etl.py. Download anthropic_usage_etl.py and save it on your computer. You upload it when you create the AWS Glue job in a later step.
On each run, the script does the following:
Reads the cost report, usage report, users, workspaces, and API keys through the Admin connection, and message batches and files through any workspace connections that you list. It writes this data unchanged to the raw namespace.
Reads your business data from the Amazon S3 location in the --reference_data_path job parameter and writes it to the reference namespace.
Flattens the usage and cost reports into daily fact tables, converts cost from cents to US dollars, and builds tables of API keys, users, and workspaces in the curated namespace.
Creates any table that doesn’t exist yet and adds columns when the source data gains new fields, so you don’t need to create tables in advance.
The following snippets show three important parts of the script: how it reads data through the connector, how it builds the curated tables, and how it loads new data incrementally.
Read Anthropic data through the connector
The connector reads data directly into Apache Spark DataFrames through CatalogConnectionHelper, a helper library included with AWS Glue. You pass the connection type, the AWS Glue connection name, and the read options. For every read option and the fields that support filter pushdown, see Anthropic connection options. The following example reads the cost report from October 1, grouped by workspace and cost description:
from connectivity.adapter import CatalogConnectionHelper
connector = CatalogConnectionHelper(spark)
def read_entity(entity, connection, filter_predicate=None):
"""Read one Anthropic entity through the AWS Glue connection into a Spark DataFrame."""
options = {"ENTITY_NAME": entity}
if filter_predicate:
options["FILTER_PREDICATE"] = filter_predicate
return connector.read("anthropic", connection, options) # connection type, connection name, options
def read_report(entity, starting_at, group_by):
"""Read a usage or cost report from starting_at, broken down by the group_by dimensions."""
conditions = [f"starting_at = '{starting_at}'"] + [f"group_by = '{field}'" for field in group_by]
report = read_entity(entity, "anthropic-admin", " AND ".join(conditions))
return report.select("starting_at", "ending_at", "results")
cost_report = read_report("cost_report", "2026-10-01T00:00:00Z", group_by=["workspace_id", "description"])
read_report builds the filter predicate from the start date and group_by dimensions, and keeps the report columns that the job uses. The result is a Spark DataFrame, so you can use it with standard Spark transformations without converting it. The job reads cost_report and usage_report with read_report and users, workspaces, and api_keys with read_entity.
Workspace entities, such as message_batches and files, need a workspace API key, so the job reads them through each workspace connection that you list in the --workspace_connections job parameter. The job writes everything that it reads, unchanged, to the raw namespace.
Build the curated tables
The connector returns the cost report as one record per day. That record holds all of the day’s cost lines in a single field, results, as a JSON array. To analyze individual cost lines, the job parses results with a schema for the cost line fields (COST_LINE_SCHEMA) and expands the array, so that each cost line becomes its own row. Anthropic reports cost amounts in cents, so the job converts them to US dollars. Anthropic also reports activity in the Default workspace with an empty workspace_id, so the job fills in the Default workspace ID:
def build_fact_cost_daily(cost_report, default_workspace_id):
"""One row per day, workspace, and cost line, with the amount converted from cents to US dollars."""
return (
cost_report
.withColumn("line", F.explode(F.from_json("results", COST_LINE_SCHEMA)))
.select(
F.to_date("starting_at").alias("cost_date"),
# Anthropic reports Default workspace activity with an empty workspace_id
F.coalesce("line.workspace_id", F.lit(default_workspace_id)).alias("workspace_id"),
"line.description",
"line.model",
"line.cost_type",
"line.token_type",
"line.currency",
(F.col("line.amount").cast("decimal(20,8)") / 100).alias("amount_usd"),
)
.groupBy(*COST_KEYS)
.agg(F.sum("amount_usd").alias("amount_usd"))
)
The job also parses nested fields such as the API key creator, scope, and principal. It writes the following tables to the curated namespace:
Table
Contents
fact_usage_daily
Token usage per day, workspace, API key, and model
fact_cost_daily
Cost in US dollars per day, workspace, and cost line
dim_api_key
API keys with status, workspace, creator, and key type (linked to a user, service account, or legacy)
dim_user, dim_workspace
Organization members and workspaces
Load new data incrementally
The first run loads all data from the date in the --start_date job parameter. Later runs re-read only the last three days, because daily buckets close after midnight UTC and recent days can still change. The job merges those days into the fact tables, so a rerun updates rows instead of duplicating them:
MERGE INTO s3tables.curated.fact_cost_daily t
USING updates s -- the re-read days
ON t.cost_date <=> s.cost_date AND t.workspace_id <=> s.workspace_id
AND t.description <=> s.description AND t.model <=> s.model
AND t.cost_type <=> s.cost_type AND t.token_type <=> s.token_type
AND t.currency <=> s.currency
WHEN MATCHED THEN UPDATE SET *
WHEN NOT MATCHED THEN INSERT *;
The dimension and reference tables are small, so the job replaces them on every run.
Review the materialized view script
The materialized view job runs the script anthropic_usage_mvs.py. Download anthropic_usage_mvs.py and save it on your computer.
The curated tables hold clean usage, cost, and access data, but each leadership question needs joins across several of them and your business data. Instead of repeating those joins in every query and dashboard, the script saves each answer as a materialized view in the mart namespace. A materialized view stores the result of a query as an Iceberg table. When its base tables change, a refresh updates the view, incrementally where possible, instead of recomputing the whole query. Athena and AWS Quick then read the precomputed results, so everyone works from the same numbers.
On each run, the script creates any view that doesn’t exist yet and refreshes the rest. It maintains one view for each leadership question:
Are any active API keys owned by employees who have left?
Add your own views
The script is extensible. Each view is one entry in the VIEWS dictionary: the key is the view name, and the value is the view’s SQL query. To answer a new question, add an entry. For example, the following entry adds a view of daily token usage by workspace and model:
VIEWS = {
# ... the three views in the preceding table ...
# Which models consume the most tokens in each workspace?
"tokens_by_model": f"""
SELECT u.usage_date,
w.name AS workspace,
u.model,
sum(u.uncached_input_tokens) AS uncached_input_tokens,
sum(u.cache_read_input_tokens) AS cache_read_input_tokens,
sum(u.output_tokens) AS output_tokens
FROM {CURATED}.fact_usage_daily u
LEFT JOIN {CURATED}.dim_workspace w ON w.workspace_id = u.workspace_id
GROUP BY 1, 2, 3
""",
}
The next run of the job creates the view, and later runs refresh it. To change the definition of an existing view, set the optional --recreate job parameter to the view name, for example tokens_by_model, for one run. The job drops the view and creates it again with the new definition.
Follow two rules when you write a view definition:
Make definitions deterministic. Functions such as current_date() aren’t allowed, so calculate those values at query time.
Use inline subqueries instead of a WITH clause. In our testing, views that used a WITH clause could be created but failed to refresh.
Create the AWS Glue jobs
Create one AWS Glue job for each script. Both jobs connect to the table bucket with the same job parameter, so prepare its value first.
Prepare the table bucket configuration
The scripts read and write the table bucket through an Apache Spark catalog named s3tables. You configure the catalog with one job parameter, --conf. Copy the following value as a single line, and replace <account-id>, <region>, and amzn-s3-demo-table-bucket with your own values:
The value contains several Spark settings. AWS Glue accepts only one --conf parameter, so the settings are separated by --conf inside the value. With this configuration, the scripts refer to tables as s3tables.<namespace>.<table>, for example s3tables.curated.fact_cost_daily. For details about these settings, see Running ETL jobs on Amazon S3 tables with AWS Glue.
Create the ETL job
On the AWS Glue console, choose ETL jobs, and then choose Script editor.
For Engine, choose Spark. Choose Upload script, select anthropic_usage_etl.py, and choose Create script.
On the Job details tab, for Name, enter anthropic-usage-etl. For IAM Role, choose the role from the prerequisites. For Glue version, choose Glue 6.0.
Expand Advanced properties. Under Connections, choose the Admin connection and each workspace connection that you created in Part 1.
Under Job parameters, choose Add new parameter and add each of the following keys and values:
Key
Value
Purpose
--datalake-formats
iceberg
Adds Apache Iceberg support to the job
--conf
The value that you prepared
Connects the job to the table bucket
--admin_connection
anthropic-admin
Name of the Admin connection
--workspace_connections
{"anthropic-workspace": "Customer Service"}
Optional. Maps each workspace connection to its workspace name. Without it, the job skips message_batches and files.
--reference_data_path
s3://<your-bucket>/<prefix>/
Location of your business data
--start_date
2026-10-01
First day to load on the first run
Choose Save.
Create the materialized view job
On the AWS Glue console, choose ETL jobs, and then choose Script editor.
For Engine, choose Spark. Choose Upload script, select anthropic_usage_mvs.py, and choose Create script.
On the Job details tab, for Name, enter anthropic-usage-mvs. For IAM Role, choose the same role. For Glue version, choose Glue 6.0 (AWS Glue materialized views require AWS Glue 5.1 or later).
Expand Advanced properties. Under Job parameters, add --datalake-formats with the value iceberg, and --conf with the same value as the ETL job. This job reads only from the table bucket, so it doesn’t need connections or other parameters.
On the ETL jobs page, run anthropic-usage-etl. After it succeeds, run anthropic-usage-mvs, which creates the views on its first run and refreshes them on later runs.
To keep the views current, create an AWS Glue workflow that runs the ETL job daily at 06:30 UTC, after Anthropic’s daily buckets close, and then runs the materialized view job. Alternatively, add SCHEDULE REFRESH EVERY 24 HOURS to each CREATE MATERIALIZED VIEW statement so that AWS Glue refreshes the views on a schedule, and schedule only the ETL job.
Answer the business questions with Amazon Athena
After you execute the following Glue scripts, in the Athena query editor, choose the catalog s3tablescatalog/amzn-s3-demo-table-bucket and the database mart. The results in this section come from the demo organization. The business datasets are samples.
Which business units are driving AI spend?
SELECT week_start, business_unit, spend_usd, prev_week_spend_usd
FROM weekly_spend_by_business_unit
WHERE week_start = (SELECT max(week_start) FROM weekly_spend_by_business_unit)
ORDER BY spend_usd DESC;
Is the spend paying off?
SELECT outcome_date, spend_usd, completed_resolutions, qa_score_pct, cost_per_resolution_usd
FROM unit_cost
WHERE business_unit = 'Customer Service'
ORDER BY outcome_date;
Figure 8: Cost per resolution over time for Customer Service
Are any active API keys owned by employees who have left?
SELECT key_name, key_type, workspace, creator_status, last_used, output_tokens
FROM access_review
WHERE review_candidate
ORDER BY output_tokens DESC;
Figure 9: Active API keys owned by employees who have left
The query returns two keys, support-legacy in Customer Service and docproc-batch-legacy in Document Processing. Both are legacy keys, created by an employee who has since left, and both were used the previous day. A departed creator doesn’t mean that a key is misused. It identifies keys whose service ownership should be confirmed, for example by moving the workload to a service-account key, before the old key is disabled.
Part 3: Visualize AI spend and governance in AWS Quick
AWS Quick is a generative AI assistant for work. It helps employees find insights, conduct deep research, automate tasks, and take action across their business applications, bringing chat agents, research, workflow automation, and business intelligence (BI) together in one place. Its BI capability, AWS Quick Sight, turns data into interactive dashboards. With generative BI, you can build a multi-sheet dashboard from a natural language prompt or ask questions of your data in plain language.
Allow AWS Quick to access the table bucket
AWS Quick reads materialized views directly from the table bucket. Before you create a dataset, an AWS Quick administrator allows Quick to access the bucket:
In AWS Quick, open Manage account.
Under Permissions, choose AWS resources.
Select Amazon S3 Tables, choose Select S3 table buckets, select the amzn-s3-demo-table-bucket table bucket, and choose Finish.
Figure 10: Granting AWS Quick access to the table bucket
Without this step, creating the data source fails with a message that AWS Quick doesn’t have permission to access the database.
Create datasets from the materialized views
Create one dataset for each view that the dashboard uses:
Choose Data, then Create dataset, and then Create data source.
Choose Amazon S3 Tables. Enter a data source name, such as anthropic-usage, and the table bucket ARN, for example arn:aws:s3tables:<region>:<account-id>:bucket/amzn-s3-demo-table-bucket. Choose Create data source.
For Namespace, choose mart. Select weekly_spend_by_business_unit and choose Select.
Choose Directly query your data, and then Edit/Preview data. Check the preview and choose Save & publish.
Repeat these steps for unit_cost, and select the anthropic-usage data source that you created instead of creating a new one.
Figure 11: Creating datasets from the materialized views in AWS Quick
Because the datasets query the views directly, the dashboard shows the latest results after each refresh of the materialized views. You don’t need a separate refresh schedule in AWS Quick.
Generate the analysis from a prompt
Instead of building each visual by hand, describe the review that leadership wants and let AWS Quick generate the analysis. On the Analyses page, choose Generate analysis. Choose Add data, select both datasets, and enter a prompt such as the following:
Create a simple weekly AI spend review for retail leadership, titled "Weekly AI Spend Review", with two sheets and no more than four visuals per sheet.
Spend sheet: each row of weekly_spend_by_business_unit is one business unit in one week. Filter the whole sheet to the most recent week_start only, never sum across weeks. Show a KPI of total spend_usd for that week compared with total prev_week_spend_usd, a horizontal bar chart of spend_usd by business_unit sorted from highest to lowest, and a bar chart of change_usd by business_unit. Add a business unit filter control.
Value sheet: Customer Service only, by outcome_date. Show cost_per_resolution_usd as US dollars with 4 decimal places in a KPI (average) and a line chart, a line chart of qa_score_pct, and a combo chart with spend_usd as bars and completed_resolutions as a line.
Keep sheet descriptions to one short plain sentence.
Figure 12: Generating the analysis from a natural language prompt
Choose Preview analysis outline. AWS Quick reviews the columns and statistics of each dataset and proposes a plan with filter controls, sheets, and the visuals on each sheet. Review the plan, choose Edit if you want to change it, and then choose Generate.
Figure 13: Previewing the proposed analysis outline
Describe the shape of your data in the prompt. The weekly_spend_by_business_unit view has one row per business unit per week. When our first prompt only asked to compare spend with the previous week, the generated analysis added all weeks together. Asking for the most recent week only fixed it.
Review the dashboard
The Spend sheet shows which business units are driving AI spend.
Figure 14: The Spend sheet showing AI spend by business unit
The Value sheet shows whether the spend is paying off.
Figure 15: The Value sheet showing whether the spend is paying off
Publish and share the dashboard
Choose Publish to create a dashboard from the analysis, and share it with leadership. Viewers can filter and explore the dashboard without access to the analysis or the datasets behind it. To have the review arrive before the weekly meeting, schedule an email report from the dashboard.
Go further
This dashboard answers leadership’s questions with two datasets and a short prompt, but the same connector data supports much more. For advanced use cases, use the Agent Toolkit for AWS with your preferred AI coding agent to build a richer version of this solution through natural language. The following dashboard compares the price per million tokens across models, shows how much prompt caching saves, and lists the API keys to revoke. We generated the entire data pipeline and this dashboard with Kiro and the Agent Toolkit for AWS.
Figure 16: A richer dashboard built with the Agent Toolkit for AWS
Considerations
Report time windows: Set starting_at for every usage and cost read. Daily buckets include only completed days. Use bucket_width = '1h' for the current day.
API key scope: An Admin API key reads organization data but not workspace data such as models, message batches, or files, and a workspace API key reads only its workspace. Use one connection per key, and one set of connections per Anthropic organization.
Rate limits: The Anthropic Admin API limits request rates. Use bounded time windows and scheduled incremental reads rather than large historical reads.
AWS Glue materialized views: AWS Glue materialized views require AWS Glue 5.1 or later and iam:PassRole for the role that refreshes them. Definitions must be deterministic, and in our testing views with a WITH clause failed to refresh, so use inline subqueries.
Security: Grant the AWS Glue role read access only to the secrets it needs, rotate Anthropic API keys regularly, and restrict access to curated tables.
Clean up
To avoid ongoing charges, delete the resources you created: the AWS Glue jobs, workflow, and connections. The Secrets Manager secrets. The materialized views, tables, namespaces, and table bucket in Amazon S3 Tables. The reference data and scripts in Amazon S3. You can also remove the dashboards and datasets that you created in AWS Quick. Consider revoking any Anthropic API keys you created for this walkthrough.
Conclusion
In this post, we showed how to use the AWS Glue connector for Anthropic to bring Anthropic usage, cost, and access data into AWS, store it as Apache Iceberg tables in Amazon S3 Tables, and keep business-ready results current with materialized views. With Amazon Athena, the retailer can see which business units drive AI spend, whether that spend pays off, and which API keys need an ownership review. Using AWS Quick, we used natural language to create dashboards.
To get started, see Anthropic connection options in the AWS Glue Developer Guide. To browse the other connection types that AWS Glue supports, including the new native connectors for SaaS applications, see Available connections.
The AWS Prescriptive Guidance topic Optimize user-defined functions explains that Python UDFs in PySpark can degrade performance because data must be serialized between the Java Virtual Machine (JVM) and the Python runtime. It recommends, in order of preference: use built-in Spark SQL functions, implement UDFs in Scala or Java, or use Apache Arrow-based UDFs (also known as vectorized or pandas UDFs) for vectorized workloads.
That guidance is based on a concise example: the operation a + b over 10 million rows, comparing a standard Python UDF, a vectorized UDF, and Spark SQL. In this post we extend that example to answer a few practical questions we hear from customers:
Does the ranking hold as data volume grows, from 10 million to 100 million rows?
Does it hold for a more compute-intensive operation, not only a + b?
AWS Glue 6.0 (Apache Spark 4.1.1) adds two newer Arrow-based options: the Arrow-optimized Python UDF (useArrow=True) and the native Arrow UDF (arrow_udf, from Apache Spark 4.1.0). Where do they fit relative to a vectorized (pandas) UDF?
Can we attribute the difference to the data transport, the computation, or both?
We ran each variant as an AWS Glue 6.0 job and share the results, the methodology, and a controlled experiment that clarifies why the vectorized UDF performs the way it does.
Solution overview
We ran a parameterized benchmark harness as an AWS Glue 6.0 job. The job generates a Parquet dataset once, writes it to Amazon Simple Storage Service (Amazon S3), and then runs each UDF variant against the same files, so that every approach reads identical data. We measured across three data volumes (10M, 50M, and 100M rows, where M = million) and three workloads of increasing per-row cost.
The following image shows the workflow of the benchmark.
Figure 1: Benchmark workflow running each UDF variant as an AWS Glue 6.0 job
The high-level steps are:
Set up the prerequisite AWS Identity and Access Management (IAM) role and Amazon Simple Storage Service (Amazon S3) bucket.
Deploy and run the AWS Glue 6.0 job, which generates the dataset and runs the variants.
Review the results, emitted to the job logs and optionally written back to Amazon S3.
The approaches we compared
All variants compute the same result. They differ in how data crosses the JVM–Python boundary and how the per-row logic runs.
Approach
Transport (JVM–Python)
Computation
standard Python UDF
Pickle, one row at a time
Python, per row
Arrow-optimized Python UDF (useArrow=True)
Apache Arrow, columnar batch
Python, per row
vectorized UDF (pandas UDF)
Apache Arrow, columnar batch
NumPy, per batch (through a pandas conversion)
native Arrow UDF (arrow_udf, Apache Spark 4.1)
Apache Arrow, columnar batch
PyArrow compute, per batch (no pandas conversion)
Spark SQL (built-in)
None — runs on the JVM
JVM, per batch
The vectorized UDF and the Arrow-optimized Python UDF both use Apache Arrow for transport, so both show ArrowEvalPython in the physical plan. The difference is the computation:
A vectorized UDF (pandas UDF) receives a pandas.Series (a batch of rows), so the computation can be expressed with NumPy and runs on the whole batch in native code. It involves a pandas conversion on top of Arrow.
An Arrow-optimized Python UDF is a scalar UDF: the function receives one value per call. Arrow makes the transport efficient, but the Python code still runs one row at a time.
A native Arrow UDF (the arrow_udf decorator, introduced in Apache Spark 4.1 and available in AWS Glue 6.0) receives and returns a pyarrow.Array and computes with PyArrow compute kernels. It operates directly on Arrow data, without the pandas conversion that a vectorized UDF performs.
The following image summarizes how each variant crosses the boundary.
Figure 2: How each UDF variant crosses the JVM to Python boundary
The code difference reflects that distinction. The registration shape is similar, but the computation differs:
# Arrow-optimized Python UDF: scalar function, Arrow transport
op = udf(lambda a, b: math.sqrt(a*a + b*b) * math.sin(a), DoubleType(), useArrow=True)
# vectorized UDF (pandas UDF): batch function, Arrow transport + NumPy computation
@pandas_udf(DoubleType())
def op(a, b): # a, b are pandas.Series (a batch of rows)
return np.sqrt(a*a + b*b) * np.sin(a)
# native Arrow UDF: batch function, Arrow transport + PyArrow compute (no pandas)
@arrow_udf("double")
def op(a, b): # a, b are pyarrow.Array (a batch of rows)
return pc.multiply(pc.sqrt(pc.add(pc.multiply(a, a), pc.multiply(b, b))), pc.sin(a))
Environment and setup
Runtime: AWS Glue 6.0 (Apache Spark 4.1.1, Python 3.13, Scala 2.13), 10 × G.1X executors plus the driver, in the US East (N. Virginia) AWS Region (us-east-1).
Data: A Parquet dataset with two bigint columns (a, b), written once to Amazon S3 and read back by every variant so all approaches read identical files.
Volumes: 10M, 50M, and 100M rows. Two dimensions are combined in every run: the workload (the per-row operation) and the query shape (how that operation is aggregated). Each of the three workloads was run under both query shapes, for every approach and volume.
Workloads (the per-row operation)
We chose three operations of increasing cost, to show how the results change as the per-row work shifts from “almost nothing” to “Python-only.”
Workload
Per-row operation
Why it’s included
Applicable approaches
arith
a + b
The operation used in the AWS Prescriptive Guidance example. The computation is trivial, so serialization dominates the runtime.
All five
mathheavy
sqrt(x² + y²) · sin(x) + ln(y)
Transcendental math with a meaningful per-row cost. It can be written in SQL, with PyArrow compute kernels, in NumPy, and in scalar Python, so all five approaches apply and compete.
All five
pyheavy
A bounded iterative loop (Collatz-style step count)
Data-dependent control flow that can’t be expressed in SQL or with PyArrow compute kernels. This is the case where a Python UDF is the only option.
Python UDF approaches only (no Spark SQL, no native Arrow UDF)
The progression matters. arith isolates the transport cost. mathheavy adds real computation, so vectorization can help. All five approaches apply, including the native Arrow UDF, because the math maps onto PyArrow compute kernels. pyheavy is the opposite extreme: an iterative loop that maps onto neither SQL nor PyArrow compute kernels, so Spark SQL and the native Arrow UDF don’t apply and only the Python-based UDFs remain.
Query shapes (how the operation is aggregated)
Each workload is measured under two query shapes, because they exercise different execution paths in the engine:
Streaming:sum(op(a, b)) — A full scan of every row, reduced to a single value. This isolates the per-row cost with minimal aggregation overhead.
Stateful:GROUP BY cast(op(a, b) AS bigint) % 1,000,000 — A full scan followed by a high-cardinality aggregation (about one million groups), which adds a shuffle and a large hash table.
Both shapes apply to all three workloads. To keep the tables readable, the following results report the streaming shape. We measured the stateful shape too and found the same ranking, with representative stateful figures given in the Results section.
Methodology
Two decisions had a material effect on the results.
Warm-up and best-of-N. The first run of each variant is dominated by cluster, JVM, and Python worker start-up. We ran one warm-up iteration that we discard, then N timed iterations, and report the best (and mean).
Reading fresh on every iteration. Our first attempt reused a cached DataFrame, and Spark cached the Parquet blocks and pruned the plan for a scalar count(). As a result the UDF timings didn’t scale with data size, and Spark SQL appeared slower than the UDFs. That was the opposite of the expected result. We corrected this by clearing the cache and re-reading the Parquet on every timed iteration, and by using sum(...) so the optimizer can’t prune the per-row work.
def bench(name, fn, repeat, warmup, pre=None):
for _ in range(warmup):
if pre: pre()
fn() # discarded
times = []
for _ in range(repeat):
if pre: pre() # e.g. spark.catalog.clearCache()
t = time.perf_counter(); fn(); times.append(time.perf_counter() - t)
return {"best_sec": min(times), "mean_sec": sum(times) / len(times)}
After this correction, the ranking matched the AWS Prescriptive Guidance recommendation and remained consistent across volumes. In short: if a UDF benchmark doesn’t scale with row count, it’s likely measuring the cache rather than the computation.
Results
The following tables report the streaming query shape for each workload. We verified the stateful shape as well, and it produces the same ranking. For example, on mathheavy at 100M rows the stateful order matched streaming (Spark SQL 1.59 seconds, vectorized UDF 4.22 seconds, Arrow-optimized Python UDF 11.02 seconds, and standard Python UDF 14.33 seconds). The pyheavy table that follows shows the streaming and stateful columns side by side. The stateful figures run somewhat slower than streaming because of the added shuffle and hash aggregation, but the relative order of the approaches doesn’t change.
Workload 1: arith (a + b)
Best of seven iterations, warm-up excluded, streaming:
Approach
10M
50M
100M
Relative to standard Python UDF (100M)
Spark SQL
0.53s
0.75s
0.99s
11.8× faster
native Arrow UDF (arrow_udf)
0.76s
1.79s
2.81s
4.2× faster
vectorized UDF (pandas UDF)
0.90s
1.98s
3.13s
3.7× faster
Arrow-optimized Python UDF
1.47s
4.82s
8.94s
1.3× faster
standard Python UDF
2.01s
6.20s
11.68s
baseline
The recommended ranking holds, and the advantage of the vectorized UDF over the standard Python UDF widens with volume (from about 2.2× at 10M to 3.7× at 100M), because the standard Python UDF’s per-row serialization cost grows with the number of rows. For this trivial operation the native Arrow UDF and the vectorized UDF are close, because there is little computation to vectorize. Their advantage over the scalar approaches comes mainly from the columnar transport.
Workload 2: mathheavy
Best of 7 iterations, streaming:
Approach
10M
50M
100M
Spark SQL
0.52s
0.84s
1.22s
native Arrow UDF (arrow_udf)
0.72s
1.87s
3.13s
vectorized UDF (Pandas UDF)
0.79s
2.21s
3.83s
Arrow-optimized Python UDF
1.57s
5.79s
11.01s
standard Python UDF
1.80s
7.19s
13.82s
Among the UDF approaches, the native Arrow UDF was the fastest. It ran about 18 percent faster than the vectorized UDF at 100M (3.13 seconds versus 3.83 seconds) because it computes on Arrow data directly and avoids the pandas conversion. The timings scale approximately linearly across 10M, 50M, and 100M, and the ranking is stable at every volume. The following chart shows the approaches across volumes on a log-log scale.
Figure 3: Runtime of each approach on the mathheavy workload across data volumes, on a log-log scale
Workload 3: pyheavy (no SQL equivalent)
This workload runs a per-row iterative loop with no closed-form equivalent. For each row it derives an integer from a and b and repeatedly applies the Collatz step (halve if even, otherwise 3n + 1) until the value reaches 1, counting the number of steps. To keep every row’s runtime predictable, the loop is bounded: it stops after at most 1,000 iterations even if it has not reached 1, so no single row can dominate the benchmark.
def collatz_steps(a, b): # a, b are scalars (one row per call)
n = int((a ^ b) % 100000) + 1
steps = 0
while n != 1 and steps < 1000: # bounded: at most 1,000 iterations per row
n = n // 2 if n % 2 == 0 else 3 * n + 1
steps += 1
return steps
This kind of data-dependent control flow can’t be expressed as a SQL scalar expression or with PyArrow compute kernels, so neither Spark SQL nor the native Arrow UDF applies, and only the Python-based UDF approaches are compared. The table shows both query shapes, at 10M, 50M, and 100M rows, to illustrate that the ranking is consistent across shapes and scales:
Approach
10M streaming
10M stateful
50M streaming
50M stateful
100M streaming
100M stateful
vectorized UDF (pandas UDF)
0.67s
0.72s
1.76s
1.85s
2.99s
3.01s
Arrow-optimized Python UDF
1.33s
1.36s
4.85s
4.86s
8.98s
8.71s
standard Python UDF
1.50s
1.55s
6.05s
6.28s
11.42s
11.73s
We report pyheavy up to 100M rows. Because Spark SQL and the native Arrow UDF don’t apply here, the only remaining options are the Python-based UDFs, whose timings scale near-linearly and whose relative order is already stable across both shapes by 100M.
This workload represents the case where a UDF is unavoidable. Examples include an iterative algorithm or a call into a Python library with no SQL counterpart that doesn’t map onto PyArrow compute kernels either. Here the vectorized UDF is the most effective available option: about 2.2× faster than the standard Python UDF at 10M, widening to about 3.8× at 100M.
A controlled experiment: Transport or computation?
The vectorized UDF consistently outperforms the Arrow-optimized Python UDF. To test whether the difference comes from the transport (both use Arrow) or the computation (only the vectorized UDF uses NumPy on a batch), we constructed the missing combination (NumPy computation with pickle transport, no Arrow) using RDD.mapPartitions.
Figure 4: Transport and computation compared as a 2×2 experiment
The NumPy-with-pickle variant was the slowest of all (21.07 seconds at 100M, slower than the standard Python UDF at 13.82 seconds). The reason is that forcing pickle transport requires leaving the DataFrame API for RDD.mapPartitions, which changes two things at once. It materializes each row as a Python object before a NumPy array can be built, and it bypasses the optimized DataFrame execution engine that the vectorized UDF benefits from.
The practical conclusion is that the benefit of a vectorized UDF is not the Arrow transport in isolation. It’s Apache Arrow integrated into the vectorized DataFrame execution path. That path combines columnar transport and NumPy computation. Reproducing only the NumPy portion outside that path doesn’t yield the same benefit.
Code comparison: Arrow-optimized Python UDF and vectorized UDF
These two approaches are often confused: both use Apache Arrow for transport and both show ArrowEvalPython in the physical plan, so it’s worth seeing them side by side. The following two definitions compute the same mathheavy operation. The registration is almost identical. The difference is the function body and the type of its arguments.
The following code is an Arrow-optimized Python UDF (useArrow=True), where the function receives scalar values and runs once per row:
import math
from pyspark.sql.functions import udf
from pyspark.sql.types import DoubleType
def op(a, b): # a, b are scalars (one row per call)
x = float(a % 100000) + 1.0
y = float(b % 100000) + 1.0
return math.sqrt(x * x + y * y) * math.sin(x) + math.log(y)
# Arrow transport, scalar Python computation
op_arrow = udf(op, DoubleType(), useArrow=True)
spark.udf.register("op_arrow", op_arrow)
df.selectExpr("sum(op_arrow(a, b)) AS r").collect()
The following code is a vectorized UDF (pandas UDF), where the function receives a pandas.Series (a batch) and computes with NumPy over the whole batch:
import numpy as np
from pyspark.sql.functions import pandas_udf
from pyspark.sql.types import DoubleType
@pandas_udf(DoubleType())
def op_pandas(a, b): # a, b are pandas.Series (a batch of rows)
x = (a % 100000).astype("float64") + 1.0
y = (b % 100000).astype("float64") + 1.0
return np.sqrt(x * x + y * y) * np.sin(x) + np.log(y) # NumPy, whole batch
spark.udf.register("op_pandas", op_pandas)
df.selectExpr("sum(op_pandas(a, b)) AS r").collect()
The following code is a native Arrow UDF (arrow_udf), where the function receives and returns a pyarrow.Array and computes with PyArrow compute kernels, operating directly on Arrow data with no pandas conversion:
import pyarrow as pa
import pyarrow.compute as pc
from pyspark.sql.functions import arrow_udf
@arrow_udf("double")
def op_native(a, b): # a, b are pyarrow.Array (a batch of rows)
x = pc.add(pc.cast(pc.subtract(a, pc.multiply(pc.divide(a, 100000), 100000)), pa.float64()), 1.0)
y = pc.add(pc.cast(pc.subtract(b, pc.multiply(pc.divide(b, 100000), 100000)), pa.float64()), 1.0)
return pc.add(pc.multiply(pc.sqrt(pc.add(pc.multiply(x, x), pc.multiply(y, y))), pc.sin(x)), pc.ln(y))
spark.udf.register("op_native", op_native)
df.selectExpr("sum(op_native(a, b)) AS r").collect()
The Arrow-optimized Python UDF and the vectorized UDF differ in two lines that matter:
Argument type – In the Arrow-optimized UDF, a and b are scalars, so the body uses math.sqrt and math.sin and runs once per row. In the vectorized UDF, a and b are pandas.Series, so the body uses np.sqrt and np.sin and runs once per batch.
Where the computation runs – The Arrow-optimized UDF still executes Python per row. The vectorized UDF executes the batch in NumPy’s native code.
This difference in where the computation runs is what separates the three at scale. On the mathheavy workload at 100 million rows, the Arrow-optimized UDF ran in 11.01 seconds, the vectorized UDF in 3.83 seconds, and the native Arrow UDF fastest at 3.13 seconds. The native Arrow UDF edges ahead because it vectorizes the computation through PyArrow compute kernels without the pandas conversion the vectorized UDF performs. However, it requires the logic to be expressible with those kernels, where the vectorized UDF remains the more flexible choice.
Recommendations
These results align with the AWS Prescriptive Guidance recommendation and add a few practical points:
Prefer built-in Spark SQL functions when the operation can be expressed in SQL – The computation runs on the JVM, and the advantage grows with data volume.
When a UDF is required and the logic can be expressed with PyArrow compute kernels, consider a native Arrow UDF (arrow_udf) – In our tests it was the fastest UDF approach, because it vectorizes the computation on Arrow data without a pandas conversion. It’s available in AWS Glue 6.0 (Apache Spark 4.1).
Otherwise, use a vectorized UDF (pandas UDF) – It outperformed the standard Python UDF by 2.2–3.8× in our tests. It’s the more flexible option when the logic is easier to express with pandas or NumPy than with PyArrow compute kernels.
Arrow-optimized Python UDFs (useArrow=True) improve the transport but not the computation – They are faster than the standard Python UDF, but a vectorized or native Arrow UDF is faster whenever the per-row work is non-trivial. Consider the Arrow-optimized Python UDF when you want a minimal change to an existing scalar UDF.
Stay in the DataFrame API to keep Arrow’s benefit – As the controlled experiment showed, the speedup doesn’t come from Arrow serialization alone. It comes from Arrow integrated into the vectorized DataFrame execution path. Applying the same NumPy logic through RDD.mapPartitions was the slowest approach of all, because it leaves that path. Implement vectorized logic as a vectorized or native Arrow UDF within the DataFrame API rather than dropping to the RDD API.
For iterative or data-dependent logic (thepyheavycase), the vectorized UDF is the fallback – When the operation maps onto neither SQL nor PyArrow compute kernels, both Spark SQL and the native Arrow UDF are unavailable, and among the remaining Python UDF approaches the vectorized UDF was the most efficient.
Decide whether the rewrite is worth the effort – Moving a scalar UDF to a vectorized or native Arrow UDF is a small code change, but it still has to be written and tested. As a rule of thumb, it pays off when the per-row work is non-trivial and the data is large or the job runs often. The speedup (and the per-second cost saving) scales with row count and with how frequently the job runs, while the rewrite is a one-time cost. For a trivial operation on a small, infrequent dataset, the standard Python UDF might be perfectly adequate. For a compute-heavy transform on hundreds of millions of rows that runs daily, the rewrite typically repays itself in the first few runs.
The exact numbers depend on your cluster – All results here use a fixed configuration (10 × G.1X workers) on AWS Glue 6.0. The ranking of approaches is a property of how each UDF crosses the JVM–Python boundary and is not expected to change with cluster size. However, the absolute timings and any crossover with alternatives will shift with worker count, worker type, and data layout. Treat the figures as a guide to relative behavior and validate against your own configuration.
Methodology affects the outcome – Warm-up handling and cache management changed our ranking. A UDF benchmark whose timings don’t scale with row count is likely measuring the cache.
Conclusion
The choice of UDF strategy has a measurable and recurring impact on both runtime and cost. On our compute-intensive workload at 100 million rows, the gap between the fastest UDF approach (the native Arrow UDF at 3.13 seconds) and the standard Python UDF (13.82 seconds) was about 4.4×, for identical output. Because AWS Glue bills by the second, that difference translates directly into spend on every job run.
These results extend the AWS Prescriptive Guidance recommendation with volume scaling from 10 million to 100 million rows, a compute-intensive workload, and the newer Arrow-based UDF options available in AWS Glue 6.0 (Apache Spark 4.1). As a methodology note, warm-up handling and cache management materially affected the ranking. A UDF benchmark whose timings don’t scale with row count is likely measuring the cache rather than the computation.
Extract, transform, and load (ETL) pipelines break silently. Schema drift, missing fields, and type mismatches corrupt downstream analytics. The typical fix is manual: detect the error, triage it, patch the record, update the code, redeploy. As data volumes grow, this detect-triage-fix-deploy cycle doesn’t scale. A self-healing pipeline built on Amazon Bedrock AgentCore, a platform to build, connect, and optimize agents at scale with any framework or model, can repair itself.
The self-healing pipeline in this post fixes its own data, persists the corrections, and can propose pull requests to help prevent the same errors from recurring (optional, requires repository credentials).
In this post, you will build a self-healing ETL pipeline that uses AWS Glue and Amazon Bedrock AgentCore. The pipeline automatically corrects bad records using domain knowledge and writes them back to the data lake. When you configure the optional repository integration, it also generates code reviews with recommended fixes. The result is a closed loop on data quality that reduces the need for human intervention. You’ll cover the architecture, deploy the infrastructure with the AWS Cloud Development Kit (AWS CDK), and test the data correction workflow with sample data, including a before-and-after record comparison.
Amazon Bedrock Knowledge Bases with pre-computed correction strategies stored in Amazon S3 Vectors, a capability of Amazon Simple Storage Service (Amazon S3), reduce the time to create and deploy corrective measures. A manual workflow involves an engineer diagnosing the error pattern, writing a fix, and deploying it through a release cycle. This system applies known corrections within seconds of detection. It also surfaces new patterns to the team with full context, including a proposed code fix. When records fail validation, automatic correction keeps them flowing to consumers instead of sitting in a dead-letter queue awaiting manual triage. Confidence threshold and human-notification fallback provide built-in oversight governing this autonomous agentic behavior. For additional responsible AI controls, consider Amazon Bedrock Guardrails, grounding, and content filtering.
The problem: Data quality at scale
Consider a hypothetical weather data system ingesting National Oceanic and Atmospheric Administration (NOAA) records across 15 schema types: temperature, precipitation, wind, pressure, humidity, visibility, cloud cover, solar radiation, and more. In a system like this, sensor failures, schema drift, and producer bugs can cause a meaningful percentage of records to fail validation.
Today, that means:
Engineers get paged about bad data hours after it arrives.
Someone manually inspects the error, determines the fix, and patches the record.
A developer traces the root cause back to upstream code and submits a fix.
The pipeline is redeployed, until the next variant of the same error appears.
Each step requires a person, a tool, and a context switch. A self-healing pipeline captures that correction knowledge and applies it automatically the next time a similar error appears.
Prerequisites
To implement this pattern, you need:
An AWS account with permissions to create resources in the following services:
Amazon Simple Notification Service (Amazon SNS), AWS Secrets Manager, AWS Identity and Access Management (IAM).
Amazon Bedrock model access enabled for Anthropic Claude (agent reasoning) and Amazon Titan Embeddings V2 (knowledge base indexing) in your target AWS Region. For model availability by Region, refer to supported models by AWS Region in Amazon Bedrock (https://docs.aws.amazon.com/bedrock/latest/userguide/models-regions.html).
Finch or Docker for building agent container images (CDK builds ARM64 images through CodeBuild, but local testing requires a container runtime).
Familiarity with Amazon S3 data lake patterns and basic understanding of multi-agent orchestration concepts.
The sample implementation uses the Strands Agents SDK for agent development and AWS CDK (Python) for infrastructure. Deploy all resources within a single AWS Region.
Solution overview
This solution replaces that manual cycle with a multi-agent system that automates three things: correct the data, persist the fix, and remediate the code. The following diagram shows the complete architecture:
Figure 1: End-to-end architecture of the self-healing ETL pipeline
Here’s how data flows through the pipeline:
Ingest – Data producers write weather records directly to an Amazon S3 raw landing bucket, organized by schema type under the raw/ prefix. Records are preserved unmodified.
Transform – An AWS Glue ETL job validates each record against its declared weather schema and writes valid records to the transformed zone. Records that fail validation are classified by error type (missing field, type mismatch, schema violation, invalid format) and routed to the AgentCore system.
AI correction – A four-agent system on Bedrock AgentCore handles the error:
Orchestrator agent coordinates the sequential workflow: correction to persistence to remediation.
Data correction agent queries domain knowledge to find and apply a high-confidence fix.
Data persistence agent writes the corrected record back to the data lake.
Code remediation agent identifies the root cause and proposes a pull request to help prevent recurrence.
Notify – When no high-confidence correction is found, the orchestrator publishes a notification through Amazon Simple Notification Service (Amazon SNS) for manual intervention rather than applying a bad fix.
How validation and error routing work
The AWS Glue ETL job acts as the quality gate. It validates each record against a dispatcher that maps each of the 15 schema types to a dedicated validator. Each validator checks required fields, data types, enum values, and numeric constraints:
def validate_record(record: dict) -> dict:
"""Validate a single weather record against its declared schema_type."""
schema_type = record.get("schema_type")
if schema_type not in VALID_SCHEMA_TYPES:
return {"valid": False, "error_type": "invalid_format",
"error_details": f"Unknown schema_type: '{schema_type}'"}
data = record.get("data")
validator = SCHEMA_VALIDATORS.get(schema_type)
error_details = validator(data)
if error_details:
# Validators emit only three message shapes, so once missing-field and
# type-mismatch are ruled out, the else is always a constraint/enum/range failure
if "Missing required field" in error_details:
error_type = "missing_field"
elif "Type mismatch" in error_details:
error_type = "type_mismatch"
else:
error_type = "schema_violation"
return {"valid": False, "error_type": error_type,
"error_details": error_details}
return {"valid": True, "error_type": None, "error_details": None}
When a record fails, the job packages it as an error record, preserving the original payload, the classified error type, and the validation details. It then routes the error to the AgentCore orchestrator through the InvokeAgentRuntime API. This is the handoff point where the pipeline stops being a passive data mover and becomes an active self-healing system.
Multi-agent orchestration with Bedrock AgentCore
The orchestrator agent coordinates the entire correction workflow. It receives an error record from the AWS Glue ETL job and drives a sequential path through the specialized agents, degrading gracefully to a human notification when it can’t correct with confidence of at least 70 percent. If a step fails, it stops rather than propagating bad data downstream. The following diagram shows that flow and how each agent connects to its knowledge sources and outputs:
Figure 2: Multi-agent orchestration workflow on Amazon Bedrock AgentCore
The diagram shows the orchestrator receiving an error record from AWS Glue and invoking the correction agent, which draws on the Amazon Bedrock knowledge base and the S3 correction files. The orchestrator then checks the correction’s confidence against the threshold: if it clears, the orchestrator routes the record to the persistence agent (which writes to both data lake zones) and the remediation agent (which opens a repository pull request). If it falls short, the orchestrator sends the record to Amazon SNS for manual review.
Each agent is a containerized application built with the Strands Agents SDK and deployed as an AgentCore runtime, a capability of Amazon Bedrock AgentCore.
The orchestrator doesn’t contain correction logic itself. It delegates to specialized agents and makes routing decisions based on their responses. This separation means you can update correction strategies without touching orchestration logic. You can also swap in a different persistence backend without affecting the correction agent.
Two-source correction: Breadth meets precision
The correction agent’s job is to find the right fix with high confidence. It uses two complementary knowledge sources:
Amazon Bedrock Knowledge Bases. The agent sends a natural language query describing the error to a knowledge base backed by Amazon S3 Vectors and Amazon Titan Embeddings V2. Amazon Bedrock Knowledge Bases provides fully managed Retrieval Augmented Generation (RAG) capabilities. In this case the knowledge base provides semantic search over indexed domain documents (NOAA data guides, schema definitions, error pattern catalogs) and returns ranked results with relevance scores.
Amazon S3 Vectors. In parallel, the agent does a direct lookup for a pre-computed correction strategy at correction/{schema_type}/{error_type}.json. These files contain specific fix instructions with confidence scores for known error combinations:
{
"correction_strategy": "For missing temperature fields, check if the complementary unit field is present (celsius/fahrenheit) and compute the missing value using the conversion formula.",
"confidence": 0.85
}
The agent compares both results and picks whichever has the higher confidence score. If the selected strategy meets the threshold (default 0.7), the correction is applied. If not, the orchestrator sends an SNS notification for manual intervention.
This design gives you:
Breadth – The knowledge base can reason about novel error patterns using domain knowledge from indexed documents, even for combinations it hasn’t seen before.
Precision – S3 Vectors provide instant, high-confidence fixes for known combinations without requiring Amazon Bedrock model inference.
Graceful degradation – If neither source returns a confident answer, the system notifies humans rather than applying a bad fix.
The correction agent decides which fix to apply by weighing two knowledge sources against a confidence threshold. The following flowchart shows that decision logic, with example confidence scores:
Figure 3: Two-source correction decision flow with a confidence threshold
The flowchart shows the correction agent querying the Amazon Bedrock knowledge base and the S3 correction files in parallel, then selecting the higher-confidence strategy (for example, an S3 score of 0.85 over a knowledge base score of 0.78). If the selected score meets the 0.7 threshold, the agent applies the correction and returns the corrected record. If it falls short, the agent returns a failure. This triggers an Amazon SNS notification for manual review.
Closing the loop: Automated code remediation
Most data quality systems stop at fixing the record. This pipeline goes further: the remediation agent traces the error back to its source and proposes a code fix.
After a successful correction, the orchestrator invokes the code remediation agent, which:
Reads the source repository – Connects to the repository using credentials stored in AWS Secrets Manager.
Analyzes root cause – Correlates the error type, schema type, and correction applied to identify which upstream code produced the bad data.
Generates a code change – Produces recommended changes that preserve existing logic (it does not recommend disabling validation or removing functionality).
Submits a pull request – Uses GitHub MCP Server to create a branch, commits the changes, and opens a pull request with the root cause analysis in the description.
This means recurring errors get fixed at the source rather than only patched in the data lake. Over time, the pipeline’s error rate decreases as upstream code improves.
The data lake: Three zones, one truth
The S3 data lake uses prefix-based organization across three zones. Downstream consumers see complete data for processed records, whether a record was valid on first pass or corrected by the agents:
Zone
Purpose
Written By
raw/
Unmodified original records (audit trail)
Data producers
transformed/
Validated, schema-conformant records
Glue ETL Job + Persistence Agent
corrected/
Corrected records with correction metadata
Persistence Agent
The persistence agent writes corrected records to both zones. The corrected zone provides auditability, capturing what was wrong and how it was fixed. The transformed zone gives downstream consumers a complete dataset without needing to union multiple paths.
Deploy the pipeline
With the architecture understood, deploy the pipeline. The complete sample implementation is available in the GitHub repository. The entire system is defined in AWS CDK (Python). A single cdk deploy command provisions all infrastructure, builds container images through CodeBuild, creates the knowledge base, and sets up the AgentCore runtime resources.
Step 1: Clone the repository and install dependencies
Deploy all stacks with a single command. CDK handles dependency ordering, container image builds, knowledge base creation, and runtime provisioning automatically:
The stacks pass resources to each other through constructor arguments in app.py. For example, the AgentCore runtime stack receives the IAM roles and ECR repository URIs from the AgentCore stack. It also receives the knowledge base ID from the knowledge base stack:
# app.py: cross-stack wiring
agentcore_stack = AgentCoreStack(
app,
"WeatherAgentCoreStack",
notification_email=config["notification_email"],
git_repo_url=config["git_repo_url"],
knowledge_base_id=knowledge_base_stack.knowledge_base.attr_knowledge_base_id,
correction_vectors_bucket=knowledge_base_stack.correction_vectors_bucket.bucket_name,
persistence_vectors_bucket=knowledge_base_stack.persistence_vectors_bucket.bucket_name,
corrected_bucket=data_lake_stack.output_bucket.bucket_name,
transformed_bucket=data_lake_stack.output_bucket.bucket_name,
log_retention_days=config["log_retention_days"],
env=env,
)
# Runtime stack deploys last, after CodeBuild pushes the agent images to ECR
runtime_stack = AgentCoreRuntimeStack(
app,
"WeatherAgentCoreRuntimeStack",
agent_roles=agentcore_stack.agent_roles,
ecr_repo_uris={name: repo.repository_uri for name, repo in agentcore_stack.ecr_repos.items()},
notification_topic_arn=agentcore_stack.notification_topic.topic_arn,
git_secret_arn=agentcore_stack.git_secret.ref,
knowledge_base_id=knowledge_base_stack.knowledge_base.attr_knowledge_base_id,
correction_vectors_bucket=knowledge_base_stack.correction_vectors_bucket.bucket_name,
persistence_vectors_bucket=knowledge_base_stack.persistence_vectors_bucket.bucket_name,
corrected_bucket=data_lake_stack.output_bucket.bucket_name,
transformed_bucket=data_lake_stack.output_bucket.bucket_name,
env=env,
)
One wiring detail deserves mention: the AWS Glue stack deploys before the runtime stack exists. This means the orchestrator ARN can’t be passed as a CDK reference without creating a circular dependency. Instead, the runtime stack writes the ARN to an AWS Systems Manager (SSM) parameter (/weather-etl/orchestrator-runtime-arn) and the AWS Glue job reads it at job runtime.
Step 3: Verify knowledge sources
The knowledge sources populate automatically during cdk deploy. Domain documents (schema definitions, error patterns, NOAA data guides) upload from the repository’s knowledge_base/ folder to the knowledge base source bucket. A custom resource then triggers the knowledge base ingestion job. Correction strategy files and storage mappings are generated from the same documents and uploaded to the agent vector buckets.
Verify the population completed:
# Resolve the auto-generated vector bucket names from stack outputs (run once)
CORRECTION_BUCKET=$(aws cloudformation describe-stacks \
--stack-name WeatherKnowledgeBaseStack \
--query "Stacks[0].Outputs[?ExportName=='WeatherKB-CorrectionVectorsBucketName'].OutputValue" \
--output text)
PERSISTENCE_BUCKET=$(aws cloudformation describe-stacks \
--stack-name WeatherKnowledgeBaseStack \
--query "Stacks[0].Outputs[?ExportName=='WeatherKB-PersistenceVectorsBucketName'].OutputValue" \
--output text)
# Check correction strategy files (one per schema-type/error-type combination)
aws s3 ls "s3://$CORRECTION_BUCKET/correction/" --recursive | head
# Check storage mapping files
aws s3 ls "s3://$PERSISTENCE_BUCKET/persistence/" --recursive | head
The correction vectors bucket contains one JSON file per schema-type/error-type combination, each with a correction strategy and confidence score. The persistence vectors bucket contains storage mapping files that tell the persistence agent where and how to write each schema type.
Step 4: Test the correction workflow with sample data
Generate sample weather data including intentional errors and upload directly to S3:
# Generate 15 valid records + 4 error records and upload to S3 raw zone
python3 scripts/generate_sample_data.py --upload --region us-east-1
After uploading data, the AWS Glue crawler catalogs the new records on its next scheduled run. You can then trigger the AWS Glue ETL job to validate records, write valid ones to the transformed zone, and route errors to the orchestrator.
# Trigger the Glue ETL job manually
aws glue start-job-run \
--job-name weather-etl-job-$(aws sts get-caller-identity --query Account --output text)-us-east-1 \
--region us-east-1
# Resolve the auto-generated data lake bucket name from stack outputs
OUTPUT_BUCKET=$(aws cloudformation describe-stacks \
--stack-name WeatherDataLakeStack \
--query "Stacks[0].Outputs[?ExportName=='WeatherDataLake-OutputBucketName'].OutputValue" \
--output text)
# Check results
aws s3 ls "s3://$OUTPUT_BUCKET/transformed/" --recursive
aws s3 ls "s3://$OUTPUT_BUCKET/corrected/" --recursive
You can watch the correction agent’s decision flow in Amazon CloudWatch Logs (log group /aws/bedrock-agentcore/runtimes/weather_correction_agent-*). This excerpt from a real run shows the two-source lookup and strategy selection for a missing_field error:
[CORRECTION] Step 1: Querying Amazon Bedrock knowledge base for semantic correction guidance
(domain docs, error patterns, schema definitions)
[KB] Querying Amazon Bedrock knowledge base (ID=XXXXXXXXXX) for correction strategy.
Query: 'How to correct a missing_field error in a precipitation_measurement
weather record? Error details: Missing required field: data'
[KB] Received 3 results from knowledge base
[KB] Top result: score=0.784, source=s3://weatherknowledgebasestack-kbsourcebucket29781297-xxxxxxxxxxxx/error_patterns/missing_field.md,
content_preview='# Error Pattern: Missing Field ## Description Records where one or
more required fields in the data payload are absent...'
[CORRECTION] Step 2: Querying S3 Vectors for pre-computed correction strategy
(exact match by schema_type + error_type)
[S3V] Querying S3 Vectors for pre-computed correction strategy.
Bucket=weatherknowledgebasestack-correctionvectorsbucket27485eb2-xxxxxxxxxxxx, Key=correction/precipitation_measurement/missing_field.json
[S3V] Found correction strategy: score=0.85, strategy='**Field name correction**:
Check for similar field names that may be typos and rename them.'
[CORRECTION] Step 3: Strategy selection — KB strategy=found (score=0.78),
S3V pattern=found (score=0.85) → selected confidence=0.85, threshold=0.70
Both sources returned a strategy. The pre-computed S3 file scored higher (0.85 compared to 0.78), cleared the 0.7 threshold, and the correction was applied.
To see the correction itself, compare an error record with its corrected version. This sample record failed validation because temperature_celsius contained a string instead of a number:
The corrected record written to the data lake preserves the original fields and annotates the record with the selected correction strategy. This gives downstream consumers and auditors visibility into which fix was chosen:
{
"record_id": "fd04d2d9-ab37-4baf-869b-33a52ef9c574",
"schema_type": "temperature_observation",
"data": {
"temperature_celsius": "not-a-number",
"temperature_fahrenheit": 74.3,
"measurement_type": "surface",
"quality_flag": "valid",
"sensor_id": "TEMP-ERR-001"
},
"_correction_applied": "**Type coercion**: For invalid numeric formats,
check if the complementary unit field is present and compute the value
using the conversion formula."
}
The sample implementation annotates records with the strategy rather than mutating field values, keeping the correction transparent and reversible. To apply transformations directly (for example, deriving temperature_celsius from the valid temperature_fahrenheit value), extend the correction agent’s _apply_correction function with your domain’s transformation logic.
After the agents finish, the corrected records appear in both data lake zones. This listing from a test run shows the four intentionally corrupted records repaired and written to the corrected zone within minutes of the AWS Glue job routing them:
The same corrected records also land in the transformed zone, so downstream consumers see them alongside the records that passed validation on first pass. If a correction had fallen below the confidence threshold, the orchestrator would instead publish an SNS notification to the configured email address with the error details for manual review.
The remediation step requires repository credentials (git_repo_url context values at deploy time, git token set using script). When configured, the remediation agent creates a branch, commits the proposed fix, and opens a pull request with the root cause analysis in the description. Without credentials, the agent logs that remediation was skipped and the workflow completes with data correction and persistence only.
What this pattern automates
The following table compares a standard ETL error-handling workflow with the self-healing approach:
Standard ETL workflow
Self-healing ETL workflow
Bad records go to a dead-letter queue
Bad records get corrected and re-inserted
Engineers manually triage errors
Agents classify and fix errors automatically
Code fixes require a separate workflow
Pull requests are submitted automatically
Same errors recur until code is patched
Root cause is addressed at the source
Downstream consumers see incomplete data
Transformed zone includes corrected records
Knowledge lives in runbooks and tribal memory
Knowledge lives in a searchable, versioned knowledge base
To see how the self-healing automations combine for a single record, follow one error record through the pipeline from end to end. The following diagram traces that path:
Figure 4: End-to-end trace of a single error record through the pipeline
The diagram traces a single error record through the pipeline: validation failure in the AWS Glue ETL job, routing to the orchestrator agent, two-source correction with confidence scores from the Amazon Bedrock knowledge base and the S3 correction files, persistence to both the transformed and corrected data lake zones, and a repository pull request that addresses the root cause in the upstream code.
Key design decisions
Four agents enforce separation of concerns – You can update the correction agent with new strategies without touching persistence logic. In environments without repository access, skip configuring the remediation agent’s credentials. Failure modes such as low-confidence notifications live in the orchestrator, independent of the correction logic.
The confidence threshold helps prevent incorrect corrections – Applying a wrong correction is worse than no correction. With the 0.7 threshold, the system acts when it’s confident, and notifies humans otherwise. You can tune this per-schema or per-error-type based on your tolerance.
The two knowledge sources serve distinct, complementary roles – The knowledge base excels at novel patterns. It can reason about error combinations it hasn’t seen before by drawing on domain documentation. Amazon S3 Vectors excel at known patterns, returning instant, deterministic results without model inference latency. Together, they cover both the long tail and the common case.
Clean up resources
To avoid ongoing charges, tear down the deployed resources when you’re done:
source .venv/bin/activate
cdk destroy --all
CDK destroys all stacks in reverse dependency order. The cleanup handles:
Deleting all CDK stacks and their resources.
Emptying S3 buckets (by using autoDeleteObjects).
Removing ECR container images (by using emptyOnDelete).
Deleting the S3 Vector bucket and index.
Force-deleting the Secrets Manager secret for repo credentials.
If you prefer to clean up manually, delete the stacks in this order:
WeatherAgentCoreRuntimeStack.
WeatherAgentCoreStack.
WeatherKnowledgeBaseStack.
WeatherGlueStack.
WeatherIngestionStack.
WeatherDataLakeStack.
CDK-created S3 buckets have autoDeleteObjects enabled and empty automatically during stack deletion. The cleanup does not delete the CDK bootstrap stack (CDKToolkit). Remove it separately if no longer needed.
Conclusion
A multi-agent system turns a standard ETL pipeline into a self-healing one. The system corrects and persists errors automatically, and the system can propose pull requests to fix the source code. The key components:
AWS Glue acts as the quality gate, validating data and routing failures to the agent system instead of a dead-letter queue.
Amazon Bedrock AgentCore with the Strands Agents SDK provides managed multi-agent orchestration without building custom workflow infrastructure.
Amazon Bedrock Knowledge Bases + S3 Vectors give agents domain expertise through both semantic reasoning and deterministic lookups.
The remediation agent is designed to close the loop when repo credentials are configured. It proposes fixes to the code that produced the bad data, not only the data itself.
To get started, clone the sample repository and follow the deployment steps in this post. To learn more about the services used, see the Amazon Bedrock AgentCore documentation, the Strands Agents SDK documentation, and the AWS Glue documentation. Adapt the pattern to your own data formats by replacing the weather schema validators with your domain’s validation logic. Update the knowledge base documents with your domain expertise, and populate S3 Vectors with correction strategies for your known error patterns. You can extend the pipeline by adding fine-tuned models for domain-specific corrections or implementing approval policies to automatically merge low-risk remediations. You can also connect additional knowledge sources as your error catalog grows.
This post is co-written with Ajay Gunasekaran, ML Platform Engineer at Samsung Ads.
Samsung Ads, the advertising division of Samsung Electronics, keeps its feature data in Snowflake as Apache Iceberg tables. Its machine learning (ML) team trains large-scale models on Amazon SageMaker AI, serving programmatic buyers who reach Samsung Smart TV and connected TV audiences. Connecting the two usually means copying the data into Amazon Simple Storage Service (Amazon S3) on a schedule. That adds a second pipeline to operate, a second copy to store, and two sets of permissions to keep in agreement.
Instead of copying the data, a team can write the final pipeline stage as Snowflake-managed Iceberg tables in Amazon S3 and federate them into AWS Lake Formation. Amazon Cognito supplies the OAuth2 tokens that Snowflake trusts. Both applications then read one copy of the data in Amazon S3, with Snowflake managing the tables and the team using Lake Formation to control which principals can read them. Model engineers can choose the query engine that fits each training job, without duplicating data or maintaining a second pipeline.
In this post, we show you how to build the pattern Samsung Ads used. You federate Snowflake Iceberg tables into AWS Lake Formation with Amazon Cognito, then query them from Amazon Athena.
Solution overview
This solution federates the Snowflake Horizon Catalog into AWS Lake Formation, using Amazon Cognito to issue OAuth2 tokens for machine-to-machine authentication. AWS Glue connection runs inside an Amazon Virtual Private Cloud (Amazon VPC), reaching Snowflake through AWS PrivateLink and the Cognito token endpoint through a NAT gateway. AWS analytics engines then query Snowflake-managed Iceberg tables under Lake Formation governance, with no second copy of the tables to maintain. The following diagram shows the query path, from Amazon Athena through AWS Lake Formation and the AWS Glue connection to Snowflake and Amazon S3.
Figure 1: Architecture for Snowflake Horizon Catalog federation to AWS Lake Formation using Amazon Cognito
Here’s how the workflow runs:
A user or application submits a SQL query in Amazon Athena that references a federated table in the Snowflake catalog.
Athena delegates catalog resolution and permission checks to Lake Formation, which evaluates fine-grained access controls on the federated catalog entry.
Lake Formation resolves the table reference through the AWS Glue Data Catalog, which holds the connection configuration for Snowflake and invokes the AWS Glue connection.
AWS Glue connection runs in a private subnet. It sends a client_credentials request to the Amazon Cognito token endpoint with the client ID, client secret, and scope. The request leaves through the NAT gateway and internet gateway because the machine-to-machine token endpoint is public.
Amazon Cognito invokes the Pre Token Generation Lambda trigger (V3_0), which adds the aud claim that Snowflake External OAuth validation requires. Amazon Cognito returns the access token to the connection.
Using that token, AWS Glue connection calls the Snowflake Horizon Catalog Iceberg REST endpoint for table metadata. The response includes the schema and the location of the data files in Amazon S3. An Amazon Route 53 private hosted zone resolves the hostname, because the Snowflake endpoint service doesn’t provide private DNS. The request travels through the VPC endpoint over AWS PrivateLink.
The connection returns the metadata to Lake Formation, which generates temporary, scoped Amazon S3 credentials and passes them to Athena.
Athena uses those credentials to read the Iceberg metadata and Parquet data files from the registered Amazon S3 location, runs the query, and returns results.
Why Amazon Cognito
AWS Glue connection authenticates with the OAuth2 client_credentials grant, so providers Snowflake trusts that support that grant can issue the token. Samsung Ads chose Amazon Cognito for three reasons:
Each table lookup against Snowflake depends on a token from the provider, so the team wanted to own it alongside the rest of the solution.
An enterprise identity provider is typically administered by a central security team, so each new machine-to-machine client is a cross-team request. Owning the user pool makes it self-service.
Each app client is a distinct machine identity, and the security integration trusts the user pool rather than an individual client. You can therefore serve several workloads from one integration, each with its own read-only Snowflake role.
Prerequisites
Before you begin, verify that you have the following:
Snowflake account hosted on AWS in the same AWS Region where you create the AWS resources in this post, on the Business-Critical edition or higher, which AWS PrivateLink requires. Confirm the Region with SELECT CURRENT_REGION();. You need ACCOUNTADMIN to create the security integration and to authorize PrivateLink.
Snowflake-managed Iceberg tables created in Snowflake Horizon Catalog using CATALOG = 'SNOWFLAKE' with an external volume pointing to the S3 bucket. If you don’t have one, see Configure an external volume for Amazon S3 in the Snowflake documentation.
AWS account with an AWS Identity and Access Management (IAM) principal that has data lake administrator permissions in AWS Lake Formation. The principal also needs permissions to create IAM roles and policies, Amazon Cognito user pools, AWS Lambda functions, VPC resources, and AWS CloudShell. We use AWS Command Line Interface (AWS CLI) commands throughout this post.
Amazon S3 bucket that holds your Snowflake-managed Iceberg data files.
An AWS user with long-term access keys that you delete immediately after Step 4:
SYSTEM$AUTHORIZE_PRIVATELINK needs a federation token from the long-term keys of an IAM user, because sts:GetFederationToken rejects role-session credentials. Snowflake persists the authorization, so you can delete the key and the user afterwards and the federation keeps working.
Walkthrough
Two AWS CloudFormation stacks cover the setup that is identical in every deployment. The Snowflake and Lake Formation steps stay as explicit SQL and AWS CLI commands, so you can adapt them to your existing Snowflake account and VPC.
Step
What you configure
How you run it
1 & 2
Cognito user pool, machine-to-machine app client, and the Lambda function that adds the aud claim
Launch Stack, snowflake-federation-oauth
3
Snowflake security integration, read-only role, service user, and table grants
Snowflake SQL worksheet
4
PrivateLink authorization for your AWS account
AWS CLI and Snowflake SQL worksheet
5
VPC, PrivateLink endpoint, Route 53 private hosted zone, and the Lake Formation data access role
Launch Stack, snowflake-federation-network
6
S3 location registration, AWS Glue connection, federated catalog, and Lake Formation permissions
AWS CLI
7
Query validation
Athena console
Step 1: Deploy the Cognito user pool and token customization Lambda function
Snowflake External OAuth validation requires an aud claim in each access token. The OAuth2 client_credentials grant doesn’t define that claim, so the Pre Token Generation trigger adds it. This stack creates the user pool, the machine-to-machine app client, and a Pre Token Generation Lambda function that adds the claim. The stack also writes the app client secret to AWS Secrets Manager in the format the AWS Glue connection expects. It then generates the Snowflake SQL statements you run in Step 3.
Choose Launch Stack.
In the Region selector, confirm the Region matches your Snowflake account Region, then choose Next.
For Stack name, keep snowflake-federation-oauth. Leave all parameters at their default values, then choose Next.
On Configure stack options, keep the defaults and choose Next.
On Review and create, select I acknowledge that AWS CloudFormation might create IAM resources with custom names, then choose Submit.
When the stack status is CREATE_COMPLETE, choose the Outputs tab.
You use six of the outputs in later steps.
Output
Used in
VerifyAudClaimCommand
Step 2
SnowflakeSecurityIntegrationSQL
Step 3
OAuthClientSecretArn
Step 5 and Step 6
CognitoTokenEndpoint, CognitoClientId and CognitoScope
Step 3 and Step 6
Figure 2: CloudFormation Outputs tab showing the values used in later steps
Note: After the connection validates in Step 6, AWS Glue caches the token it mints by writing it back into this secret. Treat read access to the secret as read access to the federated tables.
Step 2: Verify the access token
Confirm that the Lambda function is adding the claim before you configure Snowflake. A missing claim doesn’t fail here. It surfaces several steps later as an AWS Glue connection that can’t authenticate, which is harder to attribute.
On the Outputs tab, copy the value of VerifyAudClaimCommand.
Choose the AWS CloudShell icon on the console navigation bar, as shown in the following screenshot.
Paste the command and run it. Confirm two values in the output. The aud claim matches your Cognito client ID, and scope is snowflake/catalog.read.
Figure 3: Decoded access token payload showing the injected aud claim and the catalog.read scope
Step 3: Configure Snowflake
In this step you configure Snowflake to trust Cognito tokens, create the service user that Lake Formation authenticates as, and grant it read access to your tables.
Run the following statement in a Snowflake worksheet, replacing the three placeholders with the CognitoIssuerUri, CognitoJwksUrl, and CognitoClientId outputs from Step 1. The SnowflakeSecurityIntegrationSQL output contains the same statement with your values filled in. CREATE omits OR REPLACE, so it fails rather than overwriting an existing integration.
USE ROLE ACCOUNTADMIN;
-- Return a row if the integration exists. If so, use ALTER SECURITY INTEGRATION instead of CREATE
SHOW INTEGRATIONS LIKE 'lakeformation_cognito_oauth';
CREATE SECURITY INTEGRATION lakeformation_cognito_oauth
TYPE = EXTERNAL_OAUTH
ENABLED = TRUE
EXTERNAL_OAUTH_TYPE = CUSTOM
EXTERNAL_OAUTH_ISSUER = '<CognitoIssuerUri>'
EXTERNAL_OAUTH_JWS_KEYS_URL = '<CognitoJwksUrl>'
EXTERNAL_OAUTH_TOKEN_USER_MAPPING_CLAIM = 'sub'
EXTERNAL_OAUTH_SNOWFLAKE_USER_MAPPING_ATTRIBUTE = 'login_name'
EXTERNAL_OAUTH_AUDIENCE_LIST = ('<CognitoClientId>')
EXTERNAL_OAUTH_ANY_ROLE_MODE = 'ENABLE'
EXTERNAL_OAUTH_BLOCKED_ROLES_LIST = ('ACCOUNTADMIN', 'SECURITYADMIN', 'USERADMIN', 'SYSADMIN');
Snowflake normally takes the role from a session:role:<ROLE> scope, which Amazon Cognito custom scopes can’t carry because they use the form resourceServer/scope. The statement therefore sets EXTERNAL_OAUTH_ANY_ROLE_MODE to ENABLE, which lets the session use any role granted to the service user, so keep that user to a single role. The blocked roles list also covers SYSADMIN and USERADMIN, which the Snowflake default list doesn’t.
Create the read-only role and the service user. Set LOGIN_NAME to the CognitoClientId output, because the token’s sub claim carries the client ID and the integration maps sub to login_name.
CREATE ROLE lakeformation_catalog_reader
COMMENT = 'Read-only access for AWS Lake Formation catalog federation';
CREATE USER lakeformation_service_user_cognito
LOGIN_NAME = '<CognitoClientId from Step 1>'
DEFAULT_ROLE = lakeformation_catalog_reader
TYPE = SERVICE;
GRANT ROLE lakeformation_catalog_reader TO USER lakeformation_service_user_cognito;
Grant the role read access to the tables you want to federate. For the privileges the Iceberg REST Catalog API requires, see Configure access control in the Snowflake documentation.
GRANT USAGE ON DATABASE <database>
TO ROLE lakeformation_catalog_reader;
GRANT USAGE ON SCHEMA <database>.<schema>
TO ROLE lakeformation_catalog_reader;
GRANT SELECT ON ALL ICEBERG TABLES IN SCHEMA <database>.<schema>
TO ROLE lakeformation_catalog_reader;
GRANT SELECT ON FUTURE ICEBERG TABLES IN SCHEMA <database>.<schema>
TO ROLE lakeformation_catalog_reader;
Note: Federate a schema that contains only Snowflake-managed Iceberg tables. An externally managed table can fail the entire table listing. Converted tables, tables loaded from Iceberg-compatible Parquet files and clones whose source table the role can’t access aren’t supported. Tables with mixed-case quoted names aren’t federated, because the connection you create in Step 6 sets CATALOG_CASING_FILTER to UPPERCASE_ONLY.
Snowflake masking and row access policies don’t apply when Athena reads a federated table, because Lake Formation vends the Amazon S3 credentials and Athena reads the Parquet files directly. Keep tables that rely on them out of the federated schema or recreate the controls in Lake Formation and test them.
Next, find the Amazon S3 bucket and prefix your external volume writes to. You need both in Step 5.
DESC EXTERNAL VOLUME <your_external_volume>;
STORAGE_BASE_URL holds the bucket and an optional prefix. For s3://my-bucket/iceberg/, the bucket is my-bucket and the prefix is iceberg. If nothing follows the bucket name, leave the prefix blank in Step 5. A prefix is better, because it limits the data access role to that path. If ENCRYPTION_TYPE is AWS_SSE_KMS, note the key in ENCRYPTION_KMS_KEY_ID for Step 5. If it is NONE, check the bucket’s default encryption in the Amazon S3 console. The Snowflake role that owns the Iceberg tables must keep the USAGE privilege on the external volume, or operations that request vended credentials fail.
If the bucket uses a customer managed KMS key, set KMS_KEY_ID on the external volume to the full key ARN. Then add the following statement to the key policy, so the session Snowflake uses for the role in STORAGE_AWS_ROLE_ARN can read the encrypted files. Without it, the AWS Glue connection fails with an error that says no session policy allows kms:Decrypt.
Snowflake requires proof that you own the AWS account before it accepts a PrivateLink connection. You provide that proof as an AWS Security Token Service (AWS STS) federation token. You must call get-federation-token with the long-term credentials of an IAM user, because AWS STS doesn’t support calling it with temporary credentials from an assumed role.
Using an IAM user with long-term access keys, generate a federation token:
Retrieve the two values you need for the stack in Step 5:
WITH cfg AS (SELECT PARSE_JSON(SYSTEM$GET_PRIVATELINK_CONFIG()) AS j)
SELECT j:"regionless-privatelink-account-url"::string AS privatelink_hostname,
j:"privatelink-vpce-id"::string AS vpce_service_name
FROM cfg;
Record both values. privatelink_hostname is the Snowflake PrivateLink hostname, and vpce_service_name is the endpoint service name.
After authorization succeeds, delete the temporary IAM user and its access key. Revoking PrivateLink access later requires a new federation token, so recreate a similar user at that point. For more information, see How to retrieve a Federation Token from AWS for PrivateLink Self-Service.
Step 5: Set up VPC and PrivateLink connectivity
This stack creates the interface VPC endpoint to the Snowflake PrivateLink service and the Amazon Route 53 private hosted zone that resolves your Snowflake hostname to it. It also creates the security group that the endpoint shares with the AWS Glue connection. Keep Existing VPC ID blank and it also builds a VPC with public and private subnets and a NAT gateway.
To use an existing VPC, supply Existing VPC ID and two or more private subnet IDs in different Availability Zones. The stack then creates no subnets and no NAT gateway, so confirm three things first:
You have enabled DNS resolution and DNS hostnames on the VPC.
The private subnets have a 0.0.0.0/0 route to a NAT gateway, which the AWS Glue connection uses to reach the Amazon Cognito token endpoint. Amazon Cognito doesn’t support AWS PrivateLink, but the traffic stays on the AWS network because both sit in the same Region. Without this route, the stack still succeeds and the connection fails in Step 6.
No Amazon Route 53 private hosted zone for privatelink.snowflakecomputing.com is already associated with the VPC. A second zone for the same domain makes name resolution unpredictable.
To deploy the stack, complete the following steps:
Choose Launch Stack.
Confirm the Region selector matches your Snowflake account Region, then choose Next.
For Stack name, keep snowflake-federation-network, then enter the following parameters.
Parameter
Value
Snowflake PrivateLink hostname
privatelink_hostname from Step 4
Snowflake PrivateLink service name
vpce_service_name from Step 4
Iceberg S3 bucket name
The bucket in the STORAGE_BASE_URL output from Step 3
Iceberg data key prefix
The prefix in the STORAGE_BASE_URL output from Step 3. Leave blank if you have none
Iceberg bucket KMS key ARN
KMS key ARN. Leave blank if the bucket does’t use KMS
OAuth client secret ARN
OAuthClientSecretArn from Step 1
If the bucket uses SSE-KMS, the stack grants the data access role kms:Decrypt on the key you enter. The default key policy already allows this. If your key policy doesn’t delegate access to IAM, add the role as a key user.
Choose Next, keep the defaults on Configure stack options, and choose Next.
On Review and create, select I acknowledge that AWS CloudFormation might create IAM resources with custom names, then choose Submit.
When the stack status is CREATE_COMPLETE, which takes about 5 minutes, choose the Outputs tab and record PrivateSubnetIds, GlueConnectionSecurityGroupId, LakeFormationDataRoleArn, and RegisteredS3Location. You use all four values in Step 6.
NAT gateway and the interface VPC endpoint carry hourly and data processing charges. For more information, see Amazon VPC pricing.
Step 6: Register with Lake Formation and create the federated catalog
The remaining setup is a sequence of AWS CLI commands. Run them in AWS CloudShell in the same Region as both stacks.
Set the values used by the commands that follow. Fill in the Region, and the stack outputs from Step 1 and Step 5.
REGION='<your Region>'
ACCT=$(aws sts get-caller-identity --query Account --output text)
PREFIX=snowflake-federation
CONN=$PREFIX-iceberg-connection
CATALOG=$PREFIX-catalog
S3_LOCATION='<RegisteredS3Location from Step 5>'
LFROLE='<LakeFormationDataRoleArn from Step 5>'
SECRET_ARN='<OAuthClientSecretArn from Step 1>'
TOKEN_URL='<CognitoTokenEndpoint from Step 1>'
CLIENT_ID='<CognitoClientId from Step 1>'
SCOPE='<CognitoScope from Step 1>'
SUBNET='<one subnet ID from PrivateSubnetIds in Step 5>'
SG='<GlueConnectionSecurityGroupId from Step 5>'
WORKSPACE_URL='https://<privatelink_hostname from Step 4>/polaris/api/catalog'
REMOTE_DB='<Snowflake database name, uppercase>'
SCHEMA='<Snowflake schema name, lowercase>'
QUERY_PRINCIPAL='<IAM role or user ARN that will run Athena queries>'
Register the Amazon S3 location that holds your Iceberg data. This is what lets Lake Formation vend scoped credentials to Athena for the underlying data files.
Check the connection status. AWS Glue validates asynchronously. It creates the network interface, completes the OAuth2 exchange with Amazon Cognito, and calls the Snowflake Iceberg REST API over AWS PrivateLink. Repeat this command until it returns READY, which takes approximately 5–10 minutes.
aws glue get-connection --name $CONN --query Connection.Status --output text
If it returns FAILED, read the reason and correct the Snowflake configuration from Step 3. A missing security integration, service user, or grant is the usual cause.
aws glue get-connection --name $CONN --query Connection.StatusReason --output text
Then delete the connection before you retry, because the name stays in use.
Grant Lake Formation permissions to the data teams that will query the tables. The principal that created the catalog can already query it. Every other principal needs an explicit grant, including other Lake Formation administrators.
Note: The catalog ID for a federated catalog is :, not the bare account ID. Using the bare account ID grants permissions on the local AWS Glue Data Catalog instead, which succeeds and then leaves Athena returning an access denied error.
Step 7: Query the federated tables from Amazon Athena
Open the Amazon Athena console and choose Query editor. If this is the first time you use Athena in this Region, choose Settings, then Manage, and set an Amazon S3 location for query results.
In the left panel, select the following.
Field
Value
Data source
AwsDataCatalog
Catalog
Your federated catalog, for example snowflake-federation-catalog
Database
Your Snowflake schema name, in lowercase
Run the following query:
SELECT * FROM "<snowflake_schema>"."<snowflake_tablename>" LIMIT 10;
Rows in the results pane confirm the federation works end to end, as shown in the following screenshot.
Figure 5: Query results in Amazon Athena from a Snowflake-managed Iceberg table
To confirm that Athena reads current Snowflake data rather than a copy, insert a row in Snowflake and run the query again. The new row appears with no additional data movement into your AWS account.
Dropping a table in Snowflake doesn’t revoke the Lake Formation permissions granted on it. Revoke those permissions explicitly when you remove a federated table.
Clean up
To avoid incurring future charges, delete the resources you created while following this post. Complete the following steps in both your AWS account and your Snowflake account.
AWS account
On the AWS Lake Formation console, choose Catalogs, select your federated catalog, then choose Actions and Delete catalog.
Record the network interfaces the AWS Glue connection created, while the connection still exists. Filtering on the Step 5 security group and the ICEBERGRESTCATALOG description keeps the list to this deployment.
Deregister and delete the AWS Glue connection. Do this before you delete the stacks, because the stack deletion fails while the connection’s network interfaces still hold the security group. Run the following in AWS CloudShell, replacing the Region, account ID, and connection name with your values.
Deleting the connection releases its network interfaces, but they stay in the in-use state for several minutes and AWS Glue doesn’t remove them. Wait for each one to reach available, because the Amazon Elastic Compute Cloud (Amazon EC2) console Detach action fails even with Force detachment selected. The following script checks each interface you recorded and deletes it when ready.
#!/bin/bash
while read -r eni; do
[ -z "$eni" ] && continue
for attempt in $(seq 1 20); do
status=$(aws ec2 describe-network-interfaces \
--network-interface-ids "$eni" \
--query 'NetworkInterfaces[0].Status' \
--output text 2>/dev/null || echo deleted)
if [ "$status" = "available" ]; then
aws ec2 delete-network-interface --network-interface-id "$eni"
echo "$eni deleted"
break
fi
if [ "$status" = "deleted" ]; then
echo "$eni no longer exists"
break
fi
echo "$eni is $status, checking again in 30 seconds"
sleep 30
done
done < glue-enis.txt
On the Lake Formation console, under Administration, choose Data lake locations, select the registered Amazon S3 location, then choose Actions and Remove.
On the AWS CloudFormation console, delete snowflake-federation-network first, then snowflake-federation-oauth. This removes the VPC endpoint, the Amazon Route 53 private hosted zone, the security group, and the IAM role. It also removes the Amazon Cognito user pool, the AWS Lambda function, and the client secret. If the stack created the VPC, subnets, and NAT gateway, it removes those too.
Snowflake account
Open a SQL worksheet and run the following:
USE ROLE ACCOUNTADMIN;
DROP SECURITY INTEGRATION lakeformation_cognito_oauth;
USE ROLE USERADMIN;
DROP USER lakeformation_service_user_cognito;
DROP ROLE lakeformation_catalog_reader;
Revoke the PrivateLink authorization for your AWS account. This requires a fresh federation token, generated the same way as during setup, from an IAM user with long-term access keys:
Deleting the federated catalog and connection doesn’t delete data in Snowflake or Amazon S3. It only removes the federation configuration in your AWS account.
Conclusion
In this post, you learned how to federate Snowflake Horizon Catalog Iceberg tables into AWS Lake Formation and query them from Amazon Athena. Amazon Cognito handled the OAuth2 tokens for machine-to-machine authentication. To extend this pattern to additional workloads, create a new app client in your Cognito user pool and a corresponding read-only Snowflake role.
Migrating from Apache Hive Metastore (HMS) to AWS Glue Data Catalog (GDC) is a priority for many organizations as they scale their data analytics operations. At enterprise scale, maintaining an efficient and reliable metadata management system becomes increasingly critical. Many enterprises started their big data journey with HMS, which has served as a reliable catalog service for storing table definitions and metadata. As cloud adoption has grown, so have requirements for fine-grained access control and for serverless, fully managed solutions. As a result, organizations are looking to modernize their data catalog infrastructure and are moving their metastores to GDC, a fully managed AWS metadata repository. With GDC, they gain native integration with various AWS analytics and AI services, along with centralized data management and governance.
In this post, we walk through how Intuit successfully migrated its extensive data catalog from HMS to GDC. This migration is part of Intuit’s journey to an open, secure lakehouse architecture for data and analytics. We explore the challenges Intuit faced and the solutions it implemented. We also cover the benefits that motivated the move: reduced operational overhead, improved data discovery, and enhanced integration with AWS analytics services. Whether you are considering a similar migration or exploring your options for metadata management, this real-world example provides practical insights into the migration process.
Migration considerations and prerequisites
Audit the HMS catalog and remove unused tables and views by deleting or flagging them to filter out during initial migration to GDC. This will make sure that after migration you have a clean catalog and will help with better migration performance.
Estimate the read and write API limits you will need in GDC based on the traffic in HMS. To do this, you can audit the internal HMS tables and get the P99 numbers for reads and writes to tables and partitions. These numbers will need to be translated to AWS Glue Data Catalog API limits and the necessary quota increase requests will need to be submitted. Load test with these quotas to confirm that they support your peak read and write rates without throttling, and implement retries to handle any throttling that does occur.
Make sure you have your AWS Glue quotas sized properly for your account and use case. You can work with AWS Support to increase these quotas based on the results of the load testing.
Data is stored in Amazon Simple Storage Service (Amazon S3) for table resources that are planned for migration. Only databases, tables, and partitions can be migrated. Other entities, such as column statistics, privileges, roles, functions, and transactions, were outside the scope of the migration.
Plan for table renames: In GDC table/database rename isn’t supported. In some cases, customers rename tables as part of their data pipelines to get atomic updates for tables that are non-partitioned and don’t use an open table format (OTF). For use cases where this pattern is required, we recommend writing to a new S3 location and then running the following ALTER TABLE command to change the S3 location.
ALTER TABLE table_identifier [ partition_spec ] SET LOCATION 'new_location'
Architecture
The following diagram shows the overall architecture of the solution across two consumer accounts (spoke accounts), and a central data governance account as part of a hub-and-spoke architecture.
Figure 1: Solution architecture spanning the source and consumer spoke accounts and the central data governance account
In the source spoke account, Hive Metastore manages the metadata for data stored in Amazon S3. This is the current state. In the central data governance account, an HMS and GDC sync process propagates this metadata into the central AWS Glue Data Catalog, which AWS Lake Formation governs. AWS CloudTrail records operations on the central catalog. The central catalog is shared across accounts with the consumer spoke account. There, Amazon Athena, Amazon Redshift, and Amazon EMR query the data through role-based access, using Lake Formation and a local AWS Glue Data Catalog. This migration strategy is explained in detail in the following sections.
Migration strategy
At Intuit, the central team manages the data catalog and offers it as a platform for the different teams to use. Because of the scale of Intuit’s data lake and the large number of teams using the data platform, Intuit had to come up with a phased strategy. With these tenets in mind, Intuit came up with the following approach:
One-time migration of all databases, tables, and partitions. During this phase all the objects were migrated from HMS to GDC. The migration will be point-in-time and any changes happening in HMS will not be captured by the initial migration.
Ongoing sync from HMS to GDC to capture all changes happening in HMS and apply them to GDC. This would make sure any team that is ready to migrate their pipelines to GDC can do so without any dependency on upstream and downstream processes.
Ongoing sync from GDC to HMS to capture any changes that happen in GDC and apply them back to HMS. Some of your pipelines might still point to HMS while the upstream pipelines whose tables they consume have already moved to GDC. This sync process replicates all changes back to HMS, so those pipelines aren’t impacted.
To make sure both catalogs remain in sync and to prevent drift, a parity tool runs hourly to compare all critical metadata values and verify consistency between the catalogs. For details, see the Parity tool section later in this post.
An ad hoc sync process was also built. If the parity tool identifies that the two catalogs are out of sync, this process provides a straightforward way to bring them back in sync.
To prevent a circular loop between the HMS-to-GDC sync (#2) and the GDC-to-HMS sync (#3), each table is assigned a single source of truth. The source of truth is recorded as a sourceCatalog flag (HMS or GDC) in an Amazon DynamoDB arbitration table. During the HMS-to-GDC incremental sync, only tables whose source of truth is HMS are picked up and synced to GDC. Conversely, the GDC-to-HMS sync checks the sourceCatalog flag to confirm the change genuinely originated in GDC and isn’t a cascading update that was originally synced from HMS. This arbitration model makes sure each table’s metadata flows in only one direction at any given time, eliminating the risk of circular updates between the two catalogs.
1. Initial full migration
The first step is to migrate all the databases, tables, and partitions from HMS to GDC. This will need to be planned over a weekend to make sure there is no impact on the workloads running on HMS. The duration of this initial migration will vary depending on the size of your data lake. After being customized to support batching and retries, the AWS Glue Hive metastore migration utility was used to migrate all the metadata (databases, tables, and partitions) from HMS to GDC.
This utility runs an AWS Glue extract, transform, and load (ETL) job that pulls the metadata from the Amazon Aurora MySQL tables that hold the HMS metadata. The job transforms the data and writes it to the AWS Glue Data Catalog.
The following diagram shows the one-time sync process.
Figure 2: One-time migration of metadata from Hive Metastore to AWS Glue Data Catalog
An AWS Lambda function starts the AWS Glue ETL job. The job settings, such as the number of workers and the database, table, and partition write factors, come from a cdk.json configuration file. The job reads databases, tables, and partitions from the HMS MySQL database over JDBC. It transforms them into DynamicFrames with batching and rate limiting, and writes them to the AWS Glue Data Catalog. Amazon CloudWatch captures job metrics and logs. The lower half of the diagram shows nine orchestration steps: stopping the incremental sync, cleaning up GDC, running full and delta syncs, and turning on the parity jobs.
Customization options
The utility should work as-is for most cases, but Intuit customized the script to speed up the one-time migration process while making sure that GDC didn’t throttle requests.
Loading behavior
Set catalog.overwriteIfExists to false during your runs.
This is a good approach for use cases with a large number of tables because it skips overwriting a table that already exists.
One way to control the rate and reduce the amount of data sent to GDC is to change the value of catalog.ratePerDPUSecond in the code. This parameter adjusts the rate at which changes are written to GDC, and you can configure it as shown in the preceding code sample. The following formula shows how RatePerSecond is calculated and how catalog.ratePerDPUSecond influences it.
With the defaults (catalog.ratePerDPUSecond = 10, DefaultExecutorsPerDPU = 2), each data processing unit (DPU) submits five calls/sec. At that rate, a 200-DPU job submits approximately 500 calls/sec (100 x 10 / 2) when the DataFrame is well partitioned. Lower catalog.ratePerDPUSecond or the DPU count until throttling stops. Internally, these writes call BatchCreatePartitions, which batches partition creation and keeps API volume down.
Handling API limits
In GDC, there are limits for each API call and if you exceed the limits you will be throttled. One approach to handling API limits is to batch the database, table, and partition loads and send the batched data during each batch.
The second step involved creating a two-way synchronization between HMS and GDC. This synchronization made sure that any changes made to tables in HMS were reflected in GDC, and vice versa. To maintain consistency, incremental data loads were necessary between the two systems. The process synced metadata changes by capturing updates in HMS and GDC and applying them to the other system. This kept both catalogs synchronized. A key rule was to designate one catalog as the definitive source of truth for each table to avoid conflicts. This was done using the DynamoDB arbitration table as described earlier.
HMS to GDC
The following diagram shows the ongoing incremental sync from HMS to GDC.
Figure 3: Ongoing incremental sync from Hive Metastore to AWS Glue Data Catalog
The ongoing incremental sync from HMS to GDC is powered by an event-driven architecture that propagates metadata changes in near real time. Catalog updates to the source HMS can affect databases, tables, table parameters, or partitions. A Debezium connector continuously monitors the underlying MySQL instance for any INSERT, UPDATE, or DELETE operations through Change Data Capture (CDC). This approach removes the need for polling or application-level hooks.
Captured changes are routed into dedicated Kafka topics based on the type of metadata object affected. HMS-HIVE-DBS receives database-level changes, HMS-HIVE-TBLS receives table-level changes, and HMS-HIVE-TABLE_PARAMS receives table parameter modifications. HMS-HIVE-PARTITIONS receives partition changes, and HMS-HIVE-SDS receives partition or table location change events. This separation allows each object type to be processed, scaled, and retried independently. For partitions specifically, a 10-second rolling window is applied per table. When the first partition event arrives for a given table, a 10-second timer begins, and all subsequent partition events for that table are collected. When the timer expires, all accumulated events are submitted as a single batch call to the SDK, which significantly reduces API throttling for tables with high partition churn.
Before any change is synced to GDC, the system performs a schema opt-out check against an Amazon DynamoDB table. This lookup determines whether the affected database or table has been explicitly excluded from synchronization, giving individual teams governance over what metadata flows into the central catalog. If the schema is opted out, the change is dropped and no sync occurs. If it isn’t opted out, the system proceeds to apply the metadata operation (create, update, or delete) to the central GDC through the AWS Glue SDK.
Sometimes additional metadata context is needed to fully resolve a change, for example, to construct a complete table definition when processing a partition update. In these cases, the system falls back to extracting metadata directly from HMS over a JDBC connection to the source Aurora MySQL database. This makes sure that GDC always receives complete and consistent metadata, even when the CDC event alone doesn’t carry all required fields.
The overall design achieves low-latency metadata propagation without placing read pressure on the source HMS. Together, the batching strategy, queue-based decoupling, and opt-out mechanism provide a scalable, governed, and throttle-resilient sync pipeline.
GDC to HMS
The following diagram shows the ongoing incremental sync from GDC to HMS.
Figure 4: Ongoing incremental sync from AWS Glue Data Catalog to Hive Metastore
The reverse sync from GDC to HMS follows an event-driven architecture. It captures metadata changes made in the AWS Glue Data Catalog and propagates them back to HMS to maintain bidirectional consistency.
When databases, tables, or partitions are added to or deleted from GDC, Amazon EventBridge detects the change through an EventBridge rule. This rule is configured to match specific change events (adding or deleting databases, tables, or partitions) and triggers an AWS Lambda function (handle-eventbridge-events) to begin processing the event.
The Lambda function publishes the raw events to an Amazon Managed Streaming for Apache Kafka (Amazon MSK) topic called central-gdc-raw-events. A downstream Apache Flink consumer, the Streaming Pipeline for Out of Order Raw Events, reads from this topic and applies event ordering logic. Because events might arrive out of sequence, this pipeline uses a one-minute rolling window to buffer events by schema or table. It then sorts the buffered events by their event timestamp and re-publishes them in the correct order to a second Amazon MSK topic called central-gdc-ordered-events.
At this point, the flow splits into two parallel consumption paths.
The first path is consumed by another Apache Flink consumer, the gdc-to-hms-sync pipeline, which is responsible for determining whether a given schema or table is allowed to sync. It performs a lookup against an Amazon DynamoDB table to check an allow list. If the entity is permitted for synchronization, the pipeline proceeds to push the metadata change to HMS using Amazon Athena as the execution engine. If the entity isn’t on the allow list, the pipeline takes no action and the event is dropped.
The second consumption path is consumed by a Data Lake crawler which updates the Data Lake control plane metadata inventory database.
The content of each ordered event is used as a trigger to get the latest metadata from GDC. That metadata is then synced to HMS by using the Thrift SDK and a Thrift client running on an Amazon EMR cluster.
The overall design reflects changes made in GDC reliably and consistently back into HMS. The event ordering pipeline applies operations in the correct sequence, regardless of delivery order. The allowlist mechanism in DynamoDB provides governance, because teams control which schemas participate in the reverse sync. Amazon Athena handles the final push to HMS by using its native integration with both GDC and Hive-compatible data stores.
3. Parity tool
When doing a migration through a bidirectional sync approach, a mechanism to do a parity check between the two systems is important to track any drift in the two catalogs. A parity tool was built to make sure the two catalogs are always in sync and to catch any discrepancies.
The following diagram shows the four stages of the parity tool pipeline: data extraction, data storage, comparison, and results.
Figure 5: Four-stage parity tool pipeline that compares the two catalogs
The parity tool uses AWS Glue jobs and Spark processing to efficiently compare catalog metadata:
Data extraction:
Primary list: Reads from DynamoDB table to determine which databases and tables to compare.
HMS: Connects to HMS MySQL database to extract metadata for tables in the primary list.
GDC: Uses AWS Glue API to extract metadata for tables in the primary list.
Data storage:
S3 output: Extracted data from both catalogs is written to S3 in Iceberg table format.
Iceberg tables: External Iceberg tables are created, allowing for efficient querying and comparison using Spark.
Comparison engine:
Spark jobs analyzed the Iceberg tables to identify differences in:
Databases exist in both catalogs.
Tables exist in both databases.
Table structures including columns and data types.
Table locations and SerDe paths.
Partition information including values and S3 location.
View definitions.
Results and views:
Difference tables are created showing objects present in one catalog but not the other.
Aggregation views provide summary counts.
Status views show parity health and sync status.
History tables track changes over time.
4. Ad hoc migration
An ad hoc migration process was built to perform ad hoc migrations for specific databases, tables, or partitions. This makes sure that if there is a discrepancy identified by the parity tool, it can be mitigated without having to run a full sync process. The ad hoc migration is an enhancement to the utility used for one-time sync where it can take the database name, table name, and partition information as input. Depending on the input provided, it will sync the respective objects.
GDC table requirements
S3 location: The location for the table data must be in S3. Only databases with an S3 location, or databases with one or more tables with an S3 location, will be included in the migration.
S3 location name length: The S3 location name can be up to 701 characters.
Table type: Only the HMS table types MANAGED_TABLE, EXTERNAL_TABLE, and VIRTUAL_VIEW are being imported to GDC.
Non-blank column names: Every column must have a name.
Column name length: Column names can be up to 255 characters. HMS allows 256.
Column name characters: Column names must not include the following characters: ?, \n, and \\.
Column type name length: Column type names can be up to 131,072 characters (2^17).
Conclusion
Migrating metadata from HMS to GDC is a complex process, but it can enhance your data management capabilities. Intuit’s migration shows that moving from HMS to GDC requires careful planning and execution. It also shows that the benefits of a modern, cloud-native catalog service make the move a worthwhile investment for organizations that want to scale their data operations efficiently and securely. After migrating to GDC, Intuit is focusing on implementing strong access controls using row-level, column-level, and cell-level controls in AWS Lake Formation. Because Intuit is building complex solutions and applications, this level of fine-grained access control is critical. Getting its catalog migrated to GDC was an important step in this journey.
If you run data pipelines, you know how much work they can take to set up, sometimes only to break without you realizing. That doesn’t even include data from sources too small to justify a project of their own, such as instrument exports, partner CSV files, and database tables. Each one can take an engineer days to map, code, test, and provision, and the work needs to be repeated when the schema changes.
Agentic Data Ingestion, the solution referenced in this post, automates that work with agentic AI. You point it at a file or a database table, and foundation models (FMs) propose the field mapping and write the transformation code. The agent tests that code on Apache Spark before it deploys the code as an AWS Glue job, and you approve or reject the result at the mapping or code testing step. In our test deployment, a run at sample scale costs about USD $0.10–0.25, and the idle deployment about USD $15–20 a month. For more information, see Cost to run the solution.
To see it in action before you deploy, try the interactive demo.
In this solution, the FMs run on Amazon Bedrock, which is a fully managed service that provides foundation models, and the agents, built with the open-source Strands Agents SDK, run on Amazon Bedrock AgentCore, which hosts and operates AI agents. AWS Step Functions, which provides serverless workflow orchestration, manages each run, and AWS Glue, which provides serverless data integration capabilities, runs the generated jobs. You deploy the whole solution with the AWS Cloud Development Kit (AWS CDK). Before you begin, review the Prerequisites.
Solution overview
The following diagram shows the architecture.
Figure 1: Solution architecture, from sign-in and the data sources through the agents and Step Functions orchestration to the AWS Glue job and its targets
File validation – Check format and size from object metadata.
Schema extraction – Infer field names and types.
Schema comparison – Detect drift against the target schema.
Schema mapping – An FM maps source to target fields with confidence scores. (Approval gate).
Code generation – Generate the PySpark transform and data quality rules.
Code testing – Run the transform on Spark and check its output. (Approval gate, plus a forced review if tests keep failing).
Infrastructure provisioning – Create the target if it doesn’t exist.
AWS Glue job creation – Create the job with a validated configuration.
Quality checks – Record which data quality rules the job will enforce.
Run pipeline – Run the AWS Glue job.
The data quality rules, for AWS Glue Data Quality, a capability of AWS Glue, come from the approved mappings and run inside the job, which quarantines failing rows before it writes. They’re on by default for file uploads into Amazon S3 Tables, a capability of Amazon S3, which stores Apache Iceberg tables, and optional for the other targets.
Figure 2: The 10-step workflow. Steps 1 and 2 depend on the source type, approval gates follow steps 4 and 6, a failing test returns to step 5, and the job writes to one of three target types
Supported sources and targets
Source
Details
Amazon S3 upload
CSV (including TSV and pipe-delimited), JSON, Parquet, Avro, ORC, and Excel (.xlsx, one worksheet per run). Each file starts its own run.
JDBC database
PostgreSQL, Amazon Aurora, MySQL, MariaDB, Oracle, or SQL Server through the AWS Glue Java Database Connectivity (JDBC) connector, on demand or on a schedule. Incremental loads read only rows newer than the last run, keyed on a timestamp or numeric watermark column.
How we made generated code reviewable and repeatable
In our very first attempt, we asked the model to create the whole AWS Glue script, more than 500 lines on each run. Reviewing that each time wasn’t sustainable. It failed for random reasons, and because the model is non-deterministic, the next run could fail somewhere new no matter how much we optimized the prompt. To solve this, we made the job as deterministic as we could. A human-written/reviewed Jinja2 template for each target type now supplies the scaffold, and the FM writes only the transformation block, typically 5–15 lines for these samples, which is checked against an allowlist of permitted constructs before the job is created.
In our next iteration, these jobs failed inconsistently with GlueArgumentError because different parts of the code used different names for the same job arguments. We made the code itself consistent, but not how the arguments were named. The solution parses the parameters that the rendered code reads with getResolvedOptions, resolves a value for each, and refuses to create the job if one is missing.
Figure 3: Template-first code generation. The model writes only the transform block, and the job’s parameters are validated before the job is created
When we first started testing, we translated the PySpark into pandas, which we thought would simplify testing. But this approach couldn’t express everything PySpark can. It failed inconsistently and could never guarantee the script would work, which defeats the purpose of testing. So now the transform runs in an AWS Glue interactive session on the same Spark version as the job, against a 100-row sample of the source file. Its output is checked for record counts, nulls, and schema compliance. Database sources are tested on rows generated from the schema instead, because the test session in the workflow has no access to your databases.
Human approval gates
To review the results before continuing while you build trust in the pipeline, two gates pause a normal run and wait for approval, one after schema mapping and one after the code passes its tests. A mapping skips review only when each field pair is high-confidence and corroborated by a name match, and a reused mapping goes to review by default.
The gates fail closed, so if the workflow can’t tell whether a step needs review, it waits for a person. A run left waiting at a gate for 72 hours fails, and approvals and rejections are recorded with the reviewer’s identity. Two agents can help along the way. When mapping confidence is low, a complex-mapping agent adds sample values and specific questions to the mapping review. When an AWS Glue job fails, a self-healing agent starts one new run, which regenerates the code after a schema or type error or uses a larger worker after an out-of-memory error. It skips the retry when a second run could duplicate data the failed job already wrote, or when a retry can’t fix the error, such as a permissions problem. The run then stays failed, with the agent’s diagnosis on its detail page. For the full rules, see Approval Gates and the agents guide.
Customer perspective: Montai Therapeutics
Montai Therapeutics applies the same pattern to scientific data. Rather than hand-writing a parser for each new assay format, the team embedded an agent that generates the parser into the ingestion application they already had.
“We have implemented agentic parser generation to ingest semi-structured or variably formatted scientific data into our schema-controlled system of record. Embedding the parser function generation agent into our existing ingestion app has brought lead time to onboard and deploy new assays and protocols to near zero (5 to 10 minutes for parser generation and output checking on an agent runtime), where before there could be days to weeks of developer time spent scripting bespoke parsing functions that may only be used a few times.
The biggest business impact has been the proportion of experimental data that now lands in our data lake rather than in people’s inboxes, which will funnel into improving our drug specificity and efficacy predictive models. Time spent by scientists troubleshooting data formatting issues is now relegated to solving the scientific problems at the core of our business strategy.”
— Kevin Klicki, Senior Engineer – Bioinformatics, Montai Therapeutics
Security considerations
Generated code runs in an isolated test session under a read-only role before an AWS Glue job exists. The solution creates dedicated AWS Identity and Access Management (IAM) roles for pipeline jobs, scoped to that pipeline and bounded by a permissions boundary, with separate roles for agent runtimes. Data is encrypted at rest and in transit, and JDBC credentials are referenced only by their Secrets Manager Amazon Resource Name (ARN), so they don’t appear in job arguments.
You sign in through Amazon Cognito, with multi-factor authentication (MFA) required by default. The dashboard is served through Amazon CloudFront behind an AWS WAF web access control list (web ACL) with managed rules and a rate limit. A second web ACL admits only API requests that come through CloudFront. By default, signed-in users have full dashboard access. The solution doesn’t include identity federation or role-based access, which the README’s Hardening for real data section lists as next steps for production.
Cost to run the solution
We measured these figures on our test deployment in the US West (Oregon) AWS Region (us-west-2) with the repository’s sample files, which have seven or eight columns, and priced the usage at public list prices.
Idle, the solution costs about USD $15–20 per month. About USD $14 is the two AWS WAF web ACLs and their rules, up to USD $5 is Amazon CloudWatch monitoring, depending on your free tier, and storage and one secret add about USD 1. Everything else bills per use.
A run at sample scale costs about USD $0.10–0.25:
Component
Grows with
Per run, measured
Basis
Amazon Bedrock, Claude Sonnet 4.6
Number of fields and model calls
USD $0.05–0.14
About 10,500 tokens over three model calls on a clean run, up to 32,000 with regeneration, at USD $3.30 and USD $16.50 per million input and output tokens (us. inference profile)
AWS Glue interactive session (testing)
Test attempts
USD $0.01–0.02 per attempt
Two G.1X workers at USD 0.44 per data processing unit (DPU) hour
Amazon Bedrock AgentCore runtime at USD $0.0895 per vCPU hour and USD $0.00945 per GB hour
The AI cost depends on the number of fields rather than rows, because prompts carry schemas and at most 100 sample rows. A scheduled pipeline repeats most AI steps on each run and skips only the mapping call when the schema is unchanged. We haven’t yet measured a wider source or a lower-cost model such as Amazon Nova Pro. For current prices, see Amazon Bedrock, AWS Glue, Amazon Bedrock AgentCore, and AWS WAF pricing.
Prerequisites
You don’t need prior experience with Amazon Bedrock AgentCore or Strands Agents. You need the following:
An AWS account, with credentials that can create IAM roles and the solution’s resources in your Region and in US East (N. Virginia) (us-east-1). The AWS WAF stack deploys to us-east-1 because CloudFront requires its web ACL there, so service control policies (SCPs) that restrict Regions must allow it.
Node.js 20 or later, Python 3.12 or later, the AWS Command Line Interface (AWS CLI), and Docker. The deployment script installs the AWS CDK CLI for you.
A host that can build linux/arm64 images, because Amazon Bedrock AgentCore runtime supports only ARM64 containers, with about 100 GB of free disk, mostly for the Docker images. Apple silicon or an AWS Graviton instance such as a t4g.large with a 100 GB gp3 volume builds them natively (see the EC2 build host guide). An x86 host needs QEMU emulation, which ./deploy.sh --check detects. The browser-based AWS CloudShell can’t build the project, because it has no Docker daemon.
An authenticator app for MFA.
Note: This solution uses the us.anthropic.claude-sonnet-4-6 cross-Region inference profile, which is available only from US AWS Regions. If you deploy outside the US, update the model ID in the configuration before deploying.
We tested the solution in us-west-2. Other Regions need the same Amazon Bedrock models and inference profiles, AgentCore, AWS Glue 5.0, and, for S3 Tables targets, Amazon S3 Tables.
Deploy the solution
The deployment script checks the prerequisites, builds the container images, bootstraps both Regions, and deploys eight AWS CloudFormation stacks.
Note: Stack names end in -dev. If you deploy with ./deploy.sh --environment <name>, use -<name> in the commands that follow.
To deploy the solution:
Clone the repository:
git clone https://github.com/aws-samples/sample-agentic-data-ingestion.git
cd sample-agentic-data-ingestion
(Optional) Check the prerequisites without changing anything. The script prints All prerequisite checks passed. or lists each problem with its fix.
./deploy.sh --check
Deploy the solution. A first deployment can take up to roughly 20 minutes on a t4g.large, mostly to build container images.
./deploy.sh
Confirm that the script exits without an error and its last line reads All 8 stacks present and healthy. If a stack is MISSING or failed, check its Events tab in the AWS CloudFormation console, fix the error, and run ./deploy.sh again.
Run the remaining commands in a shell where AWS_PROFILE and AWS_REGION are still set. Self-sign-up is disabled, so you create the first user yourself.
To create your first user and sign in:
Create a user with a random temporary password, replacing <your-email-address> with your email address. The temporary password expires after 24 hours.
aws cloudformation describe-stacks --stack-name AgenticDataIngestion-Hosting-dev \
--query "Stacks[0].Outputs[?OutputKey=='CloudFrontUrl'].OutputValue" --output text
Open the dashboard URL and sign in with your email address and the temporary password. Set your own password, then enroll your authenticator app.
Enable the Claude model
The AI steps call the default model, Claude Sonnet 4.6, which needs a one-time setup per account. The first call to the model enables it, and that call needs AWS Marketplace permissions that the solution’s roles deliberately don’t have, so you make it with your own credentials.
To enable the Claude model:
Submit Anthropic’s one-time use case details, either by choosing an Anthropic model in the model catalog of the Amazon Bedrock console or with the PutUseCaseForModelAccess API. For details, see Request access to models.
Confirm that you get a text reply. If you get AccessDeniedException right after submitting the use case details, wait a few minutes and try again.
Without this setup, the deployment still works, but the AI steps fail with AccessDeniedException.
Run a pipeline
Next, you create a pipeline that loads a sample customer file into a new Amazon S3 Tables table, then review the run. With the sample file, a run takes roughly 5–15 minutes plus the time you spend at the gates. The following interactive demo shows the same steps, and Human approval gates describes what each gate checks.
On the dashboard, choose Create Pipeline. On Name & Description, enter a Pipeline Name, and choose Next.
On Source, for Source Type, choose S3 Upload, and choose Next.
On Target Destination, for Target Type, choose S3 Table Bucket, and then choose Create new.
Enter a Bucket name, Namespace, and Table name. The bucket name must be unique in your account and Region (see the naming rules). For Write Mode, keep the default, Append, and choose Next.
On Target Schema, for Schema Source, choose Upload, then use Choose file to select tests/test-data/target_schema.json from your local clone of the repository. Choose Next.
On AI Model & Options, for AI Model, choose Claude Sonnet 4.6. Keep the approval and data quality settings at their defaults, and choose Next.
On Review & Create, check the settings, and choose Create Pipeline.
To run and review the pipeline:
On the pipeline’s overview page, choose Upload File.
Select tests/test-data/customer_data_4.csv from your local clone, and choose Upload. The upload starts a run. The file’s column names differ from the target schema (for example, email_address instead of email), which gives the mapping step something to decide.
When the run pauses at a gate, choose Approvals in the navigation bar.
Choose Review next to the pending approval, check the mapping or the code, optionally add a comment, and choose Approve or Reject. Repeat steps 3 and 4 for each gate the run reaches.
When the run completes, open it from Recent Runs on the pipeline’s overview page, and review the Step Flow, Code, and Data Quality tabs.
Note: The mapping review lists each field pair with its Confidence, and the code review shows the transform with its Test Report.
To read from a database instead, choose JDBC Database as the Source Type. You need a Secrets Manager secret with username and password keys, an Amazon S3 gateway endpoint in the database’s subnet, and a security group that allows traffic from itself on the database port. The JDBC source guide covers the details.
Clean up
Delete your pipelines first, while the dashboard is still deployed.
To clean up the deployed resources:
For each pipeline, choose Archive Pipeline on its overview page. Then choose Archived in the navigation bar, choose Delete next to the pipeline, and confirm with Continue and Permanently Delete. This removes the pipeline’s AWS Glue job, rules, and uploaded files, and for a database source the AWS Glue connections and crawler it created.
From the repository root, list what the teardown script would delete. Without --force, it deletes nothing.
Delete the stacks. If you deployed with --environment, pass the same option. The script also deletes the DynamoDB tables the Data stack retains and the project’s IAM roles and policies across the account, because IAM is global.
Delete what your pipelines created at run time: the S3 Tables resources, which hold the ingested data and bill for storage, and any AWS Glue databases or secrets left with the project’s name prefix. Find the table bucket ARN with aws s3tables list-table-buckets, and the leftover names with the two list commands.
The CDK bootstrap stack, CDKToolkit, stays in both Regions. Delete it only if nothing else in the account deploys with CDK.
Conclusion
The approval gates are where this gets interesting in practice. The mapping review in particular surfaces assumptions about your data that are worth catching before a job runs in production. We’ve seen how the model sometimes picks a reasonable mapping that’s technically wrong for the business context, which is exactly why the human review step exists. We’ve only measured our own files and sources so far. If you run it on a wide source, say, 100 columns from a production instrument export, we’d genuinely like to know whether the mapping and costs held up.
It’s a reference solution, so the next step is adding your own sources, targets, data quality rules, approval policies, and production identity setup.
Connecting enterprise systems to modern analytics and AI platforms often requires building brittle pipelines, duplicating data, or sacrificing the governance and business context that makes the data trustworthy. Today we’re introducing the integration of Workday Data Cloud with AWS. With this integration you get bi-directional, zero-copy access to Workday’s governed people and money data from the AWS analytics and AI services that you already use.
Workday Data Cloud overview
Workday Data Cloud is an open, secure, and headless data platform that makes Workday’s people and money data available in the tools where developers build, with its semantic definitions, permission models, metric logic, and audit controls intact. It provides a curated, unified view of people and money data through the Workday Data Lake, bi-directional zero-copy access to that data through Workday Data Connect using Apache Iceberg, and near real-time SQL access for applications and AI agents through Workday Live Data Query.
AWS analytics overview
AWS provides a comprehensive set of analytics and AI services that work together for data engineering, analytics, and machine learning. Here’s how the key services come together in the context of the Workday Data Cloud integration:
Amazon SageMaker Unified Studio
Amazon SageMaker Unified Studio (SMUS) is a unified development environment for data analytics and AI. It brings together data access, querying, visualization, and notebook-based development in one place. With SMUS, developers can connect to Workday Data Cloud, explore datasets interactively, run SQL queries, and build machine learning models, all without switching between multiple tools or interfaces.
Amazon Athena
Amazon Athena is a serverless, interactive query service to analyze data directly in Amazon Simple Storage Service (Amazon S3) using standard SQL. With the Workday Data Cloud integration, analysts and developers can run ad hoc queries against Workday data stored as Iceberg tables without needing to set up or manage infrastructure.
Amazon Redshift
Amazon Redshift is a cloud data warehouse that delivers fast query performance on structured and semi-structured data using SQL. Organizations already using Amazon Redshift for their analytics workloads can now incorporate Workday people and money data through the Glue Data Catalog federation for cross-domain analytics without data movement.
AWS Glue Data Catalog
AWS Glue Data Catalog serves as the central metadata repository that makes Workday data discoverable across the supported AWS analytics services. Through the integration, Workday’s Iceberg REST Catalog is registered as a federated catalog in AWS Glue, which means any AWS service that reads from the AWS Glue Data Catalog such as Amazon Athena, Amazon Redshift, Amazon EMR, and Amazon SageMaker AI can automatically discover and query Workday datasets without additional configuration.
Glue Data Catalog also works in the other direction, letting Workday query data that lives in AWS. Customers can register the Iceberg REST Catalog endpoint of the AWS Glue Data Catalog as an external catalog in Workday Data Cloud. Workday users can then browse and query Apache Iceberg tables stored in Amazon S3 in near real-time, without copying the data into Workday.
AWS Lake Formation
With AWS Lake Formation, you can set up and manage a secure data lake. In this integration, AWS Lake Formation provides the fine-grained permission layer that governs who can access Workday data within the AWS environment, complementing the governance that Workday already applies at its data layer. Administrators can scope each analyst or application to specific databases, tables, rows, or columns.
Amazon S3
Amazon S3 is the foundational storage layer for data lakes on AWS. In the context of this integration, Amazon S3 stores Apache Iceberg tables that can be queried from Workday, so organizations can query and analyze data in AWS alongside their Workday data.
Workday Data Cloud and AWS integration overview
The integration between Workday Data Cloud and AWS enables bi-directional, zero-copy data access. This means data doesn’t need to be copied or replicated between Workday and AWS. Instead, each platform can query the other’s data in place, respecting existing governance and security controls on both sides.
Accessing data in AWS from Workday
Workday applications and AI agents can access data stored in AWS, enriching HR and finance workflows with external business data. Developers building agents or analytics within the Workday platform can query Apache Iceberg tables stored on Amazon S3 by registering the Iceberg REST Catalog endpoint of the AWS Glue Data Catalog as an external catalog in Workday Data Cloud.
Zero-copy federation
Workday Data Cloud federates to the AWS Glue Data Catalog using OAuth 2.0 authentication. After registration, Workday users can discover and query Iceberg tables backed by AWS directly from within Workday Data Cloud without copying data. AWS Lake Formation defines which databases and tables the Workday connection can read, whereas Workday’s Configurable Security controls which individual Workday principals can access the federated tables. This means an AI agent handling workforce planning in Workday can pull in revenue forecasts from an Iceberg table on AWS. Combining those financial projections with headcount data gives HR planners hiring recommendations to review, accounting for both business growth and budget constraints.
Accessing data in Workday from AWS
AWS analytics and AI services can access Workday’s governed people and money data. There are two primary patterns for AWS to query Workday data, each optimized for different use cases:
Live Data Query
Some use cases require near real-time access to Workday data, such as an AI agent checking current headcount or a dashboard showing today’s financial close status. For these, developers can use Workday Live Data Query. From Amazon SageMaker Unified Studio, Amazon Athena, Amazon EMR, or AWS Glue, users connect to Workday through the Live Data Query connector and execute SQL queries directly against live Workday datasets. The query runs within Workday’s governed environment and results flow back in near real-time. This is ideal for operational AI agents, near real-time dashboards, and any application where data freshness is critical.
Figure 1: Querying live Workday supplier data from an Amazon SageMaker Unified Studio notebook with Workday Live Data Query
Zero-copy federation with Apache Iceberg
For near real-time analytics, machine learning (ML) training, and large-scale data exploration, developers access Workday data through Workday Data Connect’s Apache Iceberg integration. By registering the Workday Iceberg REST Catalog in AWS Glue Data Catalog or AWS Lake Formation, all Workday datasets appear as standard Iceberg tables discoverable by any AWS analytics service. The compute runs on the customer’s AWS environment (using Athena, Amazon Redshift, Amazon EMR, or SageMaker AI) while the data stays in Workday Data Cloud.
Figure 2: Querying a Workday Data Connect Iceberg table with standard SQL in the Amazon Athena query editor
Figure 3: Querying a Workday Data Connect Iceberg table with standard SQL in Amazon Redshift Query Editor v2.
Figure 4: Browsing Workday Iceberg tables with PySpark in a SageMaker Unified Studio notebook using Workday Data Connect
What this means for customers
This integration changes how organizations work with their people and money data for analytics and AI. Here’s what it unlocks:
Organizations no longer need to build and maintain complex extract, transform, and load (ETL) pipelines to get Workday data into their analytics environment, which removes data silos without duplicating data. The data stays where it lives, governed and accurate, while remaining fully accessible for analysis and AI.
When AI agents and models can access Workday data with its full business context, developers spend less time reverse-engineering business logic and rebuilding permission models. That context includes who has access to what, what a metric actually means, and how calculations are defined.
Workday’s permission model, audit controls, and business logic travel with the data, and AWS Lake Formation adds governance on the AWS side. The result is data access that is both open and controlled, which is exactly what regulated industries and enterprise security teams require.
Instead of building pipelines, monitoring data freshness, and reconciling duplicates, data teams can focus on building analytics and machine learning applications that drive business outcomes.
Use case walkthrough: AI-powered workforce analytics
Consider a Chief People Officer who wants to understand the relationship between employee engagement scores, compensation benchmarks, and attrition patterns across the organization. Today, this requires extracting data from Workday, loading it into a separate analytics platform, joining it with market data, and building custom reports. This process takes weeks and produces stale results.
With the Workday Data Cloud and AWS integration, a data team can perform the following steps:
Connect to Workday Data Cloud from AWS Glue using the pre-built Workday connector.
Explore workforce datasets such as compensation, tenure, engagement, and performance directly, with full semantic context (job levels, org hierarchies, and tenure calculations) already defined.
Join Workday people data with market compensation benchmarks and recruiting pipeline data stored as Iceberg tables on Amazon S3, all through standard SQL in Athena or SageMaker AI notebooks.
Build a machine learning model in SageMaker AI that predicts attrition risk based on the combined dataset.
Deploy an AI agent that flags high-risk attrition patterns for HR business partners to review and act on. The agent uses Live Data Query for near real-time signals and batch Iceberg access for historical trend analysis.
The entire workflow runs without any data leaving its governed environment, without any custom pipelines to maintain, and with full auditability at every step.
Getting started
The Workday Data Cloud integration with AWS is generally available.
Amazon SageMaker Unified Studio users can connect to Workday Data Cloud directly through the Workday Live Data Query connector or the Workday Iceberg REST Catalog connector.
Workday Live Data Query connections can also be created in the AWS Glue console, and users can query live Workday data from Amazon Athena, Amazon EMR, and AWS Glue ETL jobs.
AWS Glue and AWS Lake Formation users can register the Workday Iceberg REST Catalog as a federated catalog to make Workday datasets discoverable across AWS analytics services.
Workday users seeking to query AWS data can register their Glue Data Catalog Iceberg REST endpoint as an external catalog in Workday Data Cloud.
For deeper technical walkthroughs and step-by-step configuration guides, refer to the following resources:
This integration represents a new model for enterprise data access, where governed data flows freely between platforms without compromising security, accuracy, or business context. We are excited to see what customers build with Workday Data Cloud and AWS together.
Most of the cost of adopting something new isn’t the new thing, it’s the move. Moving a Hive table to Apache Iceberg has typically meant weeks of engineering work. Last week, Amazon S3 Tables turned that into three steps: start, sync as often as you need, complete. The source stays writable except for a few minutes at cutover. The same week, Amazon DynamoDB started loading data from S3 into tables that already exist.
The pattern I like is that neither one asks you to stop what’s running. That’s also the way to read the agent news this week. The new Amazon Bedrock AgentCore Runtime is a single field on the runtime you already have, and Web Answer is a tool you attach to a gateway you already run. Now, let’s get into this week’s AWS news…
Headlines The new AgentCore Runtime: elastic, optimized, and consistently fast starts – If you run agents on AgentCore and haven’t tried the new runtime since it became generally available, it’s worth a look. It changes two things. First, memory: sessions start small, page in more on demand, and give memory back when it goes cold instead of holding the peak, so you pay for what your agent uses. Second, cold starts: AgentCore prepares your environment once, snapshots it, and restores the snapshot for every new instance. In the team’s tests, that kept P75 cold starts at about 2 seconds for images from 200 MB up to 2 GB, while the original runtime rose from roughly 5.4 seconds to nearly 30 seconds as images grew. The per-unit rate is higher, but you use far fewer GB-hours, so the team expects most agents to see a lower bill, though that isn’t guaranteed.
To opt in, you set platformVersion to V2 when you create or update a runtime. Create and update take several minutes while the snapshot is prepared, and your container must report healthy on /ping within 120 seconds, so report health only after initialization finishes. The docs cover how to optimize your agent for V2. V2 is available in 10 Regions, and committed baseline pricing is coming soon.
Amazon S3 Tables now offer managed migration of Apache Hive tables to Apache Iceberg – You can now migrate Parquet tables registered in the AWS Glue Data Catalog into S3 Tables without building a pipeline or provisioning compute. S3 Tables validates the source and produces a compatibility report covering every object in scope. Each sync copies only what changed, so production keeps writing until cutover. Afterward you can query the table with Amazon Athena, Amazon SageMaker Unified Studio, or any engine that speaks the Iceberg REST API. You pay only for the data copied, with no charge for the conversion, and objects in S3 Intelligent-Tiering keep their tier. At launch it works within the same account and Region, in 10 Regions.
Last week’s launches Here are some launches and updates from this past week that caught my attention:
Amazon DynamoDB now supports bulk put items – You can now load line-delimited DynamoDB JSON or Amazon Ion files from Amazon S3 into existing tables as a managed, asynchronous job. Each record can carry its own condition expression, so one file can mix plain, insert-only, and version-guarded writes. Writes use dedicated system capacity and cost less than the equivalent per-request writes. An Accelerated tier handles deadline-bound jobs. The Database blog post gives illustrative Accelerated times of less than 1 hour for 100 million 1 KB items. One thing to know before you start: canceling doesn’t roll back items already written.
Announcing Web Answer on Amazon Bedrock AgentCore – You can now give an agent a single tool call that returns a synthesized, cited answer to a natural-language question, instead of building your own search, retrieval, and citation pipeline. Web Answer plans its own searches, runs several in parallel, and decides when it has enough evidence. You attach it as a target on AgentCore Gateway and call it over MCP, and you can limit it with domain include and deny lists and publish-date filters. It’s available in US East (N. Virginia). The getting started post explains when to use it instead of Web Search, which returns ranked results for your own model to synthesize.
AWS Lambda now supports queues for Apache Kafka in self-managed Kafka event sources – You can now process records from a single Kafka partition across many parallel AWS Lambda invocations. Classic consumer groups cap parallelism at the partition count. Queue mode uses Kafka share groups and needs Kafka 4.2 or later with share groups enabled. It works with self-managed clusters and managed offerings such as Confluent Cloud. You give up ordering and get at-least-once delivery, so your functions need to be idempotent. The Compute blog walkthrough covers poller scaling and when to keep stream mode.
AWS announces AWS Interconnect – last mile preview with Equinix – You can now set up a private, managed connection from Equinix’s network of 282 data centers to AWS without ordering cross-connects or configuring routers. Capacity is quad-redundant across two locations and four links, with BGP and VLANs configured for you, a 99.99% availability SLA, and MACsec by default. You pick a Region, bandwidth, and AWS Direct Connect gateway, then paste the activation key into Equinix Fabric. The preview covers the San Jose metro and, as of last Thursday, Northern Virginia, with 1 Gbps connections at no charge.
AWS Security Hub now provides an SBOM inventory for your compute resources – You can now see every software package installed across your organization’s Amazon EC2 instances, Amazon ECR images, and Lambda functions in AWS Security Hub, with each package’s version and how many resources run it. That’s the list you want the next time a widely used library has a vulnerability. The inventory builds on the SBOMs that Amazon Inspector already generates, so it fills in automatically wherever Inspector is enabled. It’s included in Security Hub Essentials at no additional cost.
For a full list of AWS announcements, be sure to keep an eye on the What’s New with AWS page.
Other AWS news Here are some additional posts and resources that you might find interesting:
Serverless ICYMI Q3 2026 – Julian Wood’s quarterly recap is a quick serverless catch-up before re:Invent: Lambda SnapStart for container images, a 90-minute timeout on Lambda Managed Instances, Lambda MicroVMs in 10 Regions, 1 MiB payloads in Amazon SNS, and the new AgentCore Runtime.
AWS contributes a large-transaction binary log optimization to MySQL – With binlog on, a huge transaction holds a global commit lock while its events are copied, blocking every other commit. The optimization, which Amazon Aurora MySQL has run in production since 2019, promotes the spill file into the binlog instead of copying it. In AWS’s tests, commit latency for a 50 GiB transaction dropped from about 7 minutes to about 2 to 2.5 seconds. It has now shipped to community MySQL.
How OrderServ achieved up to 64% cost savings with multi-tenant ECS – Cognizant’s food-ordering platform went from one Amazon ECS cluster per brand on AWS Fargate to a shared cluster on EC2 Auto Scaling groups with warm pools. The 64% applies to a 3-year Compute Savings Plan (47% with a 1-year plan). Scaling time also fell from 5–7 minutes to 30–60 seconds.
Upcoming AWS events Check your calendar and sign up for upcoming AWS events:
AWS re:Invent – re:Invent returns to Las Vegas from November 30 to December 4. The event catalog is live and reserved seating is open, so register and claim your spots before they fill up.
Join the AWS Builder Center to connect with builders, share solutions, and access content that supports your development. Browse here for upcoming AWS-led in-person and virtual events and developer-focused events.
That’s all for this week. Check back next Monday for another Weekly Roundup!
– Daniel Abib
This post is part of our Weekly Roundup series. Check back each week for a quick roundup of interesting news and announcements from AWS!
Today, we’re announcing a simple, cost-effective path for data lake modernization. Amazon S3 Tables now support managed migration of your Apache Hive tables to Apache Iceberg. Migration works with Parquet tables in Amazon S3 that are registered in the AWS Glue Data Catalog and allows you to upgrade your data lake with no pipelines to build or compute to provision, while production workloads keep running.
Apache Iceberg has become the open standard for large analytics datasets. It lets you manage petabyte-scale tables with features like schema evolution, hidden partitioning, and time travel queries, while keeping your data open and queryable with any Iceberg-compatible engine. Amazon S3 Tables offer fully managed storage purpose-built to keep Iceberg tables performant and cost-effective as they grow, with features like automatic maintenance, optimization, replication, and S3 Intelligent-Tiering built-in.
What is new Previously, migrating Apache Hive tables to Apache Iceberg could take weeks of engineering work to build and manage the required infrastructure. Converting data types and building rollback capabilities added operational complexity. Now, this is available as a managed, API-driven operation.
S3 Tables handle the entire migration workflow, including data validation, compatibility checks, type conversions, file recompression, and compaction. Before copying any data, S3 Tables identify every source object in scope and generate a compatibility report. You can sync as many times as you need without stopping writes to your source table, except for a few minutes during cutover. Once you are ready, you can complete the migration, minimizing time that tables are offline.
Compared to self-managed approaches, S3 Tables managed migrations are cost-effective because you pay only for the data copied, with no charge for the Hive-to-Iceberg conversion, and source objects in S3 Intelligent-Tiering stay in their current access tier.
A first look at the migration To migrate an AWS Glue Hive table, choose your destination table bucket in the S3 console, then choose Create table from migration.
Create a namespace and table name for your destination Iceberg table. The destination table is created using recommended default settings tuned for query performance and storage efficiency.
When you start the migration, S3 Tables validate the source table, generate a compatibility report, and begin copying data. The destination table is read-only during the migration. Once you complete migration, the destination table is promoted to read-write.
To catch up the destination table with changes in the source, call sync-table-migration as many times as you need before you complete the migration. Each sync copies only what changed.
If you’re using coding agents like Kiro, the migrating-hive-tables-to-s3-tables skill in the Agent Toolkit for AWS provides step-by-step migration guidance with safety guardrails for agents. The skill can:
Analyze existing IAM policies and recommend equivalent destination policies
Validate the migration plan before getting started
Execute the Start → Sync → Complete API calls
Monitor job progress and guide validation and cutover
Now available Amazon S3 Tables managed migration is available today in US East (N. Virginia, Ohio), US West (Oregon), Asia Pacific (Mumbai, Singapore, Sydney, Tokyo), and Europe (Frankfurt, Ireland, Stockholm) Regions. At launch, the capability supports AWS Glue-registered Hive tables stored in Parquet format within the same AWS account and AWS Region. If you want to call APIs, search documentation, find regional availability, or troubleshoot about this new feature, try using the AWS MCP Server and plugins with your preferred AI tool.
Some numbers are hard to picture until you sit with them for a moment. Last week we published the Prime Day 2026 metrics, and the one that stuck with me is 2.3 quadrillion: the daily requests Amazon ElastiCache peaked at during the event. Prime Day ran back in June, so this post always lands as a retrospective, and that gap is part of what makes it worth reading. By the time the numbers reach you, the only evidence that any of it happened is that nothing went wrong.
The rest of the week pulled in a different direction: smaller, cheaper, and more constrained. Claude Haiku 5.5 arrived on Amazon Bedrock at roughly 75 percent less than Haiku 4.5, Amazon Nova 2.5 Sonic made voice agents quicker on their feet, and Strands Box showed up to put real boundaries around what an agent is allowed to do. Now, let’s get into this week’s AWS news…
Headlines
All the numbers: Amazon Prime Day 2026 powered by AWS is the latest entry in a tradition that goes back to 2016, and the scale is still difficult to hold in your head. Over the four days of Prime Day, Amazon DynamoDB processed more than 59 trillion requests while peaking at 192 million requests per second, and kept single-digit millisecond responses throughout. AWS Lambda handled over 2.3 trillion invocations per day. Amazon EBS peaked above 24.8 trillion I/O operations, moving more than an exabyte of data daily. Amazon ECS launched an average of 158.3 million tasks per day on AWS Fargate, a 47.7 percent jump over last year, and AWS Graviton powered up to 49 percent of the Amazon EC2 compute that Amazon.com used.
The number I keep coming back to, though, isn’t a throughput record. The team ran more than 44,000 AWS Fault Injection Service experiments ahead of the event, more than six times what they ran in 2025. Those are deliberate failures injected on purpose, months in advance, so that the trillions of requests above turn into an ordinary shopping afternoon. If you’re preparing for your own peak moment, AWS Countdown Premium is built for exactly that kind of planning.
Last week’s launches
Here are some launches and updates from this past week that caught my attention:
Claude Haiku 5.5 is now available on AWS – You can now use the fastest model in the Claude 5.5 family on Amazon Bedrock and Claude Platform on AWS, at around 75 percent less than Claude Haiku 4.5 for most tasks. It’s the first Haiku with effort controls, so you can tune cost against intelligence per task instead of fixing one setting for a whole workload. It pairs naturally with Claude Opus 5.5: Opus plans and makes the judgment calls, and because Haiku is fast and cheap, you can run many Haiku subagents in parallel for routing, classification, and small code changes across many files.
Amazon Nova 2.5 Sonic for voice agents – You can now build real-time voice agents on a speech-to-speech Amazon Nova model with better reasoning, instruction following, and tool-calling accuracy, plus lower latency. That combination matters for multi-step work: a support agent can look up an order, check return eligibility, and start the return inside one conversation. It keeps expressive voices in seven languages, controllable turn-taking, and a 256K context window, and pairs with Strands Bidi Agents, now generally available, to get a production voice agent going in a few lines of code.
Amazon GuardDuty RDS Protection now detects data exfiltration and destruction – Amazon GuardDuty now looks past login anomalies to the queries themselves on Amazon Aurora PostgreSQL and Amazon RDS for PostgreSQL. RDS Protection for data activity builds behavioral baselines and uses ML-based anomaly detection plus threat intelligence to flag unusual data access, with no agents, extra infrastructure, or database configuration changes. This closes a real gap: once an attacker has valid credentials from phishing or a misconfiguration, their queries can look indistinguishable from your application’s.
AWS Lambda supports OAuth for self-managed Apache Kafka event sources – You can now authenticate Lambda Kafka consumers through your enterprise identity provider, such as Amazon Cognito or Okta. Event source mappings previously supported only SASL/PLAIN, SASL/SCRAM, and mTLS, which left teams in regulated industries unable to use Kafka ESM at all. Now you get the automatic scaling, batching, error handling, and event filtering of Kafka ESM with the same identity governance you apply everywhere else. It works with self-hosted clusters and managed offerings including Confluent Cloud, Aiven, and Redpanda.
For a full list of AWS announcements, be sure to keep an eye on the What’s New with AWS page.
Other AWS news
Here are some additional posts and resources that you might find interesting:
Introducing Strands Box: AI agent sandboxes powered by Dogwood – As more of us let agents run shell commands and call APIs without approving every step, isolation alone stops being enough. Strands Box is an open source sandbox (Apache 2.0, developer preview) that combines OS-level containment with fine-grained policies written in Dogwood, so permissions can depend on what the agent has already done. You can say “let the agent post to the incident channel, but no more than three times every 10 minutes” and have that enforced from outside the agent’s process. It also keeps real credentials out of the agent’s environment by attaching them at an egress gateway.
AWS Continuum sets a new standard in autonomous code security – Related to that theme, AWS Continuum for Penetration Testing now integrates into your CI/CD pipeline in public preview, turning penetration testing into a deploy-time event instead of something that happens off to the side. Developers get findings with severity, affected endpoints, and remediation guidance right in the pipeline output, and the pipeline re-tests to verify fixes.
Check your calendar and sign up for upcoming AWS events:
AWS re:Invent – re:Invent returns to Las Vegas from November 30 to December 4, and reserved seating is now open. The session catalog is live, so register and claim your spots in chalk talks, workshops, and builders’ sessions before they fill up.
AWS Community Days – Community-led conferences planned and delivered by community leaders, and this is a busy stretch. Upcoming stops include San Francisco (October 13), Miami (October 14), Brisbane (October 16), Cape Town (October 16), Malta (October 16), and Mumbai (October 17). Here in Brazil, the community calendar has more editions coming before the end of the year.
Join the AWS Builder Center to connect with builders, share solutions, and access content that supports your development. Browse here for upcoming AWS-led in-person and virtual events and developer-focused events.
That’s all for this week. Check back next Monday for another Weekly Roundup!
– Daniel Abib
This post is part of our Weekly Roundup series. Check back each week for a quick roundup of interesting news and announcements from AWS!
Bad data rarely announces itself. It slips into an Amazon EMR pipeline quietly. A null where there should be a value. A timestamp in the wrong format. A referential key that no longer exists. It travels downstream until it surfaces as a wrong number in a dashboard, a failed downstream job, or a business decision made on data nobody verified.
For teams running large-scale data processing on Amazon EMR, choosing a data quality strategy has meant picking between two trade-offs. You can build your own quality checks in Apache Spark using an open source library like Deequ. With this approach, you can customize checks to your exact pipeline, but it adds custom code your team must maintain, with no centralized ruleset management and no consistent quality catalog across pipelines. Or you can route your data through AWS Glue to access its managed data quality capabilities. This approach minimizes the code you need to maintain but turns data quality validation into a separate step and adds another engine to your pipeline.
Today, there is a third option.
Amazon EMR Data Quality built on AWS Glue is now available natively on Amazon EMR, bundled in AWS runtime for Apache Spark (emr-spark-8.1.0) and later versions. You can write data quality rules using the same Data Quality Definition Language (DQDL) used in AWS Glue. Run them directly inside your Amazon EMR Spark jobs, across each of the three Amazon EMR deployment modes: Amazon EMR on EC2, Amazon EMR Serverless, and Amazon EMR on EKS.
This post walks through two patterns for using AWS Glue Data Quality, a capability of AWS Glue, on Amazon EMR. The first shows a lightweight ad hoc validation workflow, useful for exploratory processing and pipeline-local checks. The second builds on the Apache Iceberg Write-Audit-Publish (WAP) pattern. An extract, transform, and load (ETL) job writes data to an Iceberg branch, retrieves a managed ruleset from the AWS Glue Data Catalog, and validates the branch. Only if the data passes your quality bar does it merge to the main table. By the end of this post, you will have working examples of both patterns ready to run on any mode of Amazon EMR.
What is Amazon EMR Data Quality?
With Amazon EMR Data Quality, you can define and run data quality rules against your datasets. At its core is the Data Quality Definition Language (DQDL), a declarative rule syntax. With DQDL, you can express constraints like completeness, uniqueness, value ranges, referential integrity, and statistical distributions in plain, readable statements.
DQDL also includes machine learning (ML)-based anomaly detection. Rather than setting explicit thresholds, DetectAnomalies rules learn the statistical baseline of your data across runs and flag deviations automatically. This is useful for metrics that shift over time, like daily record counts or revenue totals, where a fixed range rule would require constant maintenance.
You can define rules inline within a job or store them as managed rulesets in the AWS Glue Data Catalog, a centralized metadata repository for table definitions and data quality rulesets. After the rules are stored, you can version these rulesets, share them across teams, and reuse them across multiple pipelines. The evaluator returns per-rule pass or fail results and an overall quality score. Your job can inspect the score to take action: fail the pipeline, write results to Amazon Simple Storage Service (Amazon S3), trigger an alert, or conditionally merge data.
You can now run this rule engine directly inside your Spark jobs on Amazon EMR. The same DQDL rulesets you author for AWS Glue work without modification.
For a full reference on DQDL syntax and rule types, see the AWS Glue Data Quality documentation.
Prerequisites and setup
Amazon EMR is a managed service for running Apache Spark and other open source big data frameworks on AWS. It offers three deployment modes: Amazon EMR on EC2, Amazon EMR Serverless, and Amazon EMR on EKS.
Before running the examples in this post, make sure you have the following in place.
Amazon EMR release: Amazon EMR Data Quality is bundled in AWS runtime for Apache Spark (emr-spark-8.1.0) and later versions across Amazon EMR on EC2, Amazon EMR on EKS, and Amazon EMR Serverless. No bootstrap action or additional installation is required. The library is available as part of the release.
AWS Identity and Access Management (IAM) permissions: The execution role for your Amazon EMR job needs the following permissions:
glue:AccessDataQualityRuntimeConfiguration to publish data quality results to the AWS Glue Data Catalog.
glue:CreateDataQualityRuleset to create managed rulesets in the AWS Glue Data Catalog.
glue:GetDataQualityRuleset to retrieve managed rulesets from the AWS Glue Data Catalog.
glue:GetDataQualityResult to read prior quality results.
glue:PublishDataQuality to submit data quality results to the AWS Glue Data Catalog.
glue:GetDatabase and glue:GetTable for catalog access.
Standard Amazon S3 read/write permissions for your data and output locations.
Pattern 1: Ad hoc data quality validation
This pattern defines data quality rules directly inside your Amazon EMR Spark job, with no externally managed ruleset to maintain.
The use case
Your team ingests a raw CSV file from a third-party vendor and needs to validate it before loading it into your data lake. The rules are straightforward: check that the record ID is never null, that revenue values are non-negative, and that country codes conform to an allowed list. This is a one-off check that lives entirely within the job. There is no centralized ruleset to manage, and the goal is to validate data quality before the load.
This pattern works well for:
Exploratory or one time processing pipelines.
Early-stage pipelines where rules are still evolving.
Lightweight validation that does not require centralized governance.
How it works
You define your DQDL rules inline as a string, pass your DataFrame and the rules to EvaluateDataQuality, and inspect the results to decide how the job should proceed.
To validate data quality inline using PySpark
To implement this pattern using PySpark, see the following code sample, which can be run on all three Amazon EMR deployment modes:
import os
from pyspark.sql import SparkSession
from awsdataquality.transforms import EvaluateDataQuality
spark = SparkSession.builder \
.appName("dq-ruleset-catalog") \
.enableHiveSupport() \
.getOrCreate()
# Read new incoming data
input_df = spark.read.parquet("s3://amzn-s3-demo-sales-data/sales_data/incoming_data/")
# Contains our DQDL rules and analyzers. Analyzers submit statistics to the AWS Glue service for inspection. This can help create new rules.
ruleset = """
Rules = [
RowCount > 0,
IsPrimaryKey "order_id",
Completeness "customer_email" >= 0.95,
ColumnValues "order_status" in ["PENDING","SHIPPED","DELIVERED","RETURNED"],
ColumnValues "net_amount" between 0.0 and 25000.0
]
Analyzers = [
AllStatistics "net_amount",
DistinctValuesCount "country",
RowCount
]
"""
# Publishing options for the results of the data quality evaluation
publishing_opts = {
"dataQualityEvaluationContext": "blog-post-dq-evaluation-context",
"enableDataQualityResultsPublishing": "true"
}
# AWS Glue Data Quality uses the additional_options parameter to configure advanced evaluation behaviors, output formats, anomaly detection and performance tuning for data quality checks.
additional_opts = {"compositeRuleEvaluation.method": "ROW"}
# This set tells the Data Quality Evaluator if there are other data sources that
# we need to pull in for checks such as cross table reference checking.
additional_sources = {}
# Evaluate the ruleset against the data frame created by reading the parquet files and save
# the results in dq_results as a DataFrame.
dq_results = EvaluateDataQuality.apply(input_df, ruleset, publishing_opts, additional_opts,
additional_sources)
print(f"{dq_results.count()} rule result row(s)") # forces evaluation
# Iterate through the DQ results for any failed rules and if there are any failed
# rules, throw an exception to stop the job.
failures = []
for row in dq_results.collect():
if row["Outcome"] == "Failed":
failures.append(f"Rule: {row['Rule']} | Reason: {row['FailureReason']}")
if failures:
failure_summary = "\n".join(failures)
raise RuntimeError(f"Data quality checks failed:\n{failure_summary}")
# Write out data into the Iceberg table sales_data table
input_df.writeTo("company_sales.sales_data").append()
print(f"all rules passed; appending {input_df.count()} row(s) to company_sales.sales_data")
The preceding script passes the incoming DataFrame, an inline ruleset, and publishing options to EvaluateDataQuality, which runs the ruleset and returns a results DataFrame. The results DataFrame lists each rule with a Passed or Failed outcome and, for failed rules, the reason. The publishing options control if and where the results get published. The script raises an error and stops if any rule fails. If every rule passes, it appends the incoming data to the company_sales.sales_data table.
What the data quality results look like
The EvaluateDataQuality.apply() function returns the results as a DataFrame containing each rule, whether it passed or failed, and the evaluated rule. Your job can read this DataFrame and branch its logic accordingly: writing clean records to Amazon S3, routing failed records to a quarantine path, or halting the pipeline entirely. Following is sample output of the code earlier:
Rule
Outcome
FailureReason
EvaluatedMetrics
RowCount > 0
Passed
NULL
{RowCount -> 50000.0}
IsPrimaryKey “order_id”
Passed
NULL
{Uniqueness -> 1.0, Completeness -> 1.0}
Completeness “customer_email” >= 0.95
Passed
NULL
{Completeness -> 0.97924}
ColumnValues “order_status” in […]
Failed
Value: 0.99598 does not meet …
{ColumnValues.Compliance -> 0.99598}
ColumnValues “net_amount” between 0.0 and 25000.0
Failed
Value: -2228.87 does not meet …
{Minimum -> -2228.87, Maximum -> 3394.51}
RuntimeError: Data quality checks failed:
Rule: ColumnValues "order_status" in ["PENDING","SHIPPED","DELIVERED","RETURNED"] | Reason: Value: 0.99598 ...
Rule: ColumnValues "net_amount" between 0.0 and 25000.0 | Reason: Value: -2228.87 ...
Pattern 2: Iceberg Write-Audit-Publish with managed rulesets
This pattern gates data promotion on a centrally managed ruleset, merging new data into your main table only after it passes your quality checks.
The use case
Your team runs a nightly ETL job that transforms raw transactional data and writes it to an Apache Iceberg table. Apache Iceberg is an open table format for large analytic datasets that supports schema evolution, time travel, and branching on Amazon S3. Rather than writing directly to the production table and discovering quality issues after the fact, you want a safety gate. Write to a staging branch, validate it against your organization’s data quality standards, and only promote the data to the main table if it passes.
When combining AWS Glue Data Quality with WAP, you define your quality rules once in the AWS Glue Data Catalog and have your data governance team own them. You enforce them automatically at promotion time, without touching the pipeline code. Combined with managed rulesets in the AWS Glue Data Catalog, you get quality enforcement that is consistent and auditable. The data quality rules are also decoupled from the job code and changing them does not require touching the pipeline.
This pattern works well for:
Production ETL pipelines where bad data reaching the main table has downstream consequences.
Organizations with centralized data governance teams that own and version quality standards.
Apache Iceberg-based lakehouses where the WAP pattern is already in use.
How it works
The flow has four steps:
Retrieve the ruleset – Call the AWS Glue Data Catalog to fetch the managed ruleset for this table. The ruleset is owned by your governance team and versioned in the catalog.
Write to a branch – Before writing the ETL output, create an Apache Iceberg branch on the target table. Write all transformed records to this branch rather than to main.
Evaluate – Run EvaluateDataQuality against the branch data using the retrieved ruleset.
Merge or discard – If the quality score meets your threshold, merge the branch into main. If not, discard the branch and trigger your alerting workflow.
Creating a managed ruleset: To create a ruleset in the AWS Glue Data Catalog that targets the same database and table, you can create one using the AWS Command Line Interface (AWS CLI). For example:
The --target-table values must match the ICEBERG_DATABASE and ICEBERG_TABLE environment variables used in the Pattern 2 job. The job discovers the ruleset at runtime using list_data_quality_rulesets filtered by that target table.
To validate data quality inline using PySpark
To implement this pattern, see the following code sample which can be run on all three Amazon EMR deployment modes:
import os
import boto3
from pyspark.sql import SparkSession
from awsdataquality.transforms import EvaluateDataQuality
spark = (SparkSession.builder.appName("blog-wap-dq")
.config("spark.sql.catalog.iceberg", "org.apache.iceberg.spark.SparkCatalog")
.config("spark.sql.catalog.iceberg.warehouse", "s3://amzn-s3-demo-bucket/warehouse/")
.config("spark.sql.catalog.iceberg.catalog-impl", "org.apache.iceberg.aws.glue.GlueCatalog")
.enableHiveSupport().getOrCreate())
database = os.environ["ICEBERG_DATABASE"]
table = os.environ["ICEBERG_TABLE"]
input_path = os.environ["WAP_INPUT_PATH"]
threshold = float(os.environ.get("WAP_SCORE_THRESHOLD", "1.0"))
region = os.environ.get("AWS_REGION", "us-east-1")
ruleset_name = os.environ.get("GLUE_DQ_RULESET_NAME")
# Branch name carries the Spark application id so concurrent nightly runs, and reruns
# of a failed one, never collide on the same branch.
branch = os.environ.get("WAP_BRANCH") or f"audit_{spark.sparkContext.applicationId}"
branch = branch.replace("-", "_")
fqtn = f"iceberg.`{database}`.`{table}`"
branch_fqtn = f"iceberg.`{database}`.`{table}`.branch_{branch}"
glue = boto3.client("glue", region_name=region)
# ---------------------------------------------------------- 1. DQ RULESET
# We will then get the data quality rules.
ruleset = glue.get_data_quality_ruleset(Name=ruleset_name)["Ruleset"]
print(f"auditing against catalog ruleset '{ruleset_name}':\n{ruleset}")
# ---------------------------------------------------------- 2. WRITE
main_before = spark.table(fqtn).count()
print(f"main has {main_before} row(s) before this batch")
# CREATE BRANCH (not CREATE OR REPLACE): if the branch somehow already exists, that is
# a concurrent or half-finished run and silently replacing it would discard its state.
spark.sql(f"ALTER TABLE {fqtn} CREATE BRANCH {branch}")
print(f"created branch {branch}")
# Write out our batch to our new branch
batch = spark.read.parquet(input_path)
batch.writeTo(branch_fqtn).append()
print(f"wrote {batch.count()} row(s) to branch {branch}")
# Reread the branch and create a data frame to perform our data quality checks.
branch_df = spark.read.option("branch", branch).table(f"iceberg.`{database}`.`{table}`")
# ---------------------------------------------------------- 3. AUDIT
# Will now evaluate the ruleset against the branch
publishing_opts = {
"dataQualityEvaluationContext": ruleset_name,
"publishToDataCatalogTarget": {
"DatabaseName": database,
"TableName": table
},
"enableDataQualityResultsPublishing": "true"
}
# See the AWS Glue Data Quality additional_options reference for advanced configuration:
# https://docs.aws.amazon.com/glue/latest/dg/data-quality-additional-options.html
additional_opts = {}
additional_sources = {}
# Run EvaluateDataQuality.
dq_results = EvaluateDataQuality.apply(branch_df, ruleset, publishing_opts,
additional_opts, additional_sources)
# ---------------------------------------------------------- 4. PUBLISH or discard
# Iterate through the DQ results for any failed rules and if there are any failed
# rules, throw an exception to stop the job.
failures = []
for row in dq_results.collect():
if row["Outcome"] == "Failed":
failures.append(f"Rule: {row['Rule']} | Reason: {row['FailureReason']}")
# If there are any failures of any rule, we will drop the branch, and throw an error
if failures:
# Drop first, then raise: an exception alone would leave the rejected branch (and
# its data files) behind on the table for every failed night.
spark.sql(f"ALTER TABLE {fqtn} DROP BRANCH {branch}")
main_after = spark.table(fqtn).count()
print(f"REJECTED: branch {branch} dropped; main unchanged at {main_after} row(s)")
failure_summary = "\n".join(r for r in failures)
raise RuntimeError(f"Data quality checks failed:\n{failure_summary}")
# fast_forward moves main's pointer to the branch's snapshot. It requires main to
# be an ancestor of the branch, which holds here because the branch was cut from
# main and only appended to --- no rewrite of the promoted data, no second copy.
spark.sql(f"CALL iceberg.system.fast_forward("
f"table => '{database}.{table}', branch => 'main', to => '{branch}')")
spark.sql(f"ALTER TABLE {fqtn} DROP BRANCH {branch}")
main_after = spark.table(fqtn).count()
print(f"PUBLISHED: main fast-forwarded to {branch} "
f"({main_before} -> {main_after} row(s)); branch dropped")
spark.stop()
This code demonstrates a sample WAP approach using Apache Iceberg. We start by retrieving the ruleset from the AWS Glue service that will run against the table. We then create a branch within the Apache Iceberg table and apply new data against it. We then run our data quality checks using EvaluateDataQuality with the ruleset that we earlier obtained. If any of the data quality rules fail, a branch that holds the new version of the table gets dropped. Otherwise, it will be committed as the new main branch and made available for all consumers.
In this example, you will notice that the publishing_opts (publishing options) look different. For the dataQualityEvaluationContext, we set the ruleset name. We also fill in the publishToDataCatalogTarget with the database and table name within the AWS Glue Data Catalog. This tags the data quality run and its results to that table for easier lookups if you want to view the history of data quality runs on the table.
Clean up
To avoid ongoing charges, remove the resources that you no longer need:
Shut down Amazon EMR on EC2 clusters, Amazon EMR Serverless applications, or Amazon EMR on EKS.
Delete the tables that you created. The table mentioned in this blog post is company_sales.sales_data.
Delete the data quality ruleset created in Pattern 2.
Delete any Amazon S3 data that was generated for the purposes of this blog post.
Conclusion
Data quality is a concern for most production data pipelines. Until now, teams running on Amazon EMR had to build that quality layer themselves or bring in AWS Glue as a separate processing engine to get managed quality capabilities.
With AWS Glue Data Quality now bundled in AWS runtime for Apache Spark (emr-spark-8.1.0) and later versions, that gap is closed. You write your DQDL rules once and store them in the AWS Glue Data Catalog. From there, run them across each of the three Amazon EMR deployment modes.
The patterns in this post represent two points on that spectrum: a lightweight inline check for ad hoc workloads, and a full WAP workflow for production pipelines that need atomic, auditable data promotion.
Many data integration jobs are SQL-centric: they filter, join, and aggregate data on a schedule, and they run frequently enough that fast startup matters. For this shape of work, teams want to match the engine to the job and run it quickly and cost-effectively, without standing up and tuning separate infrastructure.
AWS Glue is the serverless data integration service that customers use to run extract, transform, and load (ETL) jobs at any scale, without managing infrastructure. With AWS Glue, you can run DuckDB, an embedded, in-process, vectorized SQL engine, inside a standard AWS Glue job. DuckDB reads Parquet files from Amazon Simple Storage Service (Amazon S3) and writes Apache Iceberg tables directly to Amazon S3 Tables, a capability of Amazon S3. DuckDB is an open source, in-process, vectorized analytical SQL engine that runs embedded in your application, with no separate server or cluster to manage. It reads and writes cloud data formats such as Parquet and Apache Iceberg natively. AWS Glue 6.0 is the latest version, running on a modernized runtime with a 30 percent price reduction over previous versions. DuckDB reads Amazon S3 Parquet through its httpfs extension and commits Iceberg snapshots to Amazon S3 Tables through the Iceberg REST endpoint, so no separate catalog synchronization is required. Running DuckDB in AWS Glue is well suited to SQL-centric transformations such as filters, joins, and aggregations. It also fits frequent, scheduled jobs such as hourly or daily aggregations, incremental loads, and rollups that benefit from fast startup. This pattern complements Apache Spark on AWS Glue rather than replacing it: when a workload needs distributed processing, the same job type runs PySpark with no change to your infrastructure, IAM, or triggers.
This post walks through the pattern with a concrete ETL use case and provides complete, runnable code. It also compares measured cost and runtime against a Spark job performing the same work on the same AWS Glue 6.0 runtime.
When to use this pattern
This pattern is a complement to Spark on AWS Glue, not a replacement. The following table summarizes when each approach yields the best results.
Signal
DuckDB on AWS Glue 6.0
Apache Spark on AWS Glue 6.0
Dataset size per run
Scales with worker size
Scales horizontally across multiple nodes for datasets of any size
Parallelism requirement
Single-node, in-process execution
Distributed processing across a managed cluster
SQL complexity
Aggregations, joins, window functions
Complex graph operations, custom UDFs, ML pipelines
Cost priority
Minimize per-run cost and duration
Maximize throughput at scale
Iceberg writes
DuckDB iceberg extension to S3 Tables
Native Spark Iceberg integration
For workloads that need distributed processing, the same glueetl job type runs PySpark with no change to your infrastructure, AWS Identity and Access Management (IAM) configuration, or triggers. You choose the engine that fits each workload.
How DuckDB runs on AWS Glue 6.0
Running DuckDB in an AWS Glue job comes down to two things working together: a runtime modern enough to load DuckDB and its native extensions, and the capabilities DuckDB brings to ETL once it does.
What the AWS Glue 6.0 runtime provides
Modern runtime compatibility. AWS Glue 6.0 runs on Amazon Linux 2023 with glibc 2.34 and Python 3.13. DuckDB 1.5.x and its native C++ extension binaries (httpfs, aws, iceberg) install through pip and load without workarounds. The DuckDB extension binaries require a modern glibc (2.28 or later), which the AWS Glue 6.0 runtime provides.
AWS Glue 6.0 resolves this compatibility requirement. You can add DuckDB 1.5.x to an AWS Glue 6.0 job in two ways. The first is the --additional-python-modules job parameter (duckdb==1.5.1), which pip-installs the package at job startup and loads all extensions without additional steps. Alternatively, you can package the dependencies as a Python virtual environment, upload it to Amazon S3, and reference it using the --python-virtual-env parameter. On AWS Glue 6.0, you can also add --python-virtual-env-storage-prefix to have AWS Glue build and cache the virtual environment automatically. For more information, see Using Python virtual environments with AWS Glue.
What DuckDB provides
DuckDB is an open source, in-process analytical SQL engine. It runs inside an AWS Glue job as a single process, with no separate cluster or coordinator. The following capabilities make it a practical fit for ETL on the AWS Glue 6.0 runtime.
Single-node vectorized execution. DuckDB runs inside a single AWS Glue job. For a couple of gigabytes, there is no shuffle, no executor scheduling, and no inter-node network I/O. The work happens in a single vectorized pass over columnar memory.
Native Amazon S3 and Parquet access. The httpfs extension reads and writes Amazon S3 objects directly, using the IAM role of the AWS Glue job automatically through CREDENTIAL_CHAIN.
Native Amazon S3 Tables writes. The iceberg extension connects to the Amazon S3 Tables Iceberg REST endpoint (ENDPOINT_TYPE s3_tables) and commits standard Iceberg snapshots. With AWS Glue 6.0, you can use two capabilities that matured independently: Amazon S3 Tables and DuckDB Iceberg writes.
Larger-than-memory operators. Sort, join, and aggregate spill to /tmp, so datasets larger than available RAM still process without code changes.
Sizing guidance. DuckDB runs within a single AWS Glue worker, so its available memory and disk scale with the worker type. This walkthrough uses the minimum glueetl configuration of 2 workers (2 data processing units, or DPUs) with worker type G.1X: each G.1X worker provides 4 vCPUs and 16 GB of memory. DuckDB runs on the driver and processes data in memory, spilling to local disk when a dataset or intermediate result exceeds available RAM. For larger inputs, choose a bigger worker: G.2X provides 8 vCPUs and 32 GB of memory, and the G.4X and G.8X types scale higher. Size the worker to your input volume and the memory footprint of your aggregations and joins. For current specifications, see AWS Glue worker types.
Architecture
The following image shows the architecture described in this post.
Figure 1: Data flows from raw Parquet in Amazon S3 through an AWS Glue 6.0 job running DuckDB, which writes Apache Iceberg tables to Amazon S3 Tables for querying by Amazon Athena and Amazon QuickSight.
The pipeline consists of the following managed components:
Layer
Role
AWS Service
Source
Raw Parquet files, partitioned by date
Amazon S3
Compute
DuckDB SQL engine running on the AWS Glue 6.0 runtime
AWS Glue 6.0 (glueetl)
Destination
Iceberg analytical tables, queryable by any engine
Amazon S3 Tables
Governance
Permissions and access control for S3 Tables writes
AWS Lake Formation
Query
Analytics and business intelligence (BI) on the output tables
Amazon Athena, Amazon QuickSight
Raw Parquet files land in Amazon S3 on a schedule. An AWS Glue 6.0 job runs DuckDB. DuckDB reads the files, applies SQL transformations in memory, and writes the aggregated result as an Iceberg table to Amazon S3 Tables through the Iceberg REST catalog. Amazon Athena and Amazon QuickSight can query the output immediately. No separate catalog synchronization is required.
You can trigger the job several ways:
With a native AWS Glue trigger, which can be scheduled, on-demand, or conditional on another job or crawler completing.
This section walks through a daily ETL pipeline for an eCommerce application. The pipeline reads raw transaction files from Amazon S3, cleanses and aggregates them, and writes a query-ready summary to Amazon S3 Tables.
An AWS account with permissions for AWS Glue, Amazon S3, Amazon S3 Tables, AWS Identity and Access Management (IAM), and AWS Lake Formation.
An Amazon S3 bucket containing raw Parquet files (referred to as <amzn-s3-demo-source-bucket> in this post).
An Amazon S3 Tables table bucket (referred to as <amzn-s3-demo-table-bucket> in this post). See the Create the S3 Tables table bucket section.
An IAM role for the AWS Glue job with:
Amazon S3 read access on <amzn-s3-demo-source-bucket>.
Amazon S3 Tables read/write access.
AWS Glue job execution permissions.
AWS Lake Formation grants on the S3 Tables catalog and namespace (required for Iceberg write operations).
An AWS Glue 6.0 job (glueetl) with:
--additional-python-modules: duckdb==1.5.1.
Minimum worker configuration: 2 workers, type G.1X.
Note on DuckDB versions.DuckDB support for writing Apache Iceberg tables through a REST catalog, including Amazon S3 Tables, requires version 1.4.0 or later. This walkthrough uses duckdb==1.5.1. On the AWS Glue 6.0 runtime (Amazon Linux 2023), it installs and all native extensions load without additional configuration.
Create the S3 Tables table bucket
If you don’t already have an Amazon S3 Tables table bucket, create one using the AWS Command Line Interface (AWS CLI):
Turn on integration with AWS analytics services so the table is discoverable by Amazon Athena, Amazon Redshift, and Amazon EMR. Complete the integration by creating the s3tablescatalog catalog in the AWS Glue Data Catalog using the AWS CLI. For the steps, see Integrating Amazon S3 Tables with AWS analytics services.
After turning on integration, grant the AWS Glue job role Lake Formation permissions on the Amazon S3 Tables catalog and the analytics namespace:
# Allow the job to create the target table on first run (namespace-scoped)
aws lakeformation grant-permissions \
--principal DataLakePrincipalIdentifier=arn:aws:iam::<YOUR-ACCOUNT-ID>:role/<YOUR-AWS-GLUE-ROLE> \
--resource '{"Database":{"Name":"analytics","CatalogId":"<YOUR-ACCOUNT-ID>:s3tablescatalog/<amzn-s3-demo-table-bucket>"}}' \
--permissions '["CREATE_TABLE"]'
# Grant only the operations the job performs on the target table
aws lakeformation grant-permissions \
--principal DataLakePrincipalIdentifier=arn:aws:iam::<YOUR-ACCOUNT-ID>:role/<YOUR-AWS-GLUE-ROLE> \
--resource '{"Table":{"DatabaseName":"analytics","Name":"daily_order_summary","CatalogId":"<YOUR-ACCOUNT-ID>:s3tablescatalog/<amzn-s3-demo-table-bucket>"}}' \
--permissions '["SELECT","INSERT","DELETE"]'
Generate sample data
This walkthrough uses a synthetic eCommerce dataset. Run the following Python script locally or in AWS CloudShell to generate Parquet files that match the schema used in the transform. It produces roughly 8.4 million rows across 12 files (about 94 MB on disk as Parquet, roughly 1.2 GB uncompressed in memory).
import pandas as pd
import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
import os
np.random.seed(42)
N = 8_400_000 # ~8.4M rows
NUM_FILES = 12 # split across 12 files to mimic a partitioned landing zone
df = pd.DataFrame({
"order_date": pd.date_range("2026-08-01", periods=N, freq="s"),
"region": np.random.choice(["US", "EU", "APAC"], N),
"category": np.random.choice(["electronics", "books", "home", "clothing"], N),
"status": np.random.choice(
["completed", "processing", "cancelled"], N, p=[0.6, 0.3, 0.1]
),
"quantity": np.random.randint(1, 10, N),
"unit_price": np.round(np.random.uniform(5.0, 200.0, N), 2),
"customer_id": np.random.randint(1000, 9999, N),
})
os.makedirs("sample_orders", exist_ok=True)
for i, chunk in enumerate(np.array_split(df, NUM_FILES)):
path = f"sample_orders/orders_part_{i}.parquet"
pq.write_table(pa.Table.from_pandas(chunk), path)
print(f"Wrote {path} ({os.path.getsize(path):,} bytes)")
Note. The CLI commands and code examples in this walkthrough use angle-bracket placeholders such as <amzn-s3-demo-source-bucket> and <amzn-s3-demo-table-bucket>. Replace these with your own values before running.
Step 1: Configure DuckDB in the AWS Glue 6.0 job
The AWS Glue filesystem is read-only except for /tmp, so DuckDB uses /tmp as a writable home directory for its extension cache and spill files. The job loads DuckDB extensions: httpfs reads and writes Amazon S3 objects directly, aws handles AWS credential resolution, refresh, and AWS Region detection, and iceberg connects to the Amazon S3 Tables REST catalog. The CREDENTIAL_CHAIN provider (from the aws extension) tells DuckDB to use the standard AWS credential provider chain, which automatically picks up the IAM role attached to the AWS Glue job. No access keys or secrets appear in the code.
The home_directory setting must be applied before loading any extensions. Without it, DuckDB attempts to write to /.duckdb/ and fails with IOError: Permission denied.
Step 2: Read and transform with DuckDB SQL
DuckDB reads Amazon S3 Parquet files directly through the httpfs extension. No local download is required. The read_parquet() function accepts Amazon S3 glob patterns, reading multiple files as a single relation.
import sys
from awsglue.utils import getResolvedOptions
args = getResolvedOptions(sys.argv, ['s3_input_path'])
S3_INPUT = args['s3_input_path']
con.execute(f"""
CREATE OR REPLACE TEMP TABLE _batch AS
SELECT date_trunc('day', order_date) AS order_day,
region, category,
COUNT(*) AS total_orders,
SUM(quantity * unit_price) AS gross_revenue,
SUM(CASE WHEN status = 'completed'
THEN quantity * unit_price ELSE 0 END) AS net_revenue,
COUNT(DISTINCT customer_id) AS unique_customers,
ROUND(AVG(quantity * unit_price), 2) AS avg_order_value,
SUM(CASE WHEN quantity * unit_price > 500
THEN 1 ELSE 0 END) AS high_value_orders
FROM read_parquet('{S3_INPUT}')
WHERE status IN ('completed', 'processing')
GROUP BY ALL
ORDER BY order_day DESC, gross_revenue DESC
""")
GROUP BY ALL is a DuckDB SQL extension that groups by every non-aggregate column in the SELECT list. It’s a convenience feature rather than standard SQL, and support varies across query engines. If you adapt this query for another engine, check whether it supports GROUP BY ALL or list the grouping columns explicitly (GROUP BY order_day, region, category).
The WHERE clause retains both completed and processing orders. The gross_revenue column reflects all in-flight revenue, while net_revenue counts only completed orders. A partition containing only processing orders shows net_revenue = 0. This is by design: the two columns serve different reporting purposes.
Step 3: Write to Amazon S3 Tables
DuckDB attaches the S3 Tables bucket as an Iceberg REST catalog using the ENDPOINT_TYPE s3_tables option. DuckDB commits each write as a new Iceberg snapshot through the catalog.
The write uses an idempotent per-day reload pattern: create the table if it does not exist, delete any existing rows for the batch’s date range, then insert. This way, re-runs don’t produce duplicate rows.
Note: The DELETE and INSERT are not committed atomically. If the job fails between them, the affected partition is left empty. For mitigations, see Error handling for production.
import sys
from awsglue.utils import getResolvedOptions
args = getResolvedOptions(sys.argv, ['s3t_arn'])
S3T_ARN = args['s3t_arn']
con.execute(f"ATTACH '{S3T_ARN}' AS s3t (TYPE iceberg, ENDPOINT_TYPE s3_tables);")
con.execute("CREATE SCHEMA IF NOT EXISTS s3t.analytics;")
con.execute("""
CREATE TABLE IF NOT EXISTS s3t.analytics.daily_order_summary (
order_day DATE,
region VARCHAR,
category VARCHAR,
total_orders BIGINT,
gross_revenue DOUBLE,
net_revenue DOUBLE,
unique_customers BIGINT,
avg_order_value DOUBLE,
high_value_orders BIGINT
);
""")
con.execute("""
DELETE FROM s3t.analytics.daily_order_summary
WHERE order_day IN (SELECT DISTINCT order_day FROM _batch);
""")
con.execute("""
INSERT INTO s3t.analytics.daily_order_summary BY NAME
SELECT * FROM _batch;
""")
count = con.execute(
"SELECT COUNT(*) FROM s3t.analytics.daily_order_summary"
).fetchone()[0]
print(f"S3 Tables now holds {count} rows in analytics.daily_order_summary")
The resulting Iceberg table is immediately readable by Amazon Athena, Amazon Redshift, and Amazon EMR through the S3 Tables REST catalog. Amazon S3 Tables handles compaction, snapshot expiration, and orphan-file cleanup automatically.
Complete AWS Glue 6.0 job script
The following script combines all three steps with structured logging, error handling, and AWS Glue job parameter parsing. It can be used directly as the script for an AWS Glue 6.0 glueetl job.
import os, sys, logging, duckdb
from awsglue.utils import getResolvedOptions
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(levelname)s %(message)s')
logger = logging.getLogger(__name__)
TARGET = 's3t.analytics.daily_order_summary'
DDL = """
CREATE TABLE IF NOT EXISTS s3t.analytics.daily_order_summary (
order_day DATE, region VARCHAR, category VARCHAR,
total_orders BIGINT, gross_revenue DOUBLE, net_revenue DOUBLE,
unique_customers BIGINT, avg_order_value DOUBLE, high_value_orders BIGINT
);
"""
TRANSFORM = """
SELECT date_trunc('day', order_date) AS order_day,
region, category,
COUNT(*) AS total_orders,
SUM(quantity * unit_price) AS gross_revenue,
SUM(CASE WHEN status = 'completed' THEN quantity * unit_price ELSE 0 END) AS net_revenue,
COUNT(DISTINCT customer_id) AS unique_customers,
ROUND(AVG(quantity * unit_price), 2) AS avg_order_value,
SUM(CASE WHEN quantity * unit_price > 500 THEN 1 ELSE 0 END) AS high_value_orders
FROM read_parquet('{s3_input}')
WHERE status IN ('completed', 'processing')
GROUP BY ALL
ORDER BY order_day DESC, gross_revenue DESC
"""
def setup_duckdb():
os.makedirs('/tmp/.duckdb/extensions', exist_ok=True)
con = duckdb.connect(':memory:')
con.execute("SET home_directory='/tmp';")
con.execute("SET extension_directory='/tmp/.duckdb/extensions';")
con.execute("INSTALL httpfs; LOAD httpfs;")
con.execute("INSTALL aws; LOAD aws;")
con.execute("INSTALL iceberg; LOAD iceberg;")
con.execute("CREATE SECRET (TYPE s3, PROVIDER credential_chain);")
logger.info("DuckDB %s initialized with httpfs, aws, and iceberg extensions",
duckdb.__version__)
return con
def transform_orders(con, s3_path):
logger.info("Reading source data: %s", s3_path)
con.execute("CREATE OR REPLACE TEMP TABLE _batch AS " +
TRANSFORM.format(s3_input=s3_path))
return con.execute("SELECT COUNT(*) FROM _batch").fetchone()[0]
def write_to_s3_tables(con, s3t_arn):
con.execute(f"ATTACH '{s3t_arn}' AS s3t (TYPE iceberg, ENDPOINT_TYPE s3_tables);")
con.execute("CREATE SCHEMA IF NOT EXISTS s3t.analytics;")
con.execute(DDL)
con.execute(f"""
DELETE FROM {TARGET}
WHERE order_day IN (SELECT DISTINCT order_day FROM _batch);
""")
con.execute(f"INSERT INTO {TARGET} BY NAME SELECT * FROM _batch;")
count = con.execute(f"SELECT COUNT(*) FROM {TARGET}").fetchone()[0]
logger.info("Write complete. %s now holds %s rows.", TARGET, count)
return count
def main():
args = getResolvedOptions(sys.argv, ['s3_input_path', 's3t_arn'])
con = setup_duckdb()
n = transform_orders(con, args['s3_input_path'])
logger.info("Transformed %s summary rows", n)
total = write_to_s3_tables(con, args['s3t_arn'])
logger.info("ETL complete. Table holds %s total rows.", total)
if __name__ == '__main__':
main()
Note. Replace the angle-bracket placeholders (<amzn-s3-demo-source-bucket>, <amzn-s3-demo-table-bucket>, <YOUR-REGION>, <YOUR-ACCOUNT-ID>, <YOUR-AWS-GLUE-ROLE>) with your own values before running.
Lake Formation permissions. Amazon S3 Tables access is governed by AWS Lake Formation. Grant the AWS Glue job role only the permissions the job needs: SELECT, INSERT, and DELETE on the target table (daily_order_summary), plus CREATE_TABLE on the analytics namespace so the job can create the table on first run. For the exact permission names and resource scoping, see the Lake Formation permissions reference. The role also requires the lakeformation:GetDataAccess IAM action. Without these grants, the ATTACH and CREATE TABLE statements fail with an access-denied error.
Error handling for production
For production use, plan for three failure modes:
Catalog access. If ATTACH to Amazon S3 Tables returns an access-denied error, verify that the IAM role of the job has the scoped Amazon S3 Tables actions on the table bucket ARN and the required AWS Lake Formation grants. Writes need both.
Partial writes. The DELETE and INSERT are not committed atomically, so a failure between them can leave a partition empty. Set MaxRetries to 1 so the idempotent reload re-runs automatically, or write to a staging table and swap on success.
Timeouts. Set the job Timeout higher than the expected run time to stop hung runs.
Monitoring
DuckDB runs inside a standard AWS Glue job, so you monitor it with the same Amazon CloudWatch metrics as any AWS Glue job. Two are useful for right-sizing this workload:
glue.driver.jvm.heap.usage: driver memory pressure. A high or climbing value means the worker needs more memory or the query is spilling heavily to disk.
glue.driver.aggregate.bytesRead: bytes read from Amazon S3, useful for correlating input size with runtime and cost.
The internal execution metrics of DuckDB (query plan, operator timings, spill volume) aren’t exposed to Amazon CloudWatch. Structured logging from the job script is the primary way to observe DuckDB itself: the production script uses logger.info to record the rows transformed and rows written, and those lines appear in the CloudWatch Logs stream of the job. Add more logger.info statements around each stage if you need finer-grained timing.
Measured results
The measurements in this section were collected on AWS Glue 6.0 with DuckDB 1.5.1 writing to Amazon S3 Tables in the US East (N. Virginia) Region (us-east-1). Output tables were verified by querying them in Amazon Athena. Both jobs produced identical output: 1,176 summary rows.
The dataset consisted of 8.4 million rows across 12 Parquet files (approximately 94 MB compressed on disk, approximately 1.2 GB uncompressed). One job ran DuckDB on the AWS Glue 6.0 runtime. The other ran Apache Spark on AWS Glue 6.0 with the equivalent transform and a native Iceberg write.
Metric
DuckDB on AWS Glue 6.0
Spark on AWS Glue 6.0
Compute configuration
2 DPU (2x G.1X)
2 DPU (2x G.1X)
Job Duration
~56 seconds
~117 seconds
Billed duration
1 minute (minimum)
2 minutes
Cost per run
$0.0103
$0.0205
Output rows (Athena-verified)
1,176
1,176
On the same AWS Glue 6.0 runtime and the same 2 DPU configuration, DuckDB completed in approximately half the time at approximately half the cost of Spark for this workload.
Cost is calculated at $0.308 per DPU-hour (AWS Glue 6.0 rate). AWS Glue bills in 1-second increments with a 1-minute minimum per run. Verify against the current AWS Glue pricing page for your Region. Results scale with dataset size, query complexity, and Region.
At 20 runs per day, this job costs approximately $75 per year with DuckDB, compared to $150 per year with Spark. Beyond the cost savings, this pattern keeps SQL-centric work quick to iterate on: you express the transformation in SQL, and DuckDB runs it in-process on the AWS Glue worker.
Clean up
To avoid ongoing charges, delete the resources created during this walkthrough:
Delete the AWS Glue job (duckdb-order-summary).
Remove the sample data from your Amazon S3 bucket (s3://<amzn-s3-demo-source-bucket>/orders/).
Drop the Iceberg table in Amazon Athena: DROP TABLE analytics.daily_order_summary;
Delete the Amazon S3 Tables table bucket if it was created for this walkthrough.
Revoke the AWS Lake Formation grants and remove the IAM role if no longer needed.
Conclusion
In this post, we demonstrated how to run DuckDB inside an AWS Glue 6.0 job to read Amazon S3 Parquet, transform it with SQL, and write Apache Iceberg tables directly to Amazon S3 Tables. AWS Glue 6.0 modernized the runtime environment to Amazon Linux 2023, Python 3.13, and Apache Spark 4.1. With that modernization, you can run embedded SQL in the AWS Glue job and write Iceberg tables directly to Amazon S3 Tables. For ETL jobs where the data fits in memory on a single worker, this pattern completed the same work in approximately half the time and half the cost of Spark. The Measured results section describes these measurements. The job uses the same glueetl job type, IAM configuration, and triggering mechanisms as any Spark job on AWS Glue. When a workload outgrows single-worker processing, switching the script back to PySpark requires no infrastructure changes. The result is the ability to match the engine to each job: a scheduled SQL transformation and a large distributed workload can run on one platform, and you pick the engine per job without managing separate systems.
To get started, create an AWS Glue 6.0 job, add duckdb==1.5.1 through the --additional-python-modules parameter, and point it at your Amazon S3 source data and an Amazon S3 Tables bucket. The complete script in this post is a working starting point you can adapt to your own datasets and schedules. For more information, see the AWS Glue Developer Guide and the Amazon S3 Tables user guide. For a complementary pattern that uses DuckDB to read and query data in Amazon S3 Tables, see Streamlining access to tabular datasets stored in Amazon S3 Tables with DuckDB.
This post was co-written with Ankit Aggarwal and Raja Kalluri from United Airlines.
United Airlines processes billions of events daily across its data platform, which spans Amazon Redshift and Databricks with Unity Catalog. To bridge these platforms without duplicating data, the team turned to AWS Glue Data Catalog federation.
In this post, we walk through how to configure AWS Glue Data Catalog federation to connect with Databricks Unity Catalog, so you can run live SQL queries from Amazon Redshift without moving or duplicating data.
Why United Airlines needed catalog federation
United Airlines curates petabytes of data through a medallion architecture (bronze to silver to gold) on Amazon Simple Storage Service (Amazon S3). The airline user interaction data layer alone is several double-digit terabytes of near real-time streamed data. Teams use it to measure customer engagement patterns, feature adoption, and conversion behavior across web and mobile touchpoints. Analysts need to query this curated data through Amazon Redshift Serverless. As part of the existing data platform architecture these data tables are cataloged in Databricks Unity Catalog, not in the AWS Glue Data Catalog. As a result, Amazon Redshift has no native visibility into them. Without catalog federation, the only way to make this data queryable from Amazon Redshift would have been to duplicate it into Amazon Redshift Managed Storage (RMS) and build pipelines to keep it in sync.
AWS Glue Data Catalog federation removed this need. Amazon Redshift users now query the gold layer stored in Amazon S3 directly, with Iceberg metadata resolved from Unity Catalog at query time and no data movement. AWS Glue Data Catalog federation connects Amazon Redshift to external catalogs like Unity Catalog, so analysts query cross-platform data without building sync pipelines or duplicating storage.
Amazon Redshift Serverless is powered by the same Graviton-based query engine used in the new RG instance family, which delivers up to 2x faster data lake query performance compared to prior generations. This engine is purpose-built for reading Apache Iceberg tables directly from Amazon S3, making it well-suited for such federated query workloads.
United Airlines is taking a phased approach to adopting AWS Glue Data Catalog federation across its data platform. The initial focus is the most heavily used user interaction data tables, with 30 tables currently federated in production and 70 more in active rollout. Several hundred additional tables across different business domains are planned for production in the coming months.
Solution overview
AWS Glue Data Catalog federation bridges these platforms at the metadata layer. Here’s how the architecture works.
The architecture follows a four-layer federation chain:
Databricks Unity Catalog exposes tables through its Iceberg REST API endpoint. For Delta tables, you can turn on UniForm format to make them Iceberg compatible.
AWS Glue Data Catalog creates a federated catalog that connects to Databricks Unity Catalog, making metadata visible within AWS without data movement.
A resource link database in the default AWS Glue catalog acts as a bridge, pointing to the federated catalog database. This is required for Amazon Redshift compute.
Amazon Redshift Serverless references the resource link database through an external schema. When a query runs, Amazon Redshift traverses the link, calls AWS Glue Federation, and reads the Iceberg data through the Databricks Unity Catalog REST API. AWS Lake Formation governs permissions throughout this chain.
Key services or service features used in this solution:
Federation chain from Databricks Unity Catalog through AWS Glue and Lake Formation to Amazon Redshift Serverless
Figure 1: Federation chain from Databricks Unity Catalog to Amazon Redshift Serverless through AWS Glue and Lake Formation
The architecture follows a six-step flow:
A SQL analyst submits a query to Amazon Redshift Serverless.
Amazon Redshift resolves the external schema through the AWS Glue Data Catalog (resource link to federated catalog).
The AWS Glue federated catalog calls the Databricks Unity Catalog Iceberg REST API to retrieve current table metadata.
The namespace IAM role calls AWS Lake Formation GetDataAccess to obtain scoped, temporary S3 credentials.
Lake Formation evaluates fine-grained access policies and vends credentials for the authorized data files.
Amazon Redshift Serverless reads the Iceberg data files directly from S3 and returns results to the analyst.
Prerequisites
Before you begin, make sure the following are in place:
A Databricks workspace with Unity Catalog enabled and at least one catalog, schema, and table. Databricks uses UniForm to generate Iceberg metadata on Delta Lake tables on Amazon S3.
An AWS account with permissions to manage AWS Glue, AWS Lake Formation, Amazon Redshift Serverless, and IAM.
An Amazon Redshift Serverless workgroup and namespace already provisioned.
AWS Lake Formation set up with a data lake administrator.
AWS Command Line Interface (AWS CLI) configured with appropriate credentials.
Familiarity with Amazon Redshift Query Editor v2 or a SQL client.
The walkthrough is organized into six steps covering Lake Formation configuration, the resource link pattern, IAM role setup, and querying Databricks tables from Amazon Redshift.
Step 1: Configure AWS Lake Formation
1a. Add a data lake administrator
In Lake Formation, choose Administration, then choose Administrators and add your admin IAM user or role.
1b. Confirm the federated catalog is registered
Choose Data Catalog, then Catalogs and verify that databricks-federated-catalog is visible and registered.
Step 2: Create a resource link in the default AWS Glue catalog
This step is the key architectural detail in the walkthrough. Amazon Redshift resolves CREATE EXTERNAL SCHEMA only against the default AWS Glue Data Catalog. The federated catalog (databricks-federated-catalog) is a separate, non-default catalog object. To give Amazon Redshift a path to the federated data, you create a resource link database in the default catalog that points to the federated catalog’s database.
A resource link does not copy data or metadata. It’s a pointer that Lake Formation resolves at query time.
To create the resource link in the Lake Formation console:
Choose Data Catalog, Databases, Create database. Then select Resource link.
For Resource link name, enter databricks_federated_db_link.
For Target catalog, enter databricks-federated-catalog.
For Target database, enter the database name that was discovered by the AWS Glue crawler (for example, databricks_federated_db).
Step 3: Configure the Amazon Redshift Serverless namespace IAM role
When Amazon Redshift queries through the resource link, it uses the IAM role attached to the Amazon Redshift Serverless namespace to call the Lake Formation GetDataAccess API. Lake Formation permissions must be granted to this namespace role.
Choose one of these two approaches:
Option A – Update your existing namespace role by adding the following policy inline.
Option B – Create a new dedicated role (named RedshiftServerlessNamespaceRole) and attach it to the namespace alongside existing roles.
Note: The Resource: “*” in this policy is shown for simplicity. In production, scope resources to specific AWS Glue catalog ARNs, database ARNs, and table ARNs based on your use case.*
After creating or updating the role, associate it with your Amazon Redshift Serverless namespace:
In the Amazon Redshift Serverless console, choose Namespaces, select [your namespace], then choose Security and encryption, then Manage IAM roles.
If you use Option A, the existing role already has the new permissions, so no change is needed.
If you use Option B, add the new role alongside the existing roles.
Step 4: Grant Lake Formation permissions to the Amazon Redshift namespace role
4a. Grant DESCRIBE on the resource link database (default catalog)
In Lake Formation, choose Permissions,Data lake permissions, then Grant.
Principal: RedshiftServerlessNamespaceRole.
Resources: Named Data Catalog resources,Default catalog,databricks_federated_db_link (resouce link).
Database permissions: DESCRIBE.
4b. Grant SELECT and DESCRIBE on the target tables (Grant on Target)
Resource links permit only DESCRIBE and DROP permissions on the link itself. To allow Amazon Redshift to actually read data, you must separately grant SELECT on the target tables in the federated catalog. This is the Lake Formation Grant on Target pattern.
Principal: RedshiftServerlessNamespaceRole.
Resources: Named Data Catalog resources,databricks-federated-catalog,databricks_federated_db, then Tables.
Table permissions: SELECT, DESCRIBE.
Catalog permission: DESCRIBE.
Important: SELECT must be granted on the TARGET tables in the federated catalog, not on the resource link. Granting SELECT only on the resource link won’t work. This is a common configuration error.
Step 5: Create an external schema in Amazon Redshift
With the resource link in place and permissions granted, you can now create an external schema in Amazon Redshift that points to the resource link database. The external schema is the query interface. When a user runs SQL against it, Amazon Redshift traverses the link to the federated catalog and retrieves metadata and data from Databricks Unity Catalog.
The DATABASE parameter must reference the resource link database name in the default AWS Glue catalog (databricks_federated_db_link), not the federated catalog name directly. The CATALOG_ARN parameter isn’t required here because the resource link lives in the default catalog and Amazon Redshift resolves it automatically.
Connect to your Amazon Redshift cluster as a superuser (for example, using Amazon Redshift Query Editor v2) and run:
CREATE EXTERNAL SCHEMA databricks_schema
FROM DATA CATALOG
DATABASE 'databricks_federated_db_link'
IAM_ROLE '<iam-role-arn>'
REGION '<region>';
A key design principle in this architecture is the clear separation between data physically stored in Amazon Redshift and data accessed externally through federation. External schemas provide a transparent abstraction layer, so Amazon Redshift users can query data stored in S3 without ingestion. For consistency and clarity, United Airlines follows a standard naming convention for all federated schemas in Amazon Redshift: {domain}_iceberg. This convention makes it immediately clear that the data isn’t natively stored within Amazon Redshift but is accessed by using federation through AWS Glue and Lake Formation. This distinction is critical for analysts and engineers, because it improves discoverability, avoids ambiguity between storage layers, and reinforces architectural discipline when working across hybrid data environments.
The User Interactions domain exposes curated datasets representing customer interaction activity, engagement behavior, and channel usage patterns. Operational datasets follow the same pattern, providing governed access to supporting business events and reference information through a common federation framework.
You create a view layer over each external schema using WITH NO SCHEMA BINDING, so that analysts always resolve the freshest schema on each query execution. For example:
CREATE VIEW analytics.clickstream_events AS
SELECT * FROM {domain}_iceberg.interaction_events
WITH NO SCHEMA BINDING;
Step 6: Verify and query Databricks tables from Amazon Redshift
After creating the external schema, verify that the Databricks tables are visible and run a test query.
Verify table visibility
-- Confirm federated tables are visible in Redshift
SELECT * FROM SVV_EXTERNAL_TABLES
WHERE schemaname = 'databricks_schema';
Query a Databricks Unity Catalog table
-- Query a Databricks Unity Catalog table via the federated catalog
SELECT *
FROM databricks_schema.<table_name>
LIMIT 10;
When a query runs, Amazon Redshift calls Lake Formation GetDataAccess using the namespace IAM role to obtain temporary credentials. It then contacts the AWS Glue federated catalog, which in turn calls the Databricks Unity Catalog Iceberg REST API to retrieve metadata and read table data. The result is returned to the Amazon Redshift user transparently.
For SAML-authenticated users, connect using your IdP JDBC plugin:
The Amazon Redshift JDBC driver handles authentication automatically. It authenticates with your IdP, receives a SAML assertion, and calls sts:AssumeRoleWithSAML for temporary IAM credentials. It then calls redshift-serverless:GetCredentials to connect as the mapped database user.
Business impact
AWS Glue Data Catalog federation delivered measurable architectural and operational improvements for United Airlines:
Area
Before
After
Impact
Data access
Delta Lake and Amazon Redshift data were completely siloed, so Amazon Redshift users had no access to curated datasets on Databricks-managed S3 data
Amazon Redshift users get real-time access to Databricks-managed data through AWS Glue Data Catalog federation
~100 analysts gained access to user interaction data tables in the first phase without adding new pipelines.
Disaster recovery
Cross-Region DR relied on Amazon Redshift snapshots every 3 hours (recovery point objective, or RPO, of 3 hours or more)
Amazon S3 cross-Region replication on the Delta Lake provides a near-continuous RPO. A new Amazon Redshift Serverless workgroup in the DR Region can federate to the same S3 data
More resilient architecture. Reduces cost for Amazon Redshift snapshot and copy maintenance across Regions
Architecture simplification
Data processing happened in both Databricks and Amazon Redshift, requiring manual catalog synchronization between the two platforms which was operationally expensive and prone to drift
With the federated architecture, data processing is consolidated in Databricks, and Amazon Redshift acts solely as a query engine powering user queries and dashboards through catalog federation
Single processing platform, zero sync pipelines, single source of truth
Infrastructure cost
Running dedicated Amazon Redshift ETL cluster with RMS storage, snapshots, and compute for data processing
For this use case with federation, Amazon Redshift is not needed for ETL but only as a query engine. No RMS storage duplication, no snapshot replication required
~$30K/month in redundant ETL infrastructure cost reduced
Security considerations
At United Airlines, identity governance is unified through Azure Active Directory groups. On the AWS consumption side, users authenticate to Amazon Redshift Serverless through SAML federation. AD group membership determines database-level access to federated schemas. On the Databricks side, the same AD groups govern access to Unity Catalog schemas. This single-identity model provides consistent access control across both platforms without requiring separate user provisioning. Lake Formation handles credential vending for S3 data access during federated queries, while schema-level access decisions are managed through the AD group mappings on each platform.
The architecture also provides multiple layers of security controls built into the federation chain:
AWS Lake Formation governs fine-grained access control throughout the federation chain, so that principals can only access authorized databases, tables, and columns.
IAM roles follow least-privilege principles. The Amazon Redshift namespace role is scoped only to AWS Glue metadata operations and Lake Formation GetDataAccess.
SAML-based authentication integrates enterprise identity providers, so that users authenticate through existing SSO infrastructure before accessing federated data.
All Amazon Redshift connections enforce TLS encryption (ssl=true), protecting data in transit between clients and the Amazon Redshift endpoint.
Lake Formation permission vending issues short-lived, scoped credentials for each query execution rather than long-lived static credentials.
Delta Lake tables must have UniForm enabled to expose Iceberg-compatible metadata.
We recommend that source tables be well-partitioned and regularly compacted, because the federated query performance reflects how efficiently the data is organized at write time.
Clean up
To avoid ongoing charges for resources created in this walkthrough, remove them in the following order. This teardown doesn’t affect Databricks metadata or your underlying data stored in Amazon S3.
Drop the external schema in Amazon Redshift: DROP SCHEMA databricks_schema;.
Delete the resource link database in the default AWS Glue catalog (databricks_federated_db_link).
Revoke Lake Formation permissions granted to the Amazon Redshift namespace role on both the resource link database and the target tables in the federated catalog.
Delete the federated catalog in AWS Glue (databricks-federated-catalog).
Deregister the AWS Glue connection for the Databricks Unity Catalog if no longer needed.
Optionally, remove the IAM role (RedshiftServerlessNamespaceRole) if it was created solely for this walkthrough.
Conclusion
In this post, we showed how United Airlines uses AWS Glue Data Catalog federation to give Amazon Redshift Serverless analysts real-time access to double-digit terabytes of curated user interaction data on Amazon S3, without duplicating a single byte or building sync pipelines.
The architecture uses the Iceberg REST API, resource link databases, and Lake Formation credential vending to create a governed query path between Amazon Redshift and Unity Catalog. For United Airlines, this eliminated redundant ETL infrastructure costs, removed the need for catalog synchronization, and turned Amazon Redshift Serverless into a dedicated high-performance query engine for analysts and dashboards.
For questions or feedback, leave a comment on this post.
In this post, you learn how to reduce Apache Spark query execution time with Apache Iceberg materialized views without changing a single SQL query.
Organizations running analytical workloads on their data lakes often hit a common wall: queries that are slow and costly, yet difficult to rewrite by hand. Multi-table joins, heavy aggregations, and window functions over large fact tables all drive up execution times, but the SQL behind them often can’t be changed. It might come from business intelligence (BI) dashboards, packaged independent software vendor (ISV) applications, or legacy reports, where editing the source introduces regression risk that outweighs the performance gain.
Starting with Amazon EMR 7.12.0 and AWS Glue 5.1, you can accelerate these queries without rewriting them. Automatic query rewrite analyzes the logical plan of each incoming query and compares it against a metadata cache of available MVs. When the optimizer finds a materialized view (MV) that satisfies all or part of a query, it rewrites the plan to read from that MV instead of the base tables. Matches can be structural (aggregations and joins) or exact (more complex patterns like window functions). If no MV matches, the original query runs unchanged with no impact on correctness.
If you have previously tried to speed up slow analytical queries, you might have considered one of the following alternatives. Here is how automatic query rewrite compares:
Give a high-level overview of how automatic query rewrite works in Apache Spark.
Walk through a concrete example, showing how the same query can benefit from MVs at different levels of coverage.
Discuss the trade-offs so you can choose the right MV shape for your workload.
Prerequisites
To use automatic query rewrite with Iceberg materialized views, you need:
Amazon EMR release 7.12.0 or later, or AWS Glue 5.1 or later.
Source tables in Apache Iceberg or Parquet format, registered in the AWS Glue Data Catalog, in the same AWS Region and account as the materialized view. Parquet source tables are supported for automatic query rewrite starting with Amazon EMR 7.14.0 and AWS Glue 8.1.
An Amazon Simple Storage Service (Amazon S3) Tables (a capability of Amazon S3) bucket, or an S3 general purpose bucket, for the materialized view data.
Permissions for the definer role. You can use AWS Identity and Access Management (IAM) policies or AWS Lake Formation.
Automatic query rewrite turned on in your Spark session: --conf spark.sql.optimizer.answerQueriesWithMVs.enabled=true.
For Parquet source tables, set spark.sql.materializedView.v1SourceTables.enabled=true and spark.sql.materializedView.v1ETagVersioning.enabled=true.
Here is how MVs and automatic query rewrite work together:
You define a SQL query with aggregations, joins, or filters across your supported source tables.
AWS Glue Data Catalog stores the precomputed results as an Apache Iceberg table in your Amazon S3 bucket. You can store it in a general purpose S3 bucket or in Amazon S3 Tables. Any Apache Iceberg-compatible query engine can read the materialized view, including Amazon Athena, Amazon EMR, AWS Glue, Amazon Redshift, and Iceberg-compatible third-party query engines. Automatic query rewrite is available on the AWS optimized Spark runtime in Amazon Athena, Amazon EMR, and AWS Glue. Other engines can query the materialized view directly, but they don’t rewrite queries to use it automatically.
Automatic refresh keeps the MV current on a schedule that you define, for example SCHEDULE REFRESH EVERY 1 DAY. You set it at creation time or later with ALTER MATERIALIZED VIEW ... ADD SCHEDULE REFRESH. At that scheduled time, the refresh process checks the current Apache Iceberg snapshot ID or Parquet file ETags and refreshes the MV when it detects source-table changes.
Automatic query rewrite redirects matching queries to the MV at query optimization time. Automatic query rewrite in Apache Spark uses two matching strategies:
Structural rewrite (adapted from Amazon Redshift) handles an MV defined as a single SELECT-FROM-WHERE-GROUP-BY block over INNER joins. The optimizer can roll up an MV’s aggregates to a coarser grain and pull extra query predicates up onto the MV scan.
Exact-match rewrite handles MVs defined as other shapes, such as window functions and outer joins, by matching a canonicalized form of the MV body against subtrees of the query plan.
When the optimizer evaluates a query, it consults a metadata cache of MVs from the configured catalogs and chooses the best match. It also checks MV staleness during optimization. It skips stale MVs, so rewrite won’t return stale results. If no MV matches, the original query runs unchanged.
Note that automatic query rewrite is opt-in: set spark.sql.optimizer.answerQueriesWithMVs.enabled=true when creating the Apache Spark session.
Example: One query with three potential MVs
An MV doesn’t need to cover an entire query to help it. Automatic query rewrite in Apache Spark operates on subtrees: when an MV matches a portion of your query plan, the rewriter substitutes that subtree and lets the rest of the query run on the rewrite output unchanged. The same query can therefore be served by many possible MV designs, each making a different trade-off between per-query speedup, storage cost, and reuse across other queries.
To make this concrete, consider a typical analytics query: “Top 100 preferred US customers by total store spending.” It joins fact and dimension tables, applies two selective filters on the customer dimension, aggregates per customer, ranks the result with a window function, and keeps only the top 100:
SELECT c_customer_id, total_revenue, num_transactions, avg_purchase, revenue_rank
FROM (
SELECT cust.c_customer_id,
SUM(sales.ss_quantity * sales.ss_sales_price) AS total_revenue,
COUNT(*) AS num_transactions,
AVG(sales.ss_quantity * sales.ss_sales_price) AS avg_purchase,
RANK() OVER (ORDER BY SUM(sales.ss_quantity * sales.ss_sales_price) DESC) AS revenue_rank
FROM base_catalog.base_db.store_sales sales
INNER JOIN base_catalog.base_db.customer cust
ON sales.ss_customer_sk = cust.c_customer_sk
WHERE cust.c_birth_country = 'UNITED STATES'
AND cust.c_preferred_cust_flag = 'Y'
GROUP BY cust.c_customer_id
) ranked
WHERE revenue_rank <= 100
ORDER BY revenue_rank;
Query 1: The original query. Top 100 preferred US customers by total store spending, before any materialized view.
Three MV designs cover progressively more of this query, from a single-table pre-aggregate to the full query body itself:
Tier 1: Pre-aggregate store_sales only, no join, no filter. This tier is a single-table aggregate of store_sales at customer-surrogate-key grain. The query still must join the customer table, apply both filters, re-aggregate at c_customer_id grain, and run the window function.
CREATE MATERIALIZED VIEW mv_catalog.mv_db.customer_tier_1 AS
SELECT ss_customer_sk,
SUM(ss_quantity * ss_sales_price) AS sum_revenue,
COUNT(ss_quantity * ss_sales_price) AS count_revenue,
COUNT(*) AS num
FROM base_catalog.base_db.store_sales
GROUP BY ss_customer_sk;
Tier 1 MV: Single-table pre-aggregate of store_sales by customer surrogate key (no join, no filter).
The following plans compare the original query plan to the rewritten plan:
Window, filter, Sort
+- Aggregate by c_customer_id
: total_revenue = SUM(ss_quantity * ss_sales_price)
: num_transactions = COUNT(*)
: avg_purchase = AVG(ss_quantity * ss_sales_price)
+- Project
+- Join Inner ON ss_customer_sk = c_customer_sk
:- BatchScan store_sales <- reads the large store_sales table
+- Filter c_birth_country='UNITED STATES' AND c_preferred_cust_flag='Y'
+- BatchScan customer
Plan 1: Original plan. Scans the large store_sales table.
Window, filter, Sort
+- Aggregate by c_customer_id <- rolls up pre-aggregated sums
: total_revenue = SUM(sum_revenue) <- sum of sum_revenue
: num_transactions = SUM(num) <- sum of num
: avg_purchase = SUM(sum_revenue) / SUM(count_revenue) <- sum of sum_revenue / sum of count_revenue
+- Project
+- Join Inner ON ss_customer_sk = c_customer_sk
:- BatchScan customer_tier_1 <- reads pre-aggregated MV
+- Filter c_birth_country='UNITED STATES' AND c_preferred_cust_flag='Y'
+- BatchScan customer
Plan 2: Rewritten plan (Tier 1). Reads the pre-aggregated customer_tier_1 MV.
Tier 2: Pre-join store_sales x customer, pre-apply one filter (c_preferred_cust_flag = ‘Y’). The middle tier pre-joins both tables and bakes in the preferred-customer filter. The query still must apply the country filter as a residual on the MV scan and run the RANK() window.
CREATE MATERIALIZED VIEW mv_catalog.mv_db.customer_tier_2 AS
SELECT cust.c_customer_id, cust.c_birth_country,
SUM(sales.ss_quantity * sales.ss_sales_price) AS sum_revenue,
COUNT(sales.ss_quantity * sales.ss_sales_price) AS count_revenue,
COUNT(*) AS num
FROM base_catalog.base_db.store_sales sales
INNER JOIN base_catalog.base_db.customer cust
ON sales.ss_customer_sk = cust.c_customer_sk
WHERE cust.c_preferred_cust_flag = 'Y'
GROUP BY cust.c_customer_id, cust.c_birth_country;
Tier 2 MV: Pre-joins store_sales and customer, with the preferred-customer filter applied.
Rewritten query plan:
Window, filter, Sort
+- Aggregate by c_customer_id <- rolls up pre-aggregated sums
: total_revenue = SUM(sum_revenue) <- sum of sum_revenue
: num_transactions = SUM(num) <- sum of num
: avg_purchase = SUM(sum_revenue) / SUM(count_revenue) <- reads pre-aggregated MV
+- Filter c_birth_country='UNITED STATES' [residual filter on MV scan]
+- BatchScan customer_tier_2 <- reads pre-aggregated MV
Plan 3: Rewritten plan (Tier 2). Country filter applied as a residual on the MV scan.
Tier 3: Match the entire query, including the window function and top N filter. This is the most specific tier. The MV body is the target query verbatim (minus the top-level ORDER BY, which is meaningless for a stored set). The MV stores the top-ranked rows the query asks for (rank ≤ 100).
CREATE MATERIALIZED VIEW mv_catalog.mv_db.customer_tier_3 AS
SELECT c_customer_id, total_revenue, num_transactions, avg_purchase, revenue_rank
FROM (
SELECT cust.c_customer_id,
SUM(sales.ss_quantity * sales.ss_sales_price) AS total_revenue,
COUNT(*) AS num_transactions,
AVG(sales.ss_quantity * sales.ss_sales_price) AS avg_purchase,
RANK() OVER (ORDER BY SUM(sales.ss_quantity * sales.ss_sales_price) DESC) AS revenue_rank
FROM base_catalog.base_db.store_sales sales
INNER JOIN base_catalog.base_db.customer cust
ON sales.ss_customer_sk = cust.c_customer_sk
WHERE cust.c_birth_country = 'UNITED STATES'
AND cust.c_preferred_cust_flag = 'Y'
GROUP BY cust.c_customer_id
) ranked
WHERE revenue_rank <= 100;
Tier 3 MV: Stores the exact ranked output of the query (exact-match path).
This tier exercises the exact-match rewrite path: the rewriter canonicalizes the MV body and matches it against the query’s logical plan.
Plan 4: Rewritten plan (Tier 3). Reads around 100 stored rows.
The trade-off
The three tiers trade per-query speedup against reuse and storage. In our testing on TPC-DS 3 TB, we observed the following:
MV design
Pre-computed
Reuse
Per-query speedup
MV size
Baseline (no MV)
nothing
n/a
1x
n/a
Tier 1: store_sales agg by customer surrogate key
aggregate of all sales per customer
broadest: any per-customer aggregation
~5x faster
0.07% of store_sales for TPC-DS 3 TB
Tier 2: store_sales x customer agg, one filter pre-applied
join + aggregate, preferred customers only
medium: any country filter, preferred customers
~10x faster
0.04% of store_sales for TPC-DS 3 TB
Tier 3: entire query body verbatim (exact-match)
exact ranked output of this query
narrowest: only this exact query shape
20x+ faster
negligible (only 100 rows)
Performance measured on TPC-DS 3 TB. Speedup is the ratio of baseline execution time to MV-accelerated execution time. Results might vary based on data characteristics, cluster size, and query complexity.
In addition, MVs incur additional cost. Each one runs a query against your source tables once and stores the result. The more pre-computation it does (joining more tables, applying more filters), the more time it takes.
The following chart plots per-query speedup and creation time for the three tiers in our testing on TPC-DS 3 TB. Per-query speedup rises steadily, from about 5x at Tier 1 to over 20x at Tier 3. Creation time doesn’t follow the same pattern: it peaks at Tier 2. Tier 2 pre-joins and aggregates all preferred customers across every country, so it materializes the most data work. Tier 3 applies both filters, so it processes far fewer rows and costs less to create.
Figure 1: Per-query speedup and creation time across the three materialized view tiers, measured on TPC-DS 3 TB
Start by identifying one expensive query that runs repeatedly with stable filters. It is likely a good candidate for an exact-match MV.
Validating automatic query rewrite
To confirm that your query benefited from automatic rewrite:
Query plan inspection: Check the query’s optimized logical plan or physical plan for a leaf scan node referencing the MV (for example, BatchScan mv_catalog.mv_db.your_mv_name). If the MV appears as a scan source, rewrite succeeded.
Log confirmation (Amazon EMR 7.14.0+): Look for INFO-level log entries such as AQMV outcome: rewritten=true, mvs=[mv_name], duration=12ms.
No-rewrite diagnostics (Amazon EMR 7.14.0+): If rewrite didn’t occur, check the MVRewriteMetricsEvent in the Apache Spark Event Log for the specific reason the optimizer skipped the MV.
If you have set spark.sql.optimizer.answerQueriesWithMVs.enabled=true but your query still runs against the base tables, check the following common causes:
Write commands block rewrite by default. INSERT and MERGE statements don’t trigger rewrite. Set spark.sql.optimizer.answerQueriesWithMVs.commandBlockingEnabled=false to turn on rewrite within write command subqueries.
The MV is stale. Rewrite skips the MV when one or more source tables have changed since its last refresh. Wait for the next scheduled refresh, or force an immediate refresh with REFRESH MATERIALIZED VIEW <mv_name>.
Heuristic candidate filtering. The optimizer uses heuristic checks to narrow the set of MV candidates before attempting a full match. In some cases, an MV that could benefit the query might be filtered out early by these heuristics.
Spark version mismatch (Amazon EMR 7.13.0+). Automatic query rewrite skips MVs whose stored IMV_sparkVersion does not match the cluster’s current Apache Spark version. To bypass this check, set spark.sql.materializedView.sparkVersionCompatibilityCheck.enabled=false.
MV metadata cache not loaded. The metadata cache loads lazily during optimization of the first rewritable query in a Spark session. If your critical query fires before the cache is warm, the MV will not be available. Run a small warm-up query (for example, SELECT 1 FROM <some_iceberg_table>) at session start to pay this cost off the critical path.
MV metadata cache memory limit reached. If the cache was disabled or stopped loading MVs because of reaching its memory limit, increase spark.driver.memory.
Too many tables in configured catalogs. If there are many tables or MVs in the configured catalogs, the cache might not finish loading before your query starts. Place MVs in a dedicated catalog, add it to spark.sql.materializedViews.additionalCatalogs, and set spark.sql.materializedViews.scanCurrentCatalog=false to skip scanning the current catalog.
Parquet base tables have additional limitations and configuration requirements. For automatic query rewrite with Parquet base tables, set spark.sql.materializedView.v1SourceTables.enabled=true and spark.sql.materializedView.v1ETagVersioning.enabled=true. Without ETag versioning, Spark can’t determine a usable source-table version and skips the MV. Partitioned Parquet base tables are also subject to additional validation limits.
Performance considerations
Turning on automatic query rewrite has overhead: it introduces trade-offs that might affect some queries negatively:
Optimization overhead. Enabling rewrite adds processing time during query optimization as the optimizer evaluates MV candidates against the query plan. This overhead applies to every query in the session, including those that ultimately don’t match any MV.
Reduced task parallelism. Reading from an MV instead of the original base table might produce fewer tasks or introduce data skew, depending on the MV’s data layout. This reduces parallelism compared to a direct scan of the larger, more evenly distributed source table.
Conclusion
In this post, we showed how automatic query rewrite can accelerate your existing Apache Spark workloads. It uses Apache Iceberg materialized views in the AWS Glue Data Catalog, without changing a single line of SQL. By storing precomputed results as managed Apache Iceberg tables, the AWS Glue Data Catalog lets the Apache Spark optimizer transparently substitute matching query plans. You get the performance benefit of pre-aggregation without the application-level rewiring. BI dashboards, ISV-generated reports, and legacy pipelines all benefit the moment a matching MV exists.
We walked through three MV designs for the same analytical query, each striking a different balance between per-query speedup, storage footprint, and reuse across your workload. As the trade-off table shows, our testing found that a narrow, exact-match MV delivered 20x+ acceleration for a single query shape. A broader pre-aggregate served an entire family of queries at a more modest ~5x gain. The right choice depends on how many queries share the same join-and-aggregate pattern and how frequently your source data changes.
To get started:
Launch an Amazon EMR 7.12.0+ cluster or an AWS Glue 5.1+ job.
Create an MV over your most expensive repeating query using CREATE MATERIALIZED VIEW in the AWS Glue Data Catalog.
Turn on automatic query rewrite by setting spark.sql.optimizer.answerQueriesWithMVs.enabled=true in your Spark session configuration.
Verify the rewrite by inspecting the optimized query plan for an MV scan node, or by checking INFO-level logs on Amazon EMR 7.14.0+.
Queries with multi-table joins, heavy aggregations, or window functions over large fact tables are strong initial candidates. Start with one high-cost, frequently executed query. Validate the speedup, then expand to broader MVs as you identify shared patterns across your workload.
Special thanks to everyone who contributed to the automatic query rewrite feature and this blog: Andre Hernich, Leon Lin, Yiyang Chen, Geeta Krishna Panda, Ashok Chintalapati, Muhammad Malik, Rishabh Bhatia, and Giovanni Fumarola.
Data teams commonly build the extract, transform, and load (ETL) pipelines that turn raw order events into analyst-ready aggregates as a bronze, silver, and gold sequence, the medallion architecture. Bronze holds raw ingested records, silver holds cleaned and validated data, and gold holds the business-level aggregates that analysts query. Today you build this on AWS Glue with an orchestrator such as Amazon Managed Workflows for Apache Airflow (Amazon MWAA) or AWS Step Functions coordinating the stages. Many teams run production pipelines exactly this way. As a pipeline grows, the coordination work grows with it: you wire job dependencies, manage intermediate checkpoints, and add retry logic stage by stage.
AWS Glue 6.0, powered by Apache Spark 4.1, introduces Spark Declarative Pipelines (SDP), which simplifies this further. Instead of orchestrating jobs by hand, you declare what each dataset should contain and let the declarative framework resolve dependencies, manage checkpoints, and orchestrate execution order automatically. The result runs as a single declarative job, with no manual directed acyclic graph (DAG) wiring or imperative orchestration code.
In this post, you build a single AWS Glue 6.0 job that turns raw order records into validated, aggregated, analytics-ready tables through the bronze, silver, and gold sequence. You do this without writing any orchestration logic. This walkthrough uses the AWS Command Line Interface (AWS CLI), and the same operations are available through the AWS SDKs.
Solution overview
You build a single AWS Glue 6.0 job that reads raw order records from a CSV file in Amazon Simple Storage Service (Amazon S3). The job flows them through three declared datasets. These are a bronze materialized view (ingest as-is), a silver materialized view (type, validate, and classify), and a gold SQL materialized view (aggregate by region). With AWS Glue Data Catalog integration turned on, all three land as Data Catalog tables, queryable with standard SQL tooling such as Amazon Athena. SDP resolves the dependency order from the dataset references in your code, so you never orchestrate the steps yourself.
Two ways to build the pipeline
Before you build the pipeline, let’s understand this new way of writing ETL pipelines with a quick comparison of the imperative and declarative approaches.
With the imperative approach, you need three AWS Glue jobs, plus an orchestrator to handle sequencing and error handling. A typical pipeline therefore has two layers: an orchestration layer and the ETL processing layer. The following diagram shows this two-layer imperative pipeline.
Figure 1: The two-layer imperative pipeline, with three AWS Glue jobs coordinated by an orchestrator.
Compared to that, the declarative approach runs as a single ETL job with SDP. The following diagram mirrors the previous one, but here it is a single AWS Glue ETL job instead of three jobs plus an orchestrator.
Figure 2: The declarative pipeline, a single AWS Glue job running the bronze, silver, and gold layers with SDP.
The declarative approach reduces more than the number of jobs. It removes the boilerplate that surrounds them. An orchestrator such as Amazon MWAA or AWS Step Functions already handles retries and parallelism, but only at the granularity of a whole job. To get finer control, teams often split a pipeline into several jobs and then hand-wire the dependencies between them. With SDP, you no longer hand-wire a DAG, manage per-stage checkpoints, or split the pipeline into separate jobs for retries and parallelism. SDP derives the dependency graph from your table references and coordinates execution at the level of individual tables. You can still invoke an SDP job from an orchestrator when a broader workflow calls for it, but the pipeline’s internal coordination is no longer code you write and maintain.
SDP separates the what from the how: you declare datasets (the outputs you want), and SDP builds the flows that produce them and runs them as one pipeline, resolving dependencies and execution order automatically.
You declare these abstractions through Python decorators. This post covers three of them, @dp.table, @dp.materialized_view, and @dp.temporary_view, each with its own purpose:
@dp.table defines a streaming table, which processes new data incrementally on each run. Typical use cases are raw event ingestion and change data capture (CDC) feeds.
@dp.materialized_view defines a materialized view for batch use cases. Today, this dataset type fully recomputes on each run. Common uses include parsing, aggregations, and machine learning (ML) feature engineering.
@dp.temporary_view is for temporary computations and aggregations. It’s pipeline-scoped and isn’t persisted outside the pipeline. Use it for enrichment lookups and subqueries.
Streaming tables append only new arrivals. Materialized views fully recompute. This post uses @dp.materialized_view for all three layers to keep the walkthrough focused. In production, you would typically use @dp.table for the bronze layer to process only new files as they arrive rather than re-reading the full source each run.
Running and refreshing the pipeline
When you rerun a pipeline, you don’t always want the same work to happen. Sometimes you only want to confirm the pipeline is well-formed before spending compute. Other times you want to run it but recompute only the datasets that changed rather than the entire graph. SDP handles both cases through two independent controls, and it helps to keep them separate:
Execution mode (the spark.glue.sdp.jobMode key) answers run or only validate?
Refresh scope (the spark.glue.sdp.runMode key) answers given that I’m running, what do I recompute?
Execution mode.VALIDATE runs the pipeline in dry-run mode: SDP checks the YAML syntax, dependency resolution, and SQL and Python compilation without writing any data. Use it to verify your pipeline is well-formed before committing compute. RUN (the default) executes the pipeline normally, resolving the dependency graph and materializing datasets.
Refresh scope. By default, a RUN recomputes every materialized view. You can narrow or widen that with spark.glue.sdp.runMode:
--refresh <datasets> updates only the named datasets (comma-separated, no spaces).
--full-refresh <datasets> resets and recomputes only the named datasets (for streaming tables, this also clears their checkpoints).
--full-refresh-all resets and recomputes every dataset in the pipeline.
# Selective refresh of named datasets
aws glue start-job-run \
--job-name "${JOB_NAME}" \
--arguments '{"--conf":"spark.glue.sdp.jobMode=RUN --conf spark.glue.sdp.runMode=--refresh silver_orders,gold_sales_summary"}' \
--region "${AWS_REGION}"
# Full reset and recompute of the entire pipeline
aws glue start-job-run \
--job-name "${JOB_NAME}" \
--arguments '{"--conf":"spark.glue.sdp.jobMode=RUN --conf spark.glue.sdp.runMode=--full-refresh-all"}' \
--region "${AWS_REGION}"
Selective refresh is useful during development, so you can iterate on a single layer without reprocessing the entire graph. Note that --refresh and --full-refresh each take an explicit list of datasets. To reset the whole pipeline, use --full-refresh-all. Because materialized views hold no incremental state, resetting a materialized view and refreshing it both fully recompute it. The reset-versus-refresh distinction matters for streaming tables, where a refresh processes only new data and a reset clears the checkpoint and reprocesses from scratch.
The multiple values are passed as a single --conf argument string ("spark.glue.sdp.jobMode=RUN --conf spark.glue.sdp.runMode=..."). This is the serialization the AWS Glue SDP mode expects for the run.
Materialized views: Batch transforms with automatic dependency resolution
Materialized views recompute their full result set on each run. SDP infers dependencies from table references: in this pipeline, silver_orders references bronze_orders, so SDP runs bronze first, as shown in the following diagram.
Figure 3: SDP infers the dependency order from table references and runs bronze before silver.
The core pattern is a decorated function that returns a DataFrame:
The silver layer references bronze_orders through spark.table("bronze_orders"), with no explicit dependency declaration. SDP builds the DAG by analyzing table references in your code and runs bronze first automatically.
Bronze reads every column as a string by design: the bronze layer preserves raw source data without coercion. Type casting, validation, and filtering happen in the silver layer.
SQL and Python coexistence
SDP supports both Python and SQL definitions in the same pipeline project. A SQL materialized view can reference a Python-defined table directly, for example the gold layer aggregating the silver table:
CREATE MATERIALIZED VIEW gold_sales_summary
COMMENT 'Completed-order metrics by region'
AS
SELECT
region,
COUNT(*) AS order_count,
CAST(ROUND(SUM(amount), 2) AS DECIMAL(10, 2)) AS total_sales,
CAST(ROUND(AVG(amount), 2) AS DECIMAL(10, 2)) AS average_order_value
FROM silver_orders
GROUP BY region;
In this post, Python files define ingestion and validation logic, and SQL files define reporting views and aggregations. SDP discovers both through the libraries glob pattern in the pipeline specification and resolves the cross-language dependencies automatically. The complete source for all three layers follows in the step-by-step walkthrough.
Build the pipeline: Step by step
The rest of this post is a hands-on walkthrough. You build a single AWS Glue 6.0 job that reads orders.csv and processes it through the bronze, silver, and gold layers. The steps are:
Prerequisites: AWS account, AWS Identity and Access Management (IAM) role, and S3 bucket.
Set up sample data: create orders.csv and upload it to Amazon S3.
Build the pipeline files (the spark-pipeline.yml specification plus the three transformation files).
Package the pipeline into a zip and upload it to Amazon S3.
Create the database: a Data Catalog database with an S3 location.
Configure the job: create the AWS Glue 6.0 job with the SDP flag.
Validate: run in dry-run mode to verify the graph.
Run the pipeline to materialize all datasets.
Query results: inspect the tables with Amazon Athena.
Clean up: delete the resources you created.
Step 1 – Prerequisites
To follow along, you need:
An AWS account with access to AWS Glue 6.0.
A dedicated IAM role trusted by glue.amazonaws.com (set up in the following section).
A private, encrypted Amazon S3 bucket with Block Public Access enabled.
The AWS CLI configured with credentials for a non-production account.
IAM role for the pipeline
Create a role that AWS Glue can assume, with the following trust policy:
Attach the AWS managed policy AWSGlueServiceRole, which grants the AWS Glue Data Catalog and Amazon CloudWatch Logs access the job needs. Then add an inline policy that scopes Amazon S3 access to your bucket, covering the input data, the pipeline zip, the pipeline storage (state) path, and the warehouse location:
Set the following variables, replacing the example values (us-east-1, amzn-s3-demo-bucket, the account ID 111122223333, and the role name) with your own:
Upload the file to the input/ location under your project prefix, which is where the bronze layer reads it (the ORDERS_PATH in 01_bronze.py, shown in Step 3). Use the variables you exported in Step 1:
The file includes one invalid order (O-1003, a negative amount), which the silver layer filters out to demonstrate the validation step. The AMER and EMEA regions each have two completed orders, so the gold layer’s order_count and average_order_value are meaningful aggregations rather than single-row passthroughs.
Step 3 – Build the pipeline files
The pipeline project uses the structure introduced earlier: a transformations/ folder holding the three layer definitions (01_bronze.py, 02_silver.py, 03_gold.sql), plus the spark-pipeline.yml specification. The following screenshot shows this layout in a code editor.
Figure 4: The pipeline project layout in a code editor.
The complete contents of each file follow.
3a. spark-pipeline.yml
The specification names the pipeline, points to the Data Catalog database, configures state storage, and discovers transformation files. As with the transformation files, it uses the __DATABASE__, __BUCKET__, and __PREFIX__ tokens, which you substitute at packaging time in Step 4:
Bronze preserves the raw source as strings. No coercion, no filtering:
"""Bronze layer: preserve source order records as strings."""
from pyspark import pipelines as dp
from pyspark.sql import DataFrame, SparkSession
from pyspark.sql.types import StringType, StructField, StructType
spark = SparkSession.active()
ORDERS_PATH = "s3://__BUCKET__/__PREFIX__/input/orders.csv"
ORDERS_SCHEMA = StructType([
StructField("order_id", StringType(), True),
StructField("customer_id", StringType(), True),
StructField("region", StringType(), True),
StructField("amount", StringType(), True),
StructField("status", StringType(), True),
StructField("order_ts", StringType(), True),
])
@dp.materialized_view(comment="Raw orders loaded from CSV")
def bronze_orders() -> DataFrame:
return (
spark.read
.schema(ORDERS_SCHEMA)
.option("header", "true")
.csv(ORDERS_PATH)
)
The path uses the tokens __BUCKET__ and __PREFIX__ rather than hardcoded values. AWS Glue reads these files from the packaged zip at runtime, so shell variables like ${BUCKET} are not expanded inside them. You substitute the tokens with your real values when you package the project in Step 4, which keeps every file consistent with the variables you exported in Step 1.
3c. transformations/02_silver.py
Silver casts types, filters to complete orders with positive amounts, and derives an amount_band classification:
Silver reads bronze with spark.table("bronze_orders"), so SDP infers the dependency and runs bronze first. Two details matter here:
The to_timestamp call passes an explicit format, "yyyy-MM-dd'T'HH:mm:ss'Z'". The source timestamps are ISO 8601 with a Z suffix. Giving the format treats Z as a literal and produces the same wall-clock value regardless of the job’s session time zone, which keeps the result deterministic.
The transformation runs in two projections: the first casts and filters, and the second derives amount_band from the already-typed amount column. Deriving columns with .select(...) rather than a separate .withColumn(...) step keeps SDP’s reference to bronze_orders resolvable as a pipeline dependency. This way, SDP consistently orders the bronze layer before the silver layer. The order matters here too. Spark 4.1 enables ANSI mode by default, so comparing the raw string amount against a number would fail. amount_band therefore reads the already-cast amount.
3d. transformations/03_gold.sql
The gold layer aggregates order metrics by region using SQL:
CREATE MATERIALIZED VIEW gold_sales_summary
COMMENT 'Completed-order metrics by region'
AS
SELECT
region,
COUNT(*) AS order_count,
CAST(ROUND(SUM(amount), 2) AS DECIMAL(10, 2)) AS total_sales,
CAST(ROUND(AVG(amount), 2) AS DECIMAL(10, 2)) AS average_order_value
FROM silver_orders
GROUP BY region;
Step 4 – Package the project
Substitute the __BUCKET__, __PREFIX__, and __DATABASE__ tokens with the values you exported in Step 1. Then package spark-pipeline.yml and the transformations/ folder into a zip with both at the zip root. Because AWS Glue reads these files from the zip at runtime, the substitution has to happen now, at packaging time, not through shell variables at run time:
# Render the tokens into a build/ copy, leaving your source files untouched
rm -rf build/package && mkdir -p build/package/transformations
sed -e "s|__BUCKET__|${BUCKET}|g" \
-e "s|__PREFIX__|${PREFIX}|g" \
-e "s|__DATABASE__|${DATABASE}|g" \
spark-pipeline.yml > build/package/spark-pipeline.yml
sed -e "s|__BUCKET__|${BUCKET}|g" \
-e "s|__PREFIX__|${PREFIX}|g" \
transformations/01_bronze.py > build/package/transformations/01_bronze.py
cp transformations/02_silver.py transformations/03_gold.sql build/package/transformations/
# Zip with the spec and transformations at the zip root
(cd build/package && zip -r -q ../simple-sdp-demo.zip spark-pipeline.yml transformations)
# Upload
aws s3 cp build/simple-sdp-demo.zip "s3://${BUCKET}/${PREFIX}/pipeline/simple-sdp-demo.zip" --region "${AWS_REGION}"
Only spark-pipeline.yml and 01_bronze.py carry tokens, so the other files are copied as-is. The uploaded object is named simple-sdp-demo.zip, which is the same name the job references in Step 6.
Step 5 – Create the database
The database named in spark-pipeline.yml must already exist in the AWS Glue Data Catalog, with an S3 location URI, before the pipeline runs. SDP does not create it automatically:
Uses the AWS Glue Data Catalog as the Spark Hive metastore, so the pipeline’s output tables register in the catalog
ScriptLocation
Points to the pipeline zip, not a .py file
Table 2: Key arguments for the create-job command.
The create-job command sets ScriptLocation to the pipeline zip. You can also point it to an Amazon S3 prefix: upload the unzipped spark-pipeline.yml and transformations/ to a prefix and set ScriptLocation to that prefix (with a trailing /). No other change is needed, and the --enable-spark-declarative-pipeline flag stays the same. The zip keeps the upload to a single object.
Step 7 – Validate (dry run)
Run the job in validation mode first to verify the dependency graph without materializing data:
Validation analyzes the project structure, dependency graph, and SQL and Python compilation without creating tables, executing transforms, or writing data. Confirm that the database has no tables after validation completes.
On AWS Glue, validation runs as a job (jobMode=VALIDATE), so you create the job in Step 6 and then validate it here. If you develop locally with the open source spark-pipelines CLI, you can run its dry-run against the project before packaging and uploading.
After the run, the AWS Glue console shows the three output tables in the simple_sdp_demo_db database. The database’s Location is the warehouse path you configured, s3://amzn-s3-demo-bucket/simple-sdp-demo/warehouse/, and each table stores its data under that prefix. The following screenshot shows the database properties and the three tables (bronze_orders, silver_orders, and gold_sales_summary), each registered in the AWS Glue Data Catalog.
Figure 5: The three output tables in the AWS Glue Data Catalog.
Step 9 – Query results
Query the tables with Amazon Athena. If this is your first time using Athena in this Region, set an Amazon S3 query-results location for your workgroup first (Athena console, Settings). Also make sure your identity can read the simple_sdp_demo_db tables in the Data Catalog and the underlying S3 data.
-- Bronze preserves all 6 source rows
SELECT * FROM simple_sdp_demo_db.bronze_orders ORDER BY order_id;
-- Silver retains the 5 complete orders with positive amounts
SELECT * FROM simple_sdp_demo_db.silver_orders ORDER BY order_id;
-- Gold aggregates by region
SELECT * FROM simple_sdp_demo_db.gold_sales_summary ORDER BY region;
Expected gold result:
region
order_count
total_sales
average_order_value
AMER
2
1000.00
500.00
APAC
1
320.25
320.25
EMEA
2
210.50
105.25
Table 3: Gold layer aggregation results by region.
Running the query in the Amazon Athena console returns the aggregated result. The following screenshot shows the gold query and its three result rows (AMER, APAC, and EMEA), matching the values in the preceding table.
Figure 6: The gold table results in the Amazon Athena console.
Cost considerations
AWS Glue 6.0 bills ETL jobs by the data processing unit (DPU)-hour, per second, with a 1-minute minimum per run. AWS Glue 6.0 is also priced 30 percent lower per DPU-hour than AWS Glue 5.1, with no change to your workload, so the same job costs less to run on 6.0. This walkthrough runs on 2 G.1X workers (2 DPUs), reads a 6-row CSV, and completes each run in about 2 minutes. It produces three tables in one AWS Glue Data Catalog database.
To estimate the cost of a run, multiply the 2 DPUs by the run time in hours by your Region’s AWS Glue 6.0 DPU-hour rate. You can find that rate on the AWS Glue pricing page, and rates differ by AWS Region. The Amazon S3 objects created are the 6-row CSV, the pipeline zip, and the three tables’ data. To stop further charges, delete the resources when you finish, as shown in the next step.
Step 10 – Clean up
To avoid ongoing charges, delete the resources you created:
# Delete the AWS Glue job
aws glue delete-job --job-name "${JOB_NAME}" --region "${AWS_REGION}"
# Delete the Data Catalog database and its table metadata
aws glue delete-database --name "${DATABASE}" --region "${AWS_REGION}"
# Remove the S3 objects
aws s3 rm "s3://${BUCKET}/${PREFIX}/" --recursive --region "${AWS_REGION}"
What’s next
You now have a single pipeline that turns raw order records into validated, aggregated analytics tables, without writing orchestration logic. From here you can:
Extend: Add transformation stages (additional @dp.materialized_view functions) and connect them by referencing upstream tables. The pipeline picks up the new dependency automatically.
Scale: This walkthrough uses materialized views throughout, so every layer fully recomputes on each run (materialized views don’t support incremental refresh). To process only new data as it arrives, convert the bronze layer to a streaming table, which maintains state across runs with checkpoints. For that cross-run state to persist, a streaming table’s data and checkpoint state must not be stored locally. Hive or AWS Glue managed tables require the database’s LocationUri to point to an Amazon S3 path, while Apache Iceberg tables manage their table metadata themselves.
Govern: Protect the Data Catalog tables SDP produces with AWS Lake Formation fine-grained access control. It enforces table-, row-, column-, and cell-level permissions on read queries in AWS Glue Spark jobs (Glue 5.0 and later, for Hive and Iceberg tables). Because this enforcement covers batch reads, it applies to SDP’s materialized views but not to streaming tables, which read through Spark Structured Streaming.
Automate: Store the pipeline project in source control. Have your continuous integration and continuous delivery (CI/CD) pipeline package and upload it to Amazon S3 so each job run maps to a known build. Version the zip by object key, or upload the unzipped project to an S3 prefix and turn on Amazon S3 bucket versioning.
Monitor: Use Amazon CloudWatch metrics and AWS Glue job run insights for pipeline observability, latency tracking, and failure alerting.
Conclusion
In this post, you used Spark Declarative Pipelines, the declarative alternative to explicitly orchestrated ETL, now available in AWS Glue 6.0. Two decorated Python functions and one SQL file define the bronze, silver, and gold datasets, and SDP resolves the dependencies and manages execution order for you.
With SDP, you declare what each dataset should contain and the declarative framework handles ordering and execution. A three-layer pipeline that would otherwise need separate transform and orchestration logic runs as one job that you can ship and maintain.
Real-time event pipelines rarely get to work with a uniform schema. Whether it’s IoT metrics, ecommerce clickstreams, or financial pricing vectors, each event type brings its own schema. An equity trade and a rates trade, for instance, carry almost entirely different fields. Ingesting these multi-schema streams has traditionally forced suboptimal architectural choices. You build separate tables for each event type or maintain a wide STRUCT where every possible field across all event types must be declared upfront (fast reads, but sparse and rigid). The other option is to flatten everything into an unwieldy schema with hundreds of columns. To sidestep that maintenance burden, many teams dump events into a plain JSON string column that introduces significant performance penalty. Querying a single nested field requires your engine to deserialize the entire JSON blob for every row. At scale, you burn compute and budget scanning terabytes of raw text to extract a few bytes of data.
Adding to the challenge, these pipelines typically demand mixed processing speeds. You need a real-time path (not near-real-time) to flag anomalies or high-risk events with sub-second latency, while simultaneously pushing those same events into analytical storage for deep historical analysis in batch.
With AWS Glue 6.0, you can tackle all of these challenges (schema heterogeneity, JSON scanning overhead, and mixed-latency requirements) from a single pipeline. Built on Apache Spark 4.1 with Apache Iceberg v3 support, AWS Glue 6.0 brings Variant columns, Variant shredding, Spark Real-Time Mode (RTM), and Arrow-native user-defined functions (UDFs) to a fully managed, serverless environment.
In this post, we walk you through how to build this multi-layer architecture using a financial services use case: a market risk pipeline processing trade pricing vectors. While the example is finance, the patterns apply wherever you deal with heterogeneous schemas, expensive JSON parsing, and mixed real-time/batch requirements such as IoT device fleets, multi-tenant SaaS platforms, logistics tracking, and beyond. We will show you how to flag high-risk trades with sub-second latency, stream everything into an Iceberg v3 data lake as Variants, and run batch Value at Risk (VaR) computations efficiently using Arrow-native UDFs.
Solution overview
A bank’s Market Risk team receives a continuous stream of trade pricing vectors from front-office systems. Each trade event carries:
A trade ID and book/desk IDs.
A pricing vector as semi-structured data. The schema varies by asset class (for example, equities carry risk sensitivities known as Greeks such as delta/gamma, foreign exchange (FX) carries volatility surfaces, rates carry curve sensitivities).
A region ID for jurisdictional reporting (uses a column DEFAULT value, so rows that omit it get auto-populated).
The team needs three things from this stream, each at a different speed. We build the pipeline in three layers, each addressing a distinct requirement with a purpose-built AWS Glue 6.0 capability.
Layer 1: Real-time trade position breach detection (sub-second latency)
Positions must be updated in sub-second time, not seconds of traditional micro-batch streaming. For a team monitoring position limits, those seconds mean trades can breach limits before the system reacts. Spark Real-Time Mode (RTM) eliminates the micro-batch boundary entirely, letting records flow continuously through the pipeline so that high-risk trades trigger alerts within sub-second latency of arrival.
Every trade must land in a queryable data lake within seconds, with heterogeneous pricing vectors stored without declaring a fixed schema upfront. The Iceberg v3 Variant type handles this natively. The raw semi-structured payload goes into a single column regardless of asset class schema. At write time, Variant shredding automatically extracts fields observed in the data into typed Parquet columns, so downstream analytical queries read only the columns they need without deserializing the full blob. Trade amendments and cancellations are handled at a lower cost with deletion vectors (merge-on-read), and column DEFAULT values reduce boilerplate in ingestion code.
Layer 3: Batch risk computation (minutes to hours latency)
Risk metrics like Value at Risk (VaR) must be computed in Python across millions of trades. Traditional row-by-row pickle serialization between the Java Virtual Machine (JVM) and Python is the bottleneck. Arrow-native UDFs process data as vectorized columnar batches, eliminating serialization overhead and accelerating Python-based risk calculations.
The solution uses three separate AWS Glue 6.0 jobs, each independently scalable:
Real-time path (Scala, gluestreaming): Reads trades from Amazon Managed Streaming for Apache Kafka (Amazon MSK), enriches them with risk scores and breach flags, and writes alerts to a downstream Kafka topic. It runs with a fixed set of workers that are always on. Downstream fraud detection and position limit systems consume the alerts topic for real-time blocking decisions.
Near-real-time path (PySpark, gluestreaming): Reads from the same MSK topic and lands the full trade history into an Iceberg v3 table. It uses Glue auto scaling and can scale down between batches, keeping costs lower.
Batch analytics (PySpark, glueetl): Reads from the Iceberg v3 table, extracts fields using variant_get, computes VaR across the portfolio, and writes aggregated risk reports to a downstream summary table.
The following diagram illustrates the solution architecture.
Figure 1: Real-time market risk pipeline on AWS Glue 6.0
Prerequisites
To follow along with this post, you need the following:
An AWS account in a Region where AWS Glue 6.0 is available.
We provide an AWS CloudFormation template that provisions all the resources needed for this walkthrough.
The stack provisions the following resources:
An Amazon MSK cluster with two topics: trade-risk-vectors (input) and trade-alerts (real-time alerts output).
An Amazon S3 bucket for Iceberg table storage and streaming checkpoints.
An AWS Glue database (risk_analytics_<account-id>_glue6b1).
An IAM role (GlueRole-<account-id>-glue6b1) with permissions for Glue, MSK, S3, and CloudWatch.
Virtual private cloud (VPC) networking: A Glue network connection (connection-<account-id>-glue6b1), S3 gateway endpoint, and Glue interface endpoint.
AWS Glue job rtm-alerts-<account-id>-glue6b1 (Scala): This job reads trades from MSK, scores risk in real time using Spark RTM, writes alerts to the trade-alerts topic.
AWS Glue job nrt-ingestion-<account-id>-glue6b1 (PySpark): This job reads trades from MSK, writes to Iceberg v3 table with Variant + shredding enabled.
AWS Glue job batch-var-<account-id>-glue6b1 (PySpark): This job reads from Iceberg v3 table, computes VaR with Arrow UDF, demonstrates deletion vectors.
AWS Glue job producer-<account-id>-glue6b1-helper (PySpark): This job generates sample trade events (equities, FX, rates) to the trade-risk-vectors topic.
Choose Create stack > With new resources > Upload a template file, and upload the downloaded template.
Enter the following parameters:
VpcId: Your VPC ID.
SubnetIds: At least two subnets in different Availability Zones.
SecurityGroupId: A dedicated security group that allows all inbound TCP traffic from itself (self-referencing rule).
RouteTableId: The main route table for your VPC.
Acknowledge the IAM capabilities and choose Create stack.
Stack creation takes approximately 20 minutes.
After the stack completes, open the AWS Glue console and start the jobs in this order:
Start rtm-alerts-<account-id>-glue6b1 and nrt-ingestion-<account-id>-glue6b1.
Once both show RUNNING, start producer-<account-id>-glue6b1-helper.
After the producer finishes (~3.5 minutes), run batch-var-<account-id>-glue6b1 for risk aggregation.
The consumers must be running before the producer starts so that trades are scored in real time and landed in the Iceberg table as they arrive. The batch job runs last because it reads from the Iceberg table that the near-real-time path populates.
Understand the Iceberg v3 table design
The CloudFormation stack provisions Glue jobs that create two Iceberg v3 tables, trade_risk_vectors (primary trade store) and daily_risk_summary (batch VaR output), using new data types and features:
VARIANT: Stores semi-structured pricing vectors without requiring a fixed schema.
DEFAULT values: Automatically applies provided defaults when fields aren’t provided.
Deletion vectors (merge-on-read): Enables fast row-level updates and deletes.
Open the AWS Glue console under Data Catalog > Tables > trade_risk_vectors.
Figure 2: The trade_risk_vectors table in the AWS Glue Data Catalog
Note the use of DEFAULT values for asset_class, var_contribution, risk_weight, and region. This is an Iceberg v3 feature that applies defaults automatically when values aren’t provided during writes, reducing boilerplate in ingestion code. The pricing_vector column is defined as a Variant type, and write.parquet.shred-variants='true' automatically extracts Variant fields into separate typed Parquet columns at write time for faster downstream queries.
Sample trade event generator
The CloudFormation stack includes a Glue job (producer-<accountid>-glue6b1-helper) that produces realistic trade events to the trade-risk-vectors MSK topic. Each event carries a pricing_vector with a completely different schema per asset class. This is exactly the problem Variant solves.
Equity trade (greeks, scenarios with sector/region breakdowns):
Figure 3: Sample equity trade pricing vector
Rates trade (curve sensitivities per tenor, calibration params):
Figure 4: Sample rates trade pricing vector
Completely different structures: greeks vs curve sensitivities, BlackScholes vs HullWhite. Both land in the same pricing_vector VARIANT column with no schema changes required.
Ingest trades with Spark Real-Time Mode
Traditional Spark Structured Streaming uses micro-batches: collect records, schedule a job, process, commit, wait. Even with small batches, the fixed overhead of planning and scheduling adds noticeable latency per batch. For a risk team monitoring position limits, the delay can let a trade breach a limit before the system reacts.
The following Scala job reads trade events from Amazon MSK, applies lightweight risk rules based on data directly available in the event, and writes alerts to a Kafka topic, all with sub-second latency. The real-time path intentionally avoids external lookups (market data, volatility surfaces) to stay fast. The full VaR computation happens later in the batch layer where latency is less critical.
You can view the complete job code in the AWS Glue console under the rtm-alerts-<accountid>-glue6b1 job. Additionally, all the scripts are available in the GitHub repository.
Figure 5: Scala real-time job that scores trades and writes alerts
The Trigger.RealTime("1 minute") is what distinguishes this from a traditional micro-batch. Records flow through the pipeline continuously. Records are processed the instant they arrive. The 1-minute parameter controls how often Spark checkpoints its progress for recovery. It does not control how often records are processed. RTM on AWS Glue 6.0 currently supports Kafka-source, stateless, Scala workloads with fixed workers (no auto scaling) and update output mode only. This makes it ideal for stateless transformations that require sub-second latency, such as the filter, enrich, score, and route pattern shown here. The heavier computation (VaR, aggregations) runs in the micro-batch/batch layer where sub-second latency is less critical.
The real-time path acts as a circuit breaker: trades over $50M notional are flagged CRITICAL, over $25M flagged HIGH. Downstream systems consume the trade-alerts topic and can block or escalate before the next trade executes. The detailed VaR computation (which requires market data, volatility surfaces, and the full pricing vector) runs in the batch consumption layer where latency is less sensitive.
After the streaming phase completes, the job reads back from the trade-alerts topic and measures end-to-end latency. It compares two MSK timestamps: when the trade was received by MSK from the producer, and when the alert was received by MSK from RTM.
To verify the alerts and latency, open the Amazon CloudWatch console > Log groups > /aws-glue/jobs/output and select the RTM job’s log stream. You will see the alert summary showing each flagged trade with its end-to-end latency. The following is a sample.
Figure 6: CloudWatch output showing flagged trades and end-to-end latency
Store trades in Iceberg v3 with Variant shredding enabled
The near-real-time path reads from the same MSK topic but writes to an Iceberg v3 table using standard micro-batch streaming. This job runs separately with auto scaling enabled, scaling between batches, keeping costs lower than the always-on real-time path.
You can view the complete job code in the AWS Glue console under the nrt-ingestion-<accountId>-glue6b1 job. The critical aspects are the Variant conversion and the Iceberg write:
Figure 7: Near-real-time PySpark job writing trades to Iceberg v3 as a Variant
The PARSE_JSON() function converts the raw pricing vector into a native Variant, regardless of the asset class schema. Whether the incoming trade is an equity with greeks, an FX option with a volatility surface, or a rates swap with curve sensitivities, it all goes into the same column. Since the table has write.parquet.shred-variants enabled, fields observed in the initial sample are automatically extracted into typed Parquet columns for fast downstream queries.
How shredding works
During the write process, Spark automatically extracts the Variant fields it observes into separate typed Parquet columns at write time, a feature called shredding. At the start of each write, the engine buffers a sample of rows (controlled by write.parquet.variant-inference-buffer-size), infers which fields exist and their types, then uses that schema to shred all subsequent rows in the file. Every field observed in that sample gets its own typed column, including nested objects. Rows that lack a particular field simply store NULL in that shredded column. For our risk table, fields like $.greeks.delta, $.dv01, and $.model all live in their own typed Parquet columns, even if only one asset class carries a specific field. The result: faster read performance because queries access only the typed columns they need, skipping the rest of the document entirely. Shredding is transparent to queries. variant_get() calls work the same way whether the field is shredded or not. The query engine automatically routes to the shredded column when available, falling back to the binary Variant blob for fields that aren’t part of the inferred schema.
Note: Shredding adds write latency because the engine must infer the schema and write additional typed columns. In this pipeline, we enable shredding on the near-real-time path and absorb that cost, since the downstream read benefits (batch VaR, ad-hoc queries, audit) far outweigh the write penalty. For latency-sensitive pipelines where every millisecond on the write path matters, you can disable shredding on the streaming table and instead write shredded data in a separate batch job that reads from the unshredded table and inserts into a shredded copy. This approach trades architectural simplicity for lower ingestion latency.
Build the batch consumption layer
The third AWS Glue 6.0 job reads from the Iceberg v3 table, extracts risk metrics from the Variant column, computes VaR using an Arrow-native UDF, and writes aggregated results to a summary table.
You can view the complete job code in the AWS Glue console under the batch-var-<accountid>-glue6b1 job. The key aspects are the variant_get extraction from deeply nested structures and the Arrow-native UDF:
Figure 8: Extracting nested Variant fields with variant_get
Notice how variant_get reaches into arbitrarily nested structures: $.greeks.delta (2 levels), $.scenarios[0].breakdown.by_sector.financials (5 levels), $.model_params.calibration.fit_error (4 levels). All with the same function call. No pre-flattening, no schema-per-asset-class tables, no ETL to restructure the data before querying.
Once the risk metrics are extracted, we need to run a Monte Carlo-style Historical VaR that simulates 1,000 daily profit and loss (P&L) scenarios per trade and returns the 99th percentile loss. This is where the @arrow_udf decorator comes in.
Figure 9: Arrow-native UDF computing Historical VaR
The @arrow_udf decorator is new in Spark 4.1. Your function receives and returns pyarrow.Array directly, operating on the entire batch of rows at once. There is no pickle serialization, no row-by-row invocation, and no Pandas conversion. Data flows as native Arrow columnar arrays between the JVM and Python. For compute-heavy operations like VaR across hundreds of thousands of rows, this can be significantly faster than traditional scalar UDFs. Additionally, you can use the built-in UDF profilers to identify performance and memory bottlenecks in compute-heavy UDFs such as VaR calculations.
Handle late trade corrections with deletion vectors
In financial markets, trade amendments and cancellations are common. The batch VaR job demonstrates this after completing the risk computation. It amends one trade and cancels another.
Figure 10: Amending and cancelling trades with merge-on-read
Prior to Iceberg v3, row-level deletes required either rewriting entire data files (copy-on-write) or maintaining separate positional delete files that store (file_path, row_position) pairs as Parquet rows (merge-on-read). Both approaches are expensive at scale. Copy-on-write rewrites gigabytes for a single amendment, and positional deletes degrade read performance as delete files accumulate (each read must parse and hash-join all delete records against the data file).
Because we configured the table with write.delete.mode='merge-on-read', UPDATEs and DELETEs write deletion vectors instead of positional delete files used in Iceberg v2. A deletion vector is a Roaring Bitmap stored in a Puffin file (.puffin), one per affected data file, marking which row positions are deleted. At read time, the engine loads a single bitmap and skips flagged positions with a bit check. No file joins, no linear scan through multiple delete files. The bitmap is compact regardless of how many rows are deleted, and read performance remains predictable as amendments accumulate.
The batch job also verifies the deletion vectors were created. You can see the results in the job’s output logs.
Figure 11: Output verifying deletion vectors were created
Clean up
To avoid incurring further charges, delete the CloudFormation stack. This removes all resources provisioned as part of this post, including the S3 bucket, Glue jobs, Iceberg tables, MSK cluster, and IAM roles.
Conclusion
In this post, we built a multi-layer market risk pipeline using AWS Glue 6.0 (real-time alerting, near-real-time ingestion, and batch analytics):
Spark Real-Time Mode (RTM) on the real-time path delivers sub-second trade scoring and breach alerting, eliminating the micro-batch boundary so position limits are enforced before the next trade executes.
Iceberg v3 Variant on the near-real-time path stores heterogeneous pricing vectors without schema flattening. One table handles equities, FX, and rates with different schemas per row.
Variant shredding delivers faster reads by automatically extracting fields into separate typed Parquet columns at write time with no manual tuning required.
Arrow-native UDFs eliminate pickle serialization overhead for Python-based risk calculations, processing data as vectorized columnar batches on the batch layer.
Deletion vectors handle trade amendments and cancellations without costly data file rewrites, using compact Roaring Bitmaps instead of accumulating positional delete files.
Default values reduce boilerplate in ingestion code.
As organizations build data lakes that combine geospatial data, high-frequency event streams, and heterogeneous payloads, the limitations of older table formats become acute. Without a native geospatial type, coordinates require separate float columns (latitude/longitude) with no spatial predicates. Without nanosecond-precision timestamps, sub-microsecond event ordering is lost. Without a variant type, semi-structured data forces a choice between rigid flattening and untyped JSON strings. Each workaround adds complexity, slows queries, and increases maintenance burden.
AWS Glue 6.0, powered by Apache Spark 4.1, removes these workarounds by adding support for Apache Iceberg v3, bringing new column-level capabilities to your data lake tables. These include new data types: native geospatial types (GEOMETRY with spatial predicates, and GEOGRAPHY), nanosecond-precision timestamps, and the VARIANT type for semi-structured data with automatic shredding. Iceberg v3 also adds support for DEFAULT column values. These are table format features. After they’re written, they’re readable by any Iceberg v3-compatible engine that supports these features.
In this post, we build a connected vehicle fleet monitoring pipeline that uses these capabilities in a single Iceberg v3 table. Vehicles emit telemetry events with GPS coordinates (geospatial), sub-microsecond event times (nanosecond), and sensor payloads that vary by vehicle type (variant). We ingest these events, run spatial queries to detect geofence violations, sequence events at nanosecond precision, and extract typed metrics from heterogeneous payloads, all without workarounds, flattening, or external libraries.
Solution overview
A logistics company operates a mixed fleet of delivery vehicles: vans, electric bikes, and delivery robots. Each vehicle type produces telemetry events with a different sensor payload schema. The operations team needs to:
Detect geofence violations: flag vehicles that enter restricted zones (airports, pedestrian areas, private property).
Sequence events precisely: at fleet scale, many events land in the same microsecond window. Nanosecond timestamps give a deterministic order and prevent ties when sequencing or deduplicating events during processing.
Extract metrics from heterogeneous payloads: query battery level from delivery robots, fuel level from vans, and pedal cadence from bikes, all stored in the same column.
We address all three requirements with a single Iceberg v3 table on AWS Glue 6.0. The following data definition language (DDL) shows the table structure. The AWS Glue job we provision in subsequent steps executes this statement.
In the preceding statement, the database is shown as fleet_monitoring_db for readability. The deployed stack creates it as fleet_monitoring_<account-id>.
The following list describes the key columns:
event_time TIMESTAMP_NTZ(9): Stores the event timestamp at nanosecond precision.
location GEOMETRY(4326): Stores GPS coordinates as native spatial objects using (SRID 4326). You can use predicates like ST_Intersects directly in SQL, replacing hand-coded spatial math on raw latitude/longitude doubles (WGS 84).
service_area GEOGRAPHY(4326): Stores geographic coordinates using a spherical (geodesic) model, distinct from GEOMETRY’s planar model. AWS Glue 6.0 writes and reads GEOGRAPHY in Iceberg v3, and the type is portable to any Iceberg v3-compatible engine. Geodesic spatial predicates over GEOGRAPHY are engine-dependent today. In this post we run spatial queries on the GEOMETRY location column, which Glue 6.0 supports natively.
sensor_payload VARIANT: Each vehicle type produces a different JSON schema. Vans report fuel and engine metrics, robots report battery and camera status, bikes report cadence and heart rate. All land in this single column without schema unions or separate tables using variant data type.
vehicle_type STRING DEFAULT ‘UNKNOWN’ and speed_kmh DOUBLE DEFAULT 0.0: When an ingestion writer omits these fields, Iceberg applies the declared defaults automatically. Useful when multiple producers write to the same table and not all of them populate every column.
The table uses PARTITIONED BY (days(event_time), vehicle_type) so that analytical queries can prune by date range and vehicle type without scanning the full table. 'write.delete.mode' = 'merge-on-read' supports fast row-level corrections (for example, correcting a misreported GPS coordinate) through compact deletion vectors (Roaring Bitmaps) instead of accumulating positional delete files.
In this post, we insert sample data directly to focus on the new Iceberg data types and how to use them together. In production, these events would stream from Amazon Managed Streaming for Apache Kafka (Amazon MSK) into an AWS Glue 6.0 streaming job.
The following diagram illustrates the production architecture for reference:
Figure 1: Reference architecture for a fleet telemetry pipeline on AWS Glue 6.0
The architecture processes vehicle telemetry through two paths, with a downstream batch analytics layer:
Hot path (real-time, milliseconds): A Spark Real-Time Mode (RTM) job reads telemetry from Amazon MSK and evaluates geofence violations using spatial predicates like ST_Intersects, routing alerts to a downstream Kafka topic within milliseconds.
Cold path (near-real-time, seconds): A micro-batch job reads the same MSK topic and writes events into an Iceberg v3 table, converting payloads to GEOMETRY, TIMESTAMP_NTZ(9), and VARIANT columns with DEFAULT values applied.
Batch analytics: An AWS Glue job reads the Iceberg v3 table to run batch analytics on geofence detection, nanosecond event sequencing, and per-vehicle-type metric extraction.
Prerequisites
To follow along, you need:
An AWS account and an AWS Region where AWS Glue 6.0 is available.
An AWS Identity and Access Management (IAM) role with permissions to deploy AWS CloudFormation stacks and create resources including AWS Glue, Amazon Simple Storage Service (Amazon S3), and Amazon CloudWatch Logs.
Deploy the CloudFormation stack
We provide an AWS CloudFormation template that provisions all the resources needed for this walkthrough.
The stack provisions the following resources:
An Amazon S3 bucket for Iceberg table storage.
An IAM role with permissions for AWS Glue, Amazon S3, and Amazon CloudWatch Logs.
An AWS Glue database (fleet_monitoring_<account-id>).
An AWS Glue job fleet-telemetry-ingest-<account-id> (PySpark): creates the Iceberg v3 table vehicle_telemetry described earlier and inserts sample telemetry from three vehicle types.
An AWS Glue job fleet-telemetry-queries-<account-id> (PySpark): demonstrates geofence detection, nanosecond sequencing, variant extraction, and default values.
Choose Create stack, With new resources, Upload a template file, and upload the downloaded template.
Acknowledge the IAM capabilities and choose Create stack.
Stack creation takes approximately 2–5 minutes. No parameters are required.
After the stack completes, navigate to the AWS Glue console and run the jobs in this order:
Run fleet-telemetry-ingest-<account-id>. This job creates the Iceberg v3 table and inserts sample data (approximately 2 minutes).
After it succeeds, run fleet-telemetry-queries-<account-id>. This job executes all demonstration queries (approximately 2 minutes).
The following sections describe each job in detail.
Job 1: Ingest sample telemetry data
The ingestion job creates the Iceberg v3 table described earlier and inserts four sample telemetry events: one for each of the three vehicle types (van, robot, bike), plus one with omitted fields to demonstrate DEFAULT values. You can view the complete script in the GitHub repository. Note that the geospatial types require one additional Spark configuration (spark.sql.geospatial.enabled=true), which is already set in the job’s --conf argument by the CloudFormation template. All other types work with no extra configuration.
The following are the key snippets from the script:
Van telemetry: GPS coordinates with engine metrics and route information:
Note: EVT-001 and EVT-002 are exactly 1 nanosecond apart (.123456789 vs .123456790). Without TIMESTAMP_NTZ(9), both would round to the same microsecond and be indistinguishable.
Default values test: Event inserted with vehicle_type, speed_kmh, and region omitted:
The omitted columns automatically receive their DEFAULT values: vehicle_type = 'UNKNOWN', speed_kmh = 0.0, region = 'EMEA'.
Job 2: Query the data
The query job demonstrates all four data types working together. After the job succeeds, select the run in the AWS Glue console and choose Output logs to see the results.
The following sections walk through the key queries from the job and the results of each.
Geofence detection with ST_Intersects
The job defines a polygon and finds all vehicles inside it:
POLY = "010300...."
SELECT event_id, vehicle_id, vehicle_type, speed_kmh
FROM fleet_monitoring_db.vehicle_telemetry
WHERE ST_Intersects(
location,ST_SetSrid(ST_GeomFromWKB(X'{POLY}'), 4326)
)
ORDER BY event_id
The polygon covers coordinates (0,0)-(5,0)-(5,2)-(0,2). Three vehicles are inside (ROBOT at (4,1), BIKE at (3,1), UNKNOWN at (1,1)). The VAN at (-0.1278, 51.5074) is outside.
Figure 2: Geofence query results showing the three vehicles inside the polygon
Nanosecond event sequencing
Order events by their sub-microsecond timestamps:
SELECT event_id, vehicle_id, CAST(event_time AS STRING) AS precise_time
FROM fleet_monitoring_db.vehicle_telemetry
WHERE event_id IN ('EVT-001', 'EVT-002', 'EVT-003')
ORDER BY event_time ASC
EVT-001 and EVT-002 are correctly distinguished and ordered despite being only 1 nanosecond apart. With standard TIMESTAMP_NTZ (microsecond precision), both would show .123456 and their relative order would be undefined.
Figure 3: Nanosecond-precision ordering distinguishing two events one nanosecond apart
Variant extraction with variant_get
Different sensor schemas per vehicle type, all extracted with variant_get:
SELECT vehicle_id, vehicle_type,
CASE vehicle_type
WHEN 'VAN' THEN variant_get(sensor_payload, '$.fuel_pct', 'DOUBLE')
WHEN 'ROBOT' THEN variant_get(sensor_payload, '$.battery_pct', 'DOUBLE')
WHEN 'BIKE' THEN variant_get(sensor_payload, '$.battery_pct', 'DOUBLE')
ELSE NULL
END AS energy_level,
variant_get(sensor_payload, '$.engine.temp_c', 'DOUBLE') AS engine_temp,
variant_get(sensor_payload, '$.cameras.front', 'STRING') AS front_cam,
variant_get(sensor_payload, '$.deliveries.completed', 'INT') AS deliveries_done
FROM fleet_monitoring_db.vehicle_telemetry
WHERE vehicle_type != 'UNKNOWN'
ORDER BY vehicle_id
variant_get takes three arguments: the column, a dot-path expression, and the expected return type. It supports arbitrary nesting depth. $.engine.temp_c reaches two levels deep, $.deliveries.completed reaches into a different structure entirely. When a path doesn’t exist in a particular row’s payload, it returns NULL.
Default values
Confirm that omitted columns received their defaults:
SELECT event_id, vehicle_type, speed_kmh, region
FROM fleet_monitoring_db.vehicle_telemetry
WHERE event_id = 'EVT-004'
Figure 5: Default column values applied to the event inserted with omitted fields
EVT-004 was inserted without vehicle_type, speed_kmh, or region. The declared defaults were applied automatically.
Combined query: Combining spatial, temporal, and variant operations
The following query runs a geospatial predicate, nanosecond ordering, and variant extraction in a single SELECT statement:
SELECT vehicle_id, vehicle_type,
CAST(event_time AS STRING) AS precise_time,
CASE vehicle_type
WHEN 'VAN' THEN variant_get(sensor_payload, '$.fuel_pct', 'DOUBLE')
WHEN 'ROBOT' THEN variant_get(sensor_payload, '$.battery_pct', 'DOUBLE')
WHEN 'BIKE' THEN variant_get(sensor_payload, '$.battery_pct', 'DOUBLE')
ELSE NULL
END AS energy_level,
speed_kmh
FROM fleet_monitoring_db.vehicle_telemetry
WHERE ST_Intersects(location, ST_SetSrid(ST_GeomFromWKB(X'0103000000...'), 4326))
ORDER BY event_time ASC
Figure 6: Combined query results over a single Iceberg v3 table
This single query combines a spatial predicate, nanosecond ordering, and variant extraction over one table, with no external libraries, pre-processing, or joins to separate geometry or payload tables.
Clean up
To avoid ongoing charges from the AWS Glue jobs and Amazon S3 storage, delete the CloudFormation stack when you’re done:
Select the stack you deployed earlier and choose Delete.
Conclusion
In this post, we stored and analyzed geospatial coordinates, nanosecond timestamps, and heterogeneous sensor payloads in a single Iceberg v3 table on AWS Glue 6.0, with sensible defaults applied automatically, no external libraries, and no schema flattening.
GEOMETRY columns replace latitude/longitude doubles and support native spatial predicates like ST_Intersects for geofence detection. GEOGRAPHY is stored natively.
TIMESTAMP_NTZ(9) preserves full nanosecond precision for event sequencing where microsecond resolution is insufficient.
VARIANT stores heterogeneous payloads (different schema per vehicle type) in one column with typed extraction through variant_get.
DEFAULT values keep field population consistent across multiple ingestion writers without duplicating logic.
All capabilities require Iceberg format-version 3. Geospatial requires one additional configuration (spark.sql.geospatial.enabled=true). Nanosecond timestamps, Variant, and DEFAULT values work with no extra configuration.
These capabilities apply wherever schemas vary by source (IoT fleets, multi-tenant software as a service (SaaS), event-driven architectures), timestamps need sub-microsecond precision (trading, sensor fusion, autonomous systems), or spatial operations replace coordinate workarounds (logistics, real estate, delivery networks).
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional
Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes.The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.