Tag Archives: Advanced (300)

Enforcing zero-trust dependency policies in AWS CodeBuild with JFrog Curation

Post Syndicated from Arik Yakir original https://aws.amazon.com/blogs/devops/enforcing-zero-trust-dependency-policies-in-aws-codebuild-with-jfrog-curation/

Software supply chain attacks are rising sharply. JFrog’s 2026 research recorded a 451% year-over-year increase in malicious npm packages, yet every application that pulls open source packages during a build is still taking the same fundamental risk. When a developer runs pip install or npm install, the build environment downloads dependencies directly from public registries with no verification that those packages are safe. A vulnerable or malicious package can slip into your container image, get pushed to a registry, and reach production before anyone notices. By the time a scanner flags a critical CVE, the damage is already done.

This is a familiar situation for teams building on any continuous integration and continuous delivery (CI/CD) platform, including AWS CodeBuild. A build completes successfully, tests pass, and the artifact ships. Days or weeks later, a security review reveals that one of dozens of transitive dependencies carried a known vulnerability, or worse, was a malicious package designed to exfiltrate secrets. The fix isn’t only patching. It’s rebuilding, re-testing, and redeploying, all while assessing the scope. What teams need is a way to enforce a zero-trust dependency policy: a gate that blocks risky packages at download time, before they ever enter the build. That is exactly what JFrog Curation provides. It evaluates every package at the moment it is downloaded. When a package violates policy, it returns an HTTP 403 (Access Denied) error, failing the build before a risky dependency enters your environment.

In this post, you’ll learn how to use JFrog Curation as a policy gate inside AWS CodeBuild to block vulnerable and malicious dependencies at download time, before they ever become an artifact.

The customer problem

Your team ships a container built from open source dependencies. Weeks later, a security scan surfaces a critical vulnerability in a transitive package you didn’t even choose. Now you’re scrambling to identify which images are affected, rebuild, re-test, and redeploy, all under time pressure and with no guarantee you’ve caught everything.

The root cause is that nothing enforces policy at the moment dependencies are downloaded. When a build runs pip, npm, or Maven, it pulls whatever the manifest declares directly from a public registry. Scanning catches problems after the artifact exists, but by then the vulnerable package is already in your image and potentially in production.

Solution overview

The pipeline is an ordinary container build with one decisive change: The only route to public package registries runs through JFrog Artifactory, and Curation sits on that route. A developer commit triggers CodeBuild, which runs a Docker build. Inside that build, pip install resolves through the Artifactory virtual repository. Approved packages flow through and the image is pushed to Amazon Elastic Container Registry (Amazon ECR). A blocked package fails the build before any image exists.

For this walkthrough, the policy is “Block Critical CVEs”, which rejects any package version with a Common Vulnerability Scoring System (CVSS) score of 9.0 or above. AWS CodeBuild is the orchestration layer that resolves dependencies, and JFrog Curation is the management layer that decides, package by package and in real time, what CodeBuild is allowed to pull. The result is an Amazon ECR repository that receives only images built from policy-compliant dependencies.

On failure, a small amount of post-build scripting (shown in detail in the post-build section) queries the Curation audit API (JFrog Curated Packages Audit Events service) and reports the blocked package, its CVE identifiers and CVSS scores, and any recommended fix versions.

Deployment architecture showing AWS CodeBuild resolving dependencies through JFrog Artifactory and Curation before pushing approved images to Amazon ECR

Figure 1: Deployment architecture for the AWS CodeBuild pipeline with JFrog Curation security gate

Prerequisites

Before starting the walkthrough, make sure you have the following accounts, tools, and permissions in place.

  • An AWS account with permission to create CodeBuild projects, ECR repositories, and AWS Secrets Manager secrets.
  • A JFrog Platform instance (SaaS or self-hosted) on a tier that includes JFrog Curation (Enterprise X or Enterprise+ with the Curation add-on).
  • An Artifactory user or access token with deploy and read permissions on your virtual PyPI repository.
  • Tools (installed locally or in your build environment):
    • AWS Command Line Interface (AWS CLI) v2, configured with credentials for your target account.
    • Docker Engine 20.10 or later.
    • Git, to clone the sample repository.
    • JFrog CLI (the walkthrough installs it during pre-build, but local testing requires it beforehand).
  • JFrog Curation setup:
    • In the JFrog Platform, create a remote PyPI repository that proxies https://pypi.org.
    • Create a virtual PyPI repository that includes the remote repository you created earlier.
    • Choose Curation, then Policies, and turn on a Block Critical CVEs policy scoped to the virtual repository.
  • Clone the JFrog curation gate sample repository. All file paths referenced later are relative to the repository root.
  • Accounts and subscriptions:
    • An active AWS account with permissions to create AWS CodeBuild projects, Amazon ECR repositories, and AWS Secrets Manager secrets.
    • A JFrog Platform subscription (SaaS or self-hosted) with access to JFrog Curation. If you need an account, JFrog offers a free trial.

Walking through the implementation

The pipeline is deliberately small. A handful of shell scripts are orchestrated by a CodeBuild buildspec.yml and a Dockerfile that does the dependency install. What makes it a security gate rather than a build is one design choice. Every pip install is forced to resolve through a curated JFrog repository instead of public PyPI and the build is only allowed to publish an image when Curation approves every package.

The following shows how the pieces fit together before we look at the code:

CodeBuild pipeline phases (pre-build, build, post-build) and the shell scripts responsible for each

Figure 2: CodeBuild pipeline phases and script responsibilities

1. Project layout

File Role
buildspec.yml CodeBuild entrypoint – wires the three phases together and sets shared env vars
scripts/setup.sh Pre-build: installs the JFrog CLI, loads secrets, configures pip + Docker auth
Dockerfile Defines the image. Its pip install is what actually gets curated
requirements.txt The pinned dependency manifest that Curation evaluates, package by package
scripts/docker-build.sh Runs the curated Docker build and captures the log
scripts/post-build.sh The gate: conditional push to the registry, or extract-and-report the block reason

2. buildspec.yml – the orchestrator

The buildspec keeps logic out of YAML and in versioned shell scripts to keep the pipeline testable locally and readable in review. Two details matter beyond the phase wiring:

  • shell: bash is set explicitly. CodeBuild defaults to sh, and the post-build gate relies on bash-only constructs like ${PIPESTATUS[0]}.
  • Secrets come from AWS Secrets Manager, which stores the JFrog token encrypted with AWS Key Management Service (AWS KMS), controls access through IAM policies, records every retrieval in AWS CloudTrail, and supports rotation without changing the buildspec. CodeBuild injects the value at runtime and masks it in build logs.
version: 0.2

env:
  shell: bash
  variables:
    JFROG_HOST: "<jfrog-host>"           # e.g. yourcompany.jfrog.io
    JFROG_REPO: "<repo-pypi-virtual>"    # curated virtual pip repo
    AWS_DEFAULT_REGION: "<region>"
    ECR_REPO: "<image-repo>"
  secrets-manager:
    JFROG_USER: "<secret-name>:username"
    JFROG_TOKEN: "<secret-name>:access_token"

phases:
  pre_build:
    commands:
      - bash ./scripts/setup.sh
  build:
    commands:
      - bash ./scripts/docker-build.sh
  post_build:
    commands:
      - bash ./scripts/post-build.sh

3. Pre-build (scripts/setup.sh) – install tooling and redirect pip

This phase does three jobs: install the JFrog CLI, authenticate to both registries, and reconfigures pip so it resolves through Artifactory.

# Install the JFrog CLI
curl -fL https://install-cli.jfrog.io | sh

# Register the JFrog server using the token from Secrets Manager
jf config add jfrog-server \
  --url="https://${JFROG_HOST}" \
  --access-token="${JFROG_TOKEN}" \
  --interactive=false
jf config use jfrog-server

# Point pip at the curated repo instead of public PyPI
jf pip-config --repo-resolve="${JFROG_REPO}" --server-id-resolve=jfrog-server

# Build the authenticated index URL the Dockerfile will use
export PIP_PROXY="https://${JFROG_USER}:${JFROG_TOKEN}@${JFROG_HOST}/artifactory/api/pypi/${JFROG_REPO}/simple"

# Authenticate to the container registry (destination for the trusted image)
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
export ECR_URI="${ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com/${ECR_REPO}"
aws ecr get-login-password --region "${AWS_DEFAULT_REGION}" \
  | docker login --username AWS --password-stdin \
  "${ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com"

# Authenticate to the JFrog Docker registry (for base images, if pulled through JFrog)
echo "${JFROG_TOKEN}" | docker login "${JFROG_HOST}" -u "${JFROG_USER}" --password-stdin

Importantly, jf pip-config writes a pip config that swaps the default index URL pypi.org for the JFrog virtual repo. From that point on, any pip install, including the ones inside the Docker build, asks Artifactory for packages. Artifactory serves approved packages from cache or fetches them from its PyPI remote, and returns an HTTP 403 (Access Denied) error for anything a Curation policy blocks. The application code never changes. The redirection is entirely in configuration.

4. The Dockerfile – where curation is actually enforced

The following is the full Dockerfile:

# Base image is pulled from Amazon ECR Public (not Docker Hub) so the build does not
# depend on an external/uncontrolled registry.
FROM public.ecr.aws/docker/library/python:3.11-slim

# Passed in by scripts/docker-build.sh (the curated JFrog index URL)
ARG PIP_INDEX_URL
ARG PIP_TRUSTED_HOST

WORKDIR /app

COPY requirements.txt

# Upgrade pip itself from public PyPI (pip is not the curated surface here)
RUN pip install --no-cache-dir --upgrade pip --index-url https://pypi.org/simple && \
    # …then install ALL app dependencies through the curated JFrog repo.
    # The if/else lets the same Dockerfile build locally (no build args) while
    # always going through JFrog in CI (build args present).
    if [ -n "$PIP_INDEX_URL" ] && [ -n "$PIP_TRUSTED_HOST" ]; then \
      pip install --no-cache-dir --index-url "$PIP_INDEX_URL" --trusted-host "$PIP_TRUSTED_HOST" -r requirements.txt; \
    else \
      pip install --no-cache-dir -r requirements.txt; \
    fi

COPY app.py .

EXPOSE 8080
CMD ["python", "app.py"]

The gate is the pip install -r requirements.txt step and the mechanism is --index-url. During the build phase, docker-build.sh passes the curated JFrog index URL into the build as PIP_INDEX_URL. When that argument is present, pip resolves all dependencies in requirements.txt through the curated JFrog repository instead of public PyPI. JFrog evaluates each requested name==version against your Curation policies before it serves the package:

Approved packages are returned normally and the layer builds. Blocked packages get an HTTP 403 (Access Denied) error from JFrog. pip treats that as a failed download, the RUN instruction exits non-zero, and the entire docker build fails. The image is never produced, let alone pushed. The policy decision is made during the image build process at the precise moment pip resolves each dependency against the curated JFrog repository.

5. The post-build.sh – where data is collected and a fix is proposed

The post-build phase decides what happens with the build’s result. It branches on the CODEBUILD_BUILD_SUCCEEDING flag that CodeBuild sets, which is the mechanism that ties the registry push to Curation’s verdict:

source /tmp/build-env.sh  # ECR_URI, computed back in the pre-build phase
if [ "${CODEBUILD_BUILD_SUCCEEDING:-1}" = "1" ]; then
  # success path --- every dependency passed Curation
else
  # failure path --- Curation blocked a package
fi

Note the source /tmp/build-env.sh at the top. Each phase script runs in its own subshell, so values derived earlier (like ECR_URI) don’t survive across phases. The pre-build step writes them to a file that this script reads back in. If every dependency was approved, the script pushes the trusted image to ECR (both the build’s tag and latest) and triggers the downstream deploy stage. Configure it like so:

docker push "${ECR_URI}:${IMAGE_TAG}"
docker push "${ECR_URI}:latest"

if [ -f ./scripts/deploy.sh ]; then
  bash ./scripts/deploy.sh
fi

This is the only path that puts an image in the registry.

If curation blocked a package and pip only surfaced an HTTP 403 (Access Denied) error, the script reconstructs the reason in three steps. First, identify the package by grepping the failing 403 out of the captured build log. pip names the package in the download URL:

BLOCKED_PKG=$(grep -oP "HTTP error 403 while getting .*/packages/.*/\K[^/]+(?=#)" \
  /tmp/docker-build.log 2>/dev/null | head -1 || true)
PKG_NAME=$(echo "$BLOCKED_PKG" | sed 's/[-=<>!].*//')
PKG_VERSION=$(echo "$BLOCKED_PKG" | grep -oP '[-=]{1,3}\K[0-9][^,; ]*' | head -1 || true)

Second, ask the Curation audit API which policy fired for that package (the policy name, the matched condition, and the category):

jf api "/xray/api/v1/curation/audit/packages?package_name=${PKG_NAME}&package_version=${PKG_VERSION}&num_of_rows=1" \
  | jq -r '.data[]?.policies[]? | " Policy: \(.policy_name)\n Condition: \(.condition_name)\n Category: \(.condition_category)"'

Third, run jf curation-audit for a human-readable explanation and a recommended compliant version:

echo "${PKG_NAME}==${PKG_VERSION}" > /tmp/blocked-pkg.txt
jf curation-audit --requirements-file=/tmp/blocked-pkg.txt --format=json \
  | jq -r '.[0].policies[]? | " \(.explanation)\n Recommendation: \(.recommendation)"'

(That last step is also where any CVE detail comes from, but only when the remote repo has pass-through for Curation audit enabled.)

Finally, the script fails the build:

exit 1

The logic is deliberate: the push is gated on the build succeeding, and the build only succeeds if Curation approved every dependency.

Seeing it in action

STEP 2 - DOCKER BUILD WITH JFROG CURATION
All dependencies resolved through JFrog Artifactory
DOCKER BUILD SUCCESSFUL - ALL DEPENDENCIES APPROVED BY JFROG CURATION
STEP 3 - PUSH TO ECR

On the blocked path, the build declares pyyaml==5.3, which carries two CVSS 9.8 vulnerabilities. Curation returns HTTP 403 (Access Denied) and the build fails before an image is ever produced:

==========================================
BLOCKED BY JFROG CURATION
==========================================
Package: pyyaml==5.3
Policy: Block Critical CVEs
Condition: CVE with CVSS score of 9 or above
Vulnerabilities:
- CVE-2020-1747: 9.8
- CVE-2020-14343: 9.8
Recommendation:
- CVE-2020-1747: 5.3.1
- CVE-2020-14343: 5.4
==========================================
PIPELINE FAILED - SKIPPING ECR PUSH
==========================================

Nothing reached Amazon ECR. There is no vulnerable artifact to remediate, because it was never built.

Curation and scanning are complementary

JFrog Curation is the prevention layer at the gate, and JFrog Xray, a software composition analysis (SCA) tool, is the detection layer for what is already inside. Together they cover both new downloads and previously cached artifacts.

Making it your own

This pattern is workload-agnostic. The example builds a container, but the same gate applies equally to your AWS Lambda function, microservice, or front-end application that resolves dependencies during its build. Curation policy is configurable. For example, layer multiple thresholds to block at CVSS 9.0 and warn at 7.0. You can also add license-compliance and malicious-package policies. Supported package types include PyPI, npm, Maven, and Docker. The enforcement point stays constant: CodeBuild resolves through Artifactory, and Curation decides what is allowed through.

Cleaning up

To avoid ongoing charges, delete the resources you created for this walkthrough: the AWS CodeBuild project, the Amazon ECR repository and any images it holds, the AWS Secrets Manager secret storing the JFrog credentials, and any IAM roles created for the build. If you configured the repositories solely for this exercise, you can also remove the JFrog Artifactory virtual and remote repositories.

Conclusion

By moving dependency enforcement into the build itself, an image is not published to Amazon ECR unless every package it contains has passed your JFrog Curation policies. A blocked package fails the build, so no image is pushed. This walkthrough demonstrated the pattern with PyPI and pip, but as described in the previous section, you can apply the same three steps to any package ecosystem.

Without this gate, the cycle described at the start of this post repeats: a build pulls an unverified package, the image ships, and weeks later your team is rebuilding, re-testing, and redeploying under pressure. With JFrog Curation enforcing policy at the point of download, that cycle stops. Risky packages are blocked before they enter the build, so they are kept out of your registry and away from your customers. Instead of reacting to vulnerabilities after the fact, your pipeline prevents them by default.

To get started, visit the AWS CodeBuild detail page and the AWS CodeBuild documentation. You can also explore the accompanying GitHub repository for the complete source code used in this walkthrough.

 


About the authors

Arik Yakir

Arik Yakir

Arik is a Senior Partner Solutions Architect at AWS. He works with technology partners to design joint solutions and better-together architectures on AWS.

Eldad Assis

Eldad Assis

Eldad is a Principal DevOps Architect, CTO Office at JFrog. He focuses on CI/CD automation and software supply chain security.

Anantha Kalusivalingam

Anantha Kalusivalingam

Anantha is a Senior Solutions Architect at JFrog. He specializes in DevSecOps and helping JFrog customers secure their software delivery pipelines.

Secure MCP integrations for AWS DevOps Agent with Amazon Bedrock AgentCore

Post Syndicated from Lakshmi Kumkala original https://aws.amazon.com/blogs/devops/secure-mcp-integrations-for-aws-devops-agent-with-amazon-bedrock-agentcore/

When the agent can’t reach data you need during an incident investigation, you extend it with new tools. You also manage the security and observability overhead of each tool you add. As you connect more Model Context Protocol (MCP) tools to AWS DevOps Agent, your security team ends up tracking a separate authentication scheme, credential rotation schedule, and audit or revocation procedure for each one. This post shows how to extend AWS DevOps Agent with MCP tools securely, using Amazon Bedrock AgentCore, so that new tools can inherit consistent security, access control, private connectivity, and observability.

AWS DevOps Agent is an AI-powered, always-available operations teammate that autonomously investigates incidents, identifies root causes, and prevents future issues across AWS, multicloud, and on-premises environments. It correlates Amazon CloudWatch metrics, logs, traces, and deployment history to produce root-cause analyses in minutes instead of hours. In Announcing General Availability of AWS DevOps Agent, AWS reported results from customers and partners who used AWS DevOps Agent in preview. They saw up to 75 percent lower mean time to resolution (MTTR), 80 percent faster investigations, and 94 percent root-cause accuracy.

By default, AWS DevOps Agent integrates with a broad set of observability, source control, continuous integration and continuous delivery (CI/CD), ticketing, and collaboration services. Real-world operational environments often extend further: proprietary configuration management databases (CMDBs), internal runbook APIs, application logs in OpenSearch, custom deployment tracking systems, or self-hosted tools behind private networks. When you need data from a source without a native integration, you can use MCP tools to give the agent a standardized way to call external services during an investigation.

You will learn when an MCP tool is the right answer, where to host it, how to connect it to AWS DevOps Agent, and how AgentCore Gateway, a capability of Amazon Bedrock AgentCore, provides a unified management layer for security, policy, and observability.

Where MCP tools fit in the incident lifecycle

Before examining tool infrastructure, it helps to see where MCP tools enter the picture. When your Amazon CloudWatch alarms, ServiceNow tickets, or PagerDuty alerts trigger an incident, AWS DevOps Agent begins an autonomous investigation. The following diagram shows where MCP tools extend that investigation beyond the agent’s native integrations.

Flow diagram showing an incident triggering an AWS DevOps Agent investigation, with MCP tools extending the investigation to data sources beyond the native integrations of the agent.

Figure 1: MCP tools extend the investigation reach of AWS DevOps Agent beyond its native and built-in integrations

These tools can connect to internal operational tools, third-party platforms, on-premises systems, or any custom data source you want to expose to an agent space. AWS DevOps Agent provides logging and the ability to disconnect any MCP server from the console, but you configure authentication, rotate credentials, and maintain the audit trail for each server. As the number of MCP servers grows, managing them independently creates compounding overhead: separate credential lifecycles, no cross-tool policy enforcement, and no unified view for observability across all tools.

AgentCore Gateway helps reduce this per-tool overhead. The agent connects to one endpoint, and tools behind that endpoint share the same security, policy, and observability configuration.

For more on triggering investigations automatically, see Trigger DevOps Agent from CloudWatch Alarms & Amazon EventBridge and Automating DevOps Agent from Incident Detection and Response alarms.

When to extend AWS DevOps Agent with MCP servers

Use this decision framework to choose between a native integration, an existing MCP server, and building a custom MCP server when you need a new data source or workflow.

Decision framework flowchart for choosing between a native integration, an existing vendor MCP server, and building a custom MCP server.

Figure 2: Decision framework for extending AWS DevOps Agent: native integration, existing MCP server, or custom MCP server

Start with what AWS DevOps Agent already covers. Before building anything, check the native capability list on the Capability Providers page. These integrations need no custom server to build or host. AWS DevOps Agent Tools catalogs additional MCP servers built for use with the agent. It is also worth browsing the AWS DevOps Agent ACP/MCP samples repository for reference implementations, and awslabs/mcp for AWS-published open source MCP servers such as the Amazon Managed Service for Prometheus MCP server and the Amazon Elastic Kubernetes Service (Amazon EKS) MCP server.

If a source is not natively covered, check whether a vendor already publishes an MCP server before building your own. Many do. For example, Atlassian’s Rovo MCP Server covers Jira, Confluence, Jira Service Management, and Bitbucket, and vendors such as Datadog and PagerDuty publish official servers.

Build a custom MCP tool when your source does not fall into any of these categories. The most common scenarios are:

  • Logs that need domain-specific parsing. AWS DevOps Agent can read log files in Amazon Simple Storage Service (Amazon S3) and query them with Amazon Athena once you grant it access. To do this, add the S3 read and Athena query permissions to its role as an inline policy, scoped to the buckets it needs. For more information, see Extending permissions beyond the default. For high-volume formats such as Application Load Balancer (ALB) access logs and VPC Flow Logs, a custom tool is often the better fit. An AWS Lambda-based MCP tool that parses and pre-filters these logs gives the agent the context to correlate a 502 spike with a specific backend failure. Application logs in Amazon OpenSearch Service follow the same pattern, because they need domain-specific language (DSL) query logic rather than raw document retrieval. For reference patterns, see Six Patterns for Connecting Amazon OpenSearch Service Logs to AWS DevOps Agent.
  • Internal operational tools. Runbook APIs, proprietary CMDBs, service ownership registries, and custom deployment tracking systems are not reachable through any native integration. An MCP tool wraps the internal API and exposes it as a callable tool during investigations.
  • On-premises or other-cloud telemetry. Data from on-premises monitoring systems or GCP infrastructure that is not captured in native AWS services requires tools that can reach those environments. For network-specific patterns, see Automated network incident response with AWS DevOps Agent.

AgentCore Gateway also provides one-click integrations for tools such as Jira, Salesforce, Slack, Asana, and Zendesk, as well as native support for Amazon Bedrock Knowledge Bases as a Gateway target. If your tool is available as a one-click target, you can skip building a custom MCP server and register it directly on the Gateway, which you then connect to AWS DevOps Agent as an MCP server through the agent’s capabilities.

Where to host your custom MCP server

After you decide to build a custom MCP tool, you need to choose where it runs. The right choice depends on statefulness, latency tolerance, connection requirements, and how much infrastructure you want to manage. The following table compares the four most common hosting options.

Hosting option Best for Advantages Trade-offs
AWS Lambda (direct IAM invoke) Stateless, read-heavy tools that execute quickly, such as Amazon S3 log parsers, OpenSearch query wrappers, runbook search, and internal API or ticket lookups No infrastructure to manage, pay-per-invocation, and auto-scales to zero. AgentCore Gateway invokes Lambda directly through IAM, without needing the HTTP layer, which removes Amazon API Gateway latency for Gateway-connected tools 15-minute execution limit, cold-start latency on first invoke, and no persistent connections
AWS Lambda with Amazon API Gateway Shared tools used by multiple teams or systems, and tools that require request throttling or AWS WAF protection All Lambda benefits, plus HTTP-level controls such as throttling, WAF protection, custom domains, and per-caller access logging Added per-request latency, Amazon API Gateway per-request cost, and more configuration
Amazon Bedrock AgentCore runtime Teams who want zero-ops MCP hosting with native multi-turn session support No infrastructure to manage, built-in session isolation, native MCP protocol support, both stateless and stateful modes, and support for your own container image. Works with any MCP framework, including LangGraph, CrewAI, and Strands Agents Cold-start latency when a new session starts, and less control over the underlying compute than Amazon Elastic Container Service (Amazon ECS)
Amazon ECS on AWS Fargate Database query tools that maintain connection pools, and tools with expensive initialization or large in-memory caches No cold starts, persistent connections, and full control over the runtime environment Always-on cost even when idle, and container image management overhead

For hosting walkthroughs, see Connect API Gateway to AgentCore Gateway with MCP for the API Gateway pattern and Deploy MCP servers in Runtime for AgentCore runtime. The AgentCore runtime released in September 2026 reduces cold starts to about two seconds at p75 regardless of container image size.

As a rule of thumb, start with Lambda for most read-only tools, move to AgentCore runtime, a capability of Amazon Bedrock AgentCore, when you need multi-turn sessions or zero-ops hosting, and use Amazon ECS when you need persistent connections or large in-memory state.

Connecting MCP servers to AWS DevOps Agent

There are two ways to connect MCP servers to AWS DevOps Agent. The right choice depends on how many tools you have, whether tool access needs to be consistent across multiple accounts, and whether you need central policy enforcement. The following diagram compares a direct per-account connection with a single connection through AgentCore Gateway.

Comparison of two connection paths. Path 1, direct connection, where AWS DevOps Agent registers each public and private MCP server per account. Path 2, where a single AgentCore Gateway endpoint fronts multiple targets including AWS Lambda, Amazon ECS, AgentCore runtime, and HTTP or third-party one-click targets.

Figure 3: Connecting MCP servers to AWS DevOps Agent: direct connection compared to AgentCore Gateway

Path 1: Direct connection

With a direct connection, you register each MCP server at the AWS account level from the Capability Providers page. To register a server:

  1. On the Capability Providers page, register the MCP server once with its endpoint URL and authentication credentials.
  2. In each agent space’s Capabilities tab, select the registered MCP server and choose which specific tools to enable for that space.
  3. Classify each tool as read-only, mutating, or destructive so that AWS DevOps Agent applies the correct safety controls during investigations.

Your MCP server must implement the streamable HTTP transport protocol and support one of the following authentication methods:

  • OAuth 2.0 Client Credentials.
  • OAuth 3LO (three-legged OAuth).
  • API key or token-based authentication.
  • Multi-auth headers (up to three secrets sent in HTTP headers that you name).
  • AWS Signature Version 4 (SigV4).

AWS DevOps Agent supports private connections natively. When you register an MCP server, select Connect to endpoint using private connection and choose or create a private connection. AWS DevOps Agent uses Amazon VPC Lattice to route traffic to your private endpoint entirely over the AWS network, with no public endpoint needed. Private connections work with any integration that needs to reach a private endpoint, including self-hosted Grafana or Splunk instances and source control systems such as GitHub Enterprise Server and GitLab Self-Managed. For a detailed walkthrough, see Securely connect AWS DevOps Agent to private services in your VPCs.

Tool safety with directed actions

When you connect an MCP server, you classify each of its tools as read-only, mutating, or destructive. The console prompts you for each tool, and API or CLI registrations set this with toolDetails. Read-only tools run without operator approval. Mutating tools are available only after you enable directed actions on the agent space, and each call requires operator approval in chat. AWS DevOps Agent does not invoke tools classified as destructive. If you register a server through the API or CLI without classifying its tools, every tool defaults to read-only, so classify any tool that can change state. For more information, see Working with directed actions.

Limit prompt-injection exposure

Custom MCP servers can introduce additional prompt-injection risk. Allow only the tools each agent space needs, prefer read-only tools, and give each server’s credentials read-only access. For more information, see the security considerations in Connecting MCP Servers.

Path 2: Amazon Bedrock AgentCore Gateway

AgentCore Gateway is a fully managed service that provides a single, secure entry point for agentic traffic, connecting agents to tools, to other agents, and to models. Instead of registering each MCP server independently in the AWS DevOps Agent account, you register all of them as targets on the Gateway. AWS DevOps Agent registers the Gateway URL once at the account level, and all tools from all registered targets become available through that single registration.

Gateway also consolidates authentication. AWS DevOps Agent connects to a single Gateway endpoint with AWS SigV4. It signs requests with either a dedicated IAM role or, if you register without one, the IAM role of the AWS account associated with the agent space. Grant that role bedrock-agentcore:InvokeGateway, scoped to the Gateway ARN. You still configure per-target credentials on the Gateway, because each backend MCP server has its own authentication. But the Gateway manages those credentials centrally, handling token refresh, secure storage, and credential lifecycle in one place rather than scattering them across individual agent space registrations.

With Policy in Amazon Bedrock AgentCore, you can enforce Cedar rules across every tool behind the Gateway with a single policy, for example blocking any tool that writes to production resources regardless of which MCP server exposes it. Because AWS DevOps Agent already refuses tools classified as destructive, Gateway policy is most valuable as an independent backstop in case someone misclassifies a tool.

Gateway also provides a unified audit trail and built-in observability automatically, with no instrumentation code and no per-target logging configuration. Amazon CloudWatch Logs records every tool call, including tool name, caller identity, request arguments, response, latency, and status, across all registered targets in one log group. AWS X-Ray provides end-to-end distributed traces across the MCP client, Gateway, and Lambda or runtime layers. The CloudWatch generative AI observability dashboard reports per-tool metrics, including invocation count, error rate, and latency percentiles (p50, p90, and p99). These metrics appear regardless of whether the tool runs on Lambda, Amazon ECS, AgentCore runtime, or a third-party server.

Gateway can also route to private MCP servers through VPC Lattice egress. If you need private connectivity together with the authentication, policy, and observability capabilities of the Gateway, register the tool as a private Gateway target. For connectivity patterns, see Private connectivity patterns for AgentCore Gateway Targets. If you only need private connectivity for a single tool without central policy, a direct private connection requires less configuration.

You can also route native MCP integrations through Gateway. Some AWS DevOps Agent native capabilities, such as the Grafana integration, connect to external MCP servers (Grafana’s own MCP server, in this case). If you want unified policy enforcement, observability, and authentication across both your native MCP-based integrations and your custom MCP servers, you can route them through AgentCore Gateway as well. This gives you a single control plane regardless of whether the tool came from the Capability Providers page or a custom registration.

For more on extending Gateway with MCP servers, see Extending MCP support for AgentCore Gateway and Transform your MCP architecture: Unite MCP servers through AgentCore Gateway.

Choosing between direct connection and Gateway

Use a direct connection when you have one or two MCP servers in a single AWS account, when each agent space configures its own tool set manually, and when you do not need cross-cutting policy enforcement. Choose AgentCore Gateway when you have multiple MCP servers and want to manage them through a single registration, when agent spaces across multiple AWS accounts need to share the same tools, when you want one authentication configuration, when you need Cedar policy enforcement across all tools, or when you want a unified audit trail and built-in observability. For full instructions, see Connecting MCP Servers in the AWS DevOps Agent User Guide.

Connectivity options at a glance

This table maps common scenarios to the recommended connection approach.

Scenario Recommended approach
One or two MCP servers, single account Direct connection
Multiple MCP servers, single registration preferred AgentCore Gateway
Agent spaces across multiple AWS accounts sharing the same tools AgentCore Gateway
Private VPC tool, no central policy needed Direct connection with DevOps Agent private connection
Private VPC tool with Cedar policy or unified auth Gateway with VPC Lattice target
Cedar policy enforcement across all tools AgentCore Gateway
Unified audit trail across all MCP servers AgentCore Gateway

Managing tool access with Gateway targets and policy

Beyond choosing a connection path, Gateway gives you finer control over which tools an agent space can reach.

Keep the per-space tool ceiling in mind as you scope access: a single agent space can have at most 500 MCP tools on the allowlist across all of its MCP servers, and this limit is not adjustable. Scoping each space to only the tools it needs keeps you well under that ceiling. For the full list of limits, see AWS DevOps Agent quotas.

When AWS DevOps Agent connects to an MCP server, its tools appear on the agent space console, where an admin selects which tools to allow and classifies each one as read-only, mutating, or destructive. This workflow exists with or without Gateway.

Gateway adds a mechanism on top: separate targets per tool category. Register read-only tools and write or destructive tools as separate Gateway targets, then associate AWS DevOps Agent with only the read-only target. The write tools don’t appear in that agent space, because they are not in the target. For how to register targets, see Add targets to an existing AgentCore Gateway.

For example, if an MCP server exposes list_runbooks, get_runbook, search_runbooks, upload_runbook, and delete_runbook, register a target named readonly-runbook-tools with only the first three. Connect the production agent space to the readonly-runbook-tools target, and connect development and staging agent spaces to a target that exposes all five tools.

Even when tools are visible and enabled in an agent space, Gateway policy, which uses Cedar, can block execution. This is the enforcement boundary below the admin workflow, and it holds regardless of what an admin configures on the console, which helps guard against configuration mistakes. For more on Cedar policy patterns, see Secure AI agents with Policy in Amazon Bedrock AgentCore.

Conclusion

AWS DevOps Agent covers a broad set of AWS services and third-party tools by default. When investigations need to reach further, into OpenSearch, internal runbook APIs, proprietary CMDBs, or tools in private VPCs, MCP tools extend that reach.

For one or two tools in a single account, a direct connection with account-level registration is sufficient. The picture changes when MCP servers multiply, when agent spaces span multiple AWS accounts, or when security teams need consistent enforcement and a unified audit trail. AgentCore Gateway collapses that to one registration per account pointing to a single Gateway URL. You configure authentication once, enforce Cedar policies consistently, get built-in CloudWatch observability across your tools, and revoke access in one place instead of across each tool registration.

For more on what AWS DevOps Agent can do by default, see Announcing General Availability of AWS DevOps Agent, AWS DevOps Agent features, and Native Capabilities.

Get started

To try this pattern, register one read-only MCP server as an AgentCore Gateway target, connect the Gateway to a non-production agent space, and classify each tool before you enable it. The following resources cover each step.

What Link
AWS DevOps Agent overview Product page · User Guide
Connecting MCP servers to AWS DevOps Agent User Guide – Connecting MCP Servers
AgentCore Gateway Developer Guide – Gateway · Getting started
Cedar policy for Gateway Understanding Cedar · Core concepts · Schema constraints
AgentCore runtime (MCP hosting) Deploy MCP servers in Runtime
Private connectivity VPC Lattice egress · Private endpoints · DevOps Agent private connections
Observability Service-provided observability · Observability overview
Gateway authentication Inbound auth setup · Cognito as IdP
Related blog posts Transform your MCP architecture with Gateway · Connect API Gateway to AgentCore Gateway · Why AgentCore chose Cedar
MCP/ACP samples DevOps Agent ACP/MCP samples
Samples DevOps Agent + CloudWatch sample

 


About the authors

Lakshmi Kumkala

Lakshmi Kumkala

Lakshmi is a Senior Technical Account Manager at AWS. Lakshmi works with enterprise customers on DevOps, operational excellence, and agentic AI architecture.

Hima Atluri

Hima Atluri

Hima is a Technical Account Manager at AWS, Global Financial Services. Hima helps customers build secure, observable operational workflows using AWS native services and agentic AI.

Building a gated review pipeline for AI coding agents on AWS

Post Syndicated from Owen Hawkins original https://aws.amazon.com/blogs/devops/building-a-gated-review-pipeline-for-ai-coding-agents-on-aws/

AI coding agents have changed the economics of writing software. Tools like Kiro turn specifications into working code, tests, and documentation, and a single agent can open dozens of pull requests across your repositories in an afternoon. What they have not changed is the number of senior engineers available to review those pull requests. The AI Productivity Paradox research from Faros AI drew on telemetry from more than 10,000 developers. It found that teams with high AI adoption merged 98% more pull requests while review time rose 91%. The gains did not show up in company-level delivery metrics. The constraint moved downstream, from writing code, to reviewing it.

The intuitive fix is to add an AI reviewer to every pull request. The evidence says that alone is not enough. Human-Centric to Agentic Code Review, a study of 1.02 million pull requests across 207 open source projects, found that reviews involving AI agents reached decisions faster but did not improve quality. After AI reviewers took part, the strongest factor explaining review efficiency was not the tooling, but how humans and agents were wired together in the review flow.

This post presents a pattern for wiring together humans and agents as part of code review. It introduces a gated review pipeline with six controls that pairs deterministic checks with verified AI review, applies your policy through risk-tiered gates, and keeps humans in charge of every consequential decision. It describes the core components of each control, how to implement them with AWS services, and how to measure the effect on defect and rework rates.

Two kinds of controls, and one wiring pattern

The AWS Blog Balancing speed and safety: a control framework for AI coding agents establishes a control taxonomy for what agents produce, through author-time controls (steering documents, specifications, and agent hooks) and pipeline scanning. It also introduces an AI-assisted review control. In this post, we expand that control into an operational design pattern. The pattern includes a review panel that produces verified findings, a deterministic gate that applies policy to findings, risk tiers that set agent autonomy, and metrics that show whether defect and rework rates fell.

This pipeline adds two design rules to that foundation. The first is a deliberate pattern for human and agent collaboration, because the research cited earlier found that collaboration patterns shape review efficiency. The second is risk-tiered autonomy. A documentation fix and a payments change carry different risk, so they shouldn’t pass through the same gate.

Assign the initial tier deterministically from what the change touches, not from what the author declares. Certain critical paths and files should be assigned the highest risk tier regardless of the change, for example changes to build and pipeline definitions, the Control 4 policy bundle, steering files, and the panel reviewer prompts. Changes such as a new dependency or an AWS Identity and Access Management (IAM) policy change should also escalate the risk tier. Evaluate related changesets together so a high-risk change can’t be split into low-risk pieces.

Tier Change risk Autonomy Review depth Evidence required
T1 Low (docs, internal tooling) Agent drafts, human approves Light spot-check Pull request + provenance tag (agent, model, requester)
T2 Medium (standard features) Agent drafts, engineer edits Full review + tech-lead sign-off Pull request + tests + approved spec or design notes
T3 High (payments, auth, data, changes to pipeline configuration) Agent assists, engineer implements Two human reviewers, plus architecture review when the design changes Full audit package
Diagram of the six-control gated review pipeline across deterministic, AI, and human columns, from standards through deterministic gates, the verified AI review panel, the policy gate, human judgment, and post-merge operations

Figure 1: An overview of the six controls in the gated review pipeline

The framework is methodology-agnostic. It composes naturally with structured approaches such as the AI-Driven Development Life Cycle (AI-DLC), but requires none of them. Where a team approves the specification before generation, that review settles whether this is the right change before any diff exists, leaving the pull request review to confirm it was built correctly.

Control 1: Standards consumable from one place

Code quality rules, architectural preferences, security standards, and compliance requirements each have an authoritative home where they’re owned, versioned, and published. Those homes can differ. A security team might keep a policy repository, compliance teams a wiki, and architects a decision log. All of these should feed a single consumption endpoint, so that every repository, pipeline, and agent pulls the same standards through the same mechanism instead of integrating with each source directly. Curating organizational knowledge into a form agents can consume is an easily underestimated investment. Funneling it through one consumption point means you make that investment once, not once for each repository and each source.

A single consumption point doesn’t require a single delivery mechanism. Retrieve situational standards on demand. Small, non-negotiable ones, such as production-safety guardrails, inclusive-language rules, and conventions for working with internal systems, belong in context on every interaction. Push those as baseline configuration, such as a global steering file or default agent configuration, so the agent doesn’t need to fetch them.

On AWS: Keep each standard in its authoritative home and put a single consumption layer in front of them. AgentCore Gateway, a capability of Amazon Bedrock AgentCore, can serve as that consumption point. It exposes each source as Model Context Protocol (MCP) tools from configuration alone, whether the source is a Git repository behind its provider’s MCP server, an HTTP endpoint, or Amazon Bedrock Knowledge Bases built over documents in Confluence or Amazon Simple Storage Service (Amazon S3). Every agent and tool then pulls the same versioned standards at runtime. The knowledge base is a retrieval layer for prose-style guidance that benefits from semantic search. It isn’t the system of record, and the owning team’s repository or document store remains authoritative. If you need evidence of which standard was in force for a given change, either sync a pinned copy into the repository as a pipeline step and record the version, or write the consumed standard version to an audit log at time of use. Deterministic consumers, such as linter configurations and the Control 4 policy bundle, should take the pinned path. A standards change then arrives as a version bump instead of failing every repository’s next build.

In the developer’s environment, the consumption format is whatever the agent reads, such as Kiro steering files or agent skills. Generate or sync those files from the gateway instead of writing them for each repository, so a local project becomes one more consumer of the same standards. For the always-on class of standards, generate the global steering files or default agent configuration from the gateway’s sources, and push them out through whatever provisions your developer environments. The gateway remains the on-demand path for situational standards.

Control 2: Deterministic gates first, with agent self-correction

The first gates to run are fast, deterministic, and hard-fail. These include formatting, lint, type checks, static application security testing (SAST), and secrets scanning. The remediation agent then self-corrects in a build, fail, fix loop until the stage passes or hits a maximum iteration cap, which hands the change to human review. Don’t use AI to review what a rule can catch. When the deterministic gates run first, the AI review stage sees only mechanically clean code and spends its reasoning on semantics instead of style. It also keeps most mechanical defects out of human review.

The self-correction loop is told to make the gates pass, and the shortest path to a passing gate is often a weaker gate. Treat suppression annotations, threshold changes, and removed or skipped tests in agent commits as change risk escalations.

The blog CI/CD Pipelines with agentic AI describes how Elastic does this. When a build fails, an agent steps in as a pipeline stage. It reads the failure logs, applies fixes from a deterministic tool allowlist, verifies the build, and commits, with auto-merge turned off whenever agent commits are present. In its first month, covering under half of Elastic’s dependencies, it fixed 24 broken pull requests and saved 20 days of development work.

On AWS: Run the same gates in two places. In the developer’s environment, Kiro agent hooks run them on file save and task completion. That catches defects before a pull request exists, where the fix loop is cheapest to run. The pipeline is the enforcement backstop. The same gates run in AWS CodeBuild on every pull request as a required status check, so a failing gate blocks the merge and nothing reaches review on the strength of a local run alone. Order them by cost and severity, as the predecessor post describes: secrets detection, SAST, software composition analysis (SCA), and then infrastructure as code (IaC) scanning.

When a pipeline gate fails, a remediation agent takes over. Because this agent commits to the repository, host it as a harness on AgentCore runtime, a capability of Amazon Bedrock AgentCore, outside the build, and call it from the failing CodeBuild action. The harness runs the agent loop in its own managed workspace. It treats the failure logs as untrusted data, applies fixes constrained by a tool allowlist, re-runs the gates, and commits to the source branch, reporting progress back to the pipeline. Authenticate that call with the pipeline’s IAM role so the automation runs on a workload identity you control, with no developer credential embedded in the build. Bound the loop with the harness’s execution limits. Cap fix attempts, set a wall-clock timeout, and give the agent a token budget. Count them per pull request, because each agent commit starts a new build. When any limit trips, the build stops and hands the failure to a human. Configure branch protection to dismiss approvals on new commits, so an agent fix always gets a fresh human review. For standing up the harness itself, see Hosting coding agents on Amazon Bedrock AgentCore.

Control 3: AI review as a verified panel

Run AI review as a panel of reviewers with distinct focus areas, for example, correctness, security, operational readiness, and, where the change was built from an approved specification, scope. Each seat on the panel is an agent that starts from its own clean context, which keeps it from inheriting assumptions about the code. Give each seat the diff as its focus, plus the full changed files and the dependencies they touch, so it reviews the change in context. An agent that sees only the changed lines can’t judge cross-file or architectural impact, and those are the defects most likely to survive the deterministic gates. From a security perspective, the code is untrusted input, so seats should be limited to sandbox environments with read-only tools.

Two sessions of the same model share the same blind spots. For each focus area on the panel, assign at least one agent to use a different model family than the author recorded in the provenance tag. For high-risk changes, you might run multiple agents with different models for the same focus area. Choose models by measurement. Evaluate candidates against past pull requests with known findings and prioritize models that score best for that focus area.

A two-stage verification step decides what reaches a human at the review gate. The first stage is deterministic. It confirms that the cited file and line exist and that the quoted code matches what’s there. A deterministic check can’t tell whether an anchored finding describes a real problem, which is a semantic judgment. The second stage can use a decision model, which returns one bounded answer (valid, invalid, or escalate to a human) with a confidence score. Because the answer is bounded, you can measure it. Evaluate the model against past findings with known outcomes, calibrate its thresholds, and route low-confidence cases to a human. Without this filter, volume works against you, as seen in one industrial deployment of a large language model (LLM)-based review tool. Average pull request closure time rose by more than 40%, even though developers acted on most of the automated comments.

On AWS: Run the panel seats as a single AWS CodeBuild batch build graph, one build per seat, each invoking an agentic coding harness in a fresh session and writing its findings to Amazon S3 under the commit’s key. Mount the checked-out repository so each seat has that context. The agents run inside CodeBuild because they only read code the build has already checked out, in an environment discarded after the run. The remediation agent in Control 2 writes to the repository, so it runs on AgentCore runtime under its own identity and limits.

A verification build that depends on the agents then reads their findings and runs the two-stage check. The deterministic pass checks each finding against the checked-out code and discards any finding whose file, line, or quoted code doesn’t match. A validity judgment then runs on what remains. The open source Strands Decider models fit that judgment, returning a bounded valid, invalid, or escalate classification with a confidence score. The verified, high-confidence set passes to the Control 4 gate, and low-confidence cases go to a human. For the security seat, you can use an open source harness such as the Visa Vulnerability Agentic Harness, which applies the same pattern to vulnerabilities. It uses deterministic stages for repeatable work and agentic stages for judgment, verifies each finding adversarially, and produces Static Analysis Results Interchange Format (SARIF) output that a gate can read. Run your chosen harness in a detection-only mode, so it emits findings without editing code, and feed its output to the same verification step and gate as the other agents.

Control 4: A deterministic policy gate on structured findings

The AI review panel in Control 3 never approves or blocks. It emits structured findings, each with a severity (important or minor), whether this change introduced it or it was pre-existing, and its evidence. Findings use a standard format such as SARIF, so deterministic and AI findings reach the gate in the same shape. A deterministic gate then applies your policy to that signal. It blocks on important findings, fast-paths clean changes, forces oversized changesets to split, and scales all of it by risk tier. Keeping policy in a deterministic component, apart from the model judgment it acts on, is the core of this pipeline. It makes the merge gate auditable, reproducible, and tunable for each repository. An empty finding set means the panel found nothing, not that nothing is there. Fast-path rules might shorten the queue for T1 changes but should never reduce human review depth at T2 or T3.

On AWS: Have the verification build write the verified findings to Amazon S3, keyed to the commit, as the record of that run. Then make the gate itself policy as code. A CodeBuild step or an AWS Lambda function evaluates the findings against rules written in Open Policy Agent or Cedar. The rules encode the preceding policy, scaled by risk tier. Oversized changes reach the gate less often when the specification breaks work into reviewable tasks. The gate reports to the pull request as a status check and posts a severity summary, for example “2 important, 4 minor,” before the verified findings. The rules ship in the pinned standards bundle from Control 1, so changing the merge bar means publishing a new policy version.

Control 5: Human judgment on a pre-triaged change

Human review remains a key pipeline component. What changes is what the human reads. Instead of a raw diff, the reviewer gets a change that the gates have made mechanically clean and the panel has triaged into ranked, evidence-backed findings. The reviewer no longer needs to catch what rules and agents already catch, and can focus on the judgments only a person can make. Is this change worth its risk? Does it fit the system’s design? Does it carry business context the agents never had? Are the important findings resolved, or only acknowledged?

Scale the depth to the tier: a T1 change needs one approver doing a light spot-check, a T2 change a full review with tech-lead sign-off, a T3 change two human reviewers plus architecture review when it changes a design boundary. The person who directed the agent is the change’s author and doesn’t count toward its reviewers. Review depth scales with risk, and the human decision is never delegated.

On AWS: Your existing pull request approval flow stays the baseline human gate. The panel’s verified findings land as review comments with a severity summary at the top, so the approver starts from a pre-triaged change. For T3 changes, require a second human reviewer before merge, and use your source provider’s approval rules to block approval by the requester. After merge, an AWS CodePipeline manual approval action adds a second recorded decision before production. It notifies approvers through an Amazon Simple Notification Service (Amazon SNS) topic routed to wherever they already work. Have the tooling that runs the agent, not the agent itself, write the provenance tag as commit trailers that record the agent, model, session, specification, standards version, and requester.

Architecture diagram of the pre-merge flow in AWS Cloud, where AgentCore Gateway serves standards to the developer environment and pipeline, deterministic gates run in CodeBuild, a four-seat AI review panel writes verified findings to an Amazon S3 store, and a Lambda policy gate and branch protection enforce tiered human review before merge

Figure 2: The pre-merge pipeline, where standards, deterministic gates, the verified review panel, and the policy gate run as pull request checks and branch protection enforces the gate and the tiered human review

Control 6: Post-merge verification and operations

The same logic extends after merge. Tests that ship with a change go through Controls 2 and 3 with the change. This control covers suite-improvement tests that an agent generates against existing code. Meta’s TestGen-LLM is an example. It admits a generated test only after the test clears filters showing that it measurably improves the existing suite. Admit these tests as you would untrusted contributions. They must build, pass reliably across repeated runs, and measurably improve the suite, through a coverage delta or a mutation score, before a human spends time on them. The filter removes tests that add nothing, but it can’t tell whether the asserted behavior is correct, because a test generated against existing code records what the code does today. That judgment belongs to a person, and it matters more here. A test that pins wrong behavior into the regression pack blocks the future change that fixes it. Tests that clear the bar join the regression pack that the deterministic gates run on every later change, so post-merge generation keeps strengthening the pre-merge gates. In operations, agents investigate on their own, reading telemetry, correlating signals, and proposing mitigation plans, while a person approves any remediation.

On AWS: Enforce the coverage or mutation threshold in a CodeBuild project that runs as an action in a dedicated stage of your CodePipeline. A generated test that doesn’t measurably improve the suite fails the build and never reaches the regression pack. This is the same mechanism as Control 2, pointed at a different signal. There, the build fails on lint, type, or SAST violations. Here, it fails on a coverage delta or mutation score that doesn’t clear the bar. For operations, AWS DevOps Agent fits this split. It’s read-only by default, investigating pipeline and operational failures and proposing mitigation plans for a person to approve.

Measuring whether it works

The research cited earlier found that AI review made decisions faster without making them better. Cycle time is the number most readily moved, and it can improve while quality degrades. Track review cycle time, because review is the constraint this approach exists to relieve, but only alongside the following quality measures. Avoid lines of code and pull request counts entirely, because they measure activity, not outcomes.

Measure instead:

  • Defect escape rate and rework rate – Bugs found after merge, and changes that need follow-up fixes.
  • Change failure rate and time to restore – The DevOps Research and Assessment (DORA) stability metrics, which show whether stability held as change volume grew.
  • Finding acceptance rate per panel seat – A falling rate means the seat is getting noisier, or that reviewers have stopped engaging with its findings. Check the seat first.
  • Panel recall – The share of escaped defects the panel would have flagged, found by replaying them through it. Acceptance shows what the panel gets right, and recall shows what it misses.
  • Changeset size drift – Agents will absorb ever-larger diffs if you let them. Keep changes small even as more of them are automated.
  • Cost per accepted finding – Model and compute spend divided by the findings that reviewers acted on, by seat and tier. It shows which seats earn their place and where tier policy should run fewer.

For the executive rollup, cost to serve software, defined as total delivery cost divided by units of value delivered, captures the whole system. Faster generation that creates more review burden shows up as a worse cost to serve. Pair cost to serve with tension metrics, such as security incidents and rollback rate, so the number can’t be improved by cutting controls. Developer experience work at Amazon reported a 15.9% year-over-year reduction on this measure in 2024.

On AWS: Measure from the signals the pipeline already emits instead of building a parallel system. Route CodePipeline and AWS CodeDeploy deployment events, plus your incident records, through Amazon EventBridge to AWS Lambda and into Amazon CloudWatch for the change failure rate and time-to-restore metrics. The DORA metrics sample is a useful reference for wiring this up. The review-quality metrics come from artifacts the pipeline already writes. Query the Control 4 findings store in Amazon S3 with Amazon Athena for acceptance rate per seat and changeset size drift. For that, the gate records each change’s tier and size in its report, and each finding’s outcome on the pull request (resolved or dismissed) is written back to the store. Defect escape and rework rates need one deliberate link. Tag post-merge defects and their follow-up fixes back to the commit that caused them, so the numbers attribute to a change.

Roll the executive view up in Amazon QuickSight, showing cost to serve software alongside the tension metrics that keep it from being gamed.

Architecture diagram of the post-merge flow, where an AWS CodePipeline re-runs backstop gates, admits generated suite tests, requires T3 manual approval before deploy, and uses AWS DevOps Agent for operations, while Amazon EventBridge, AWS Lambda, Amazon CloudWatch, Amazon Athena, and Amazon QuickSight produce delivery and review-quality metrics

Figure 3: The post-merge pipeline re-runs the gates, admits generated tests, adds the T3 approval before production, and feeds delivery and review-quality metrics

An incremental adoption path

Roll the pipeline out in stages instead of all at once. Each stage produces the evidence you need to trust the next. A baseline tells you whether anything improved, airtight deterministic gates show what the panel adds beyond rules, and an advisory panel shows whether its findings deserve to block.

  1. Baseline first. Capture defect escape and rework for four weeks before you turn anything on, or you will have no evidence story. Expect escape rates to lag, because defects surface weeks after merge. Rework moves sooner.
  2. Deterministic gates next. Get Control 2 airtight with the agent self-correction loop. This step alone keeps most mechanical defects out of human review.
  3. Add the panel selectively. Pick starter repositories with high pull request volume and moderate (T2) risk, where you get signal fast without affecting a critical system. In this phase, the panel is advisory. It posts findings but doesn’t block anything, because the policy gate isn’t wired yet. Use this window to confirm its value. Watch the finding acceptance rate, and check whether the panel surfaces real issues your reviewers were missing before you let severity block anything.
  4. Wire the policy gate only after the panel has earned trust. When acceptance rates are stable and engineers act on the findings, let severity block merges.
  5. Extend to tests and operations last.The same evidence can widen agent autonomy over time, for example letting the remediation agent fix verified findings in categories where the panel has proven reliable. Teams with long-established trust in their pipeline sometimes go further and auto-merge low-risk changes, as the Kiro Crew team describes.
Timeline of the staged rollout: a measurement baseline, deterministic gates, a selective AI panel, the policy gate, and then tests and operations, aligned to rising risk tiers from T1 to T3

Figure 4: The staged rollout, from a measurement baseline through deterministic gates, a selective AI panel, the policy gate, and finally tests and operations, aligned to rising risk tiers

The same pipeline, two changes

The following table follows a T1 change and a T3 change through all six controls. The pipeline is the same for both. What changes is autonomy and review depth.

Control T1: fix a broken link in the README T3: change refund-retry logic in the payments service
1. Standards Pulls the same standards, and the always-on security and compliance guardrails that are baseline config for every change
2. Deterministic gates Formatting and link-check run, pass, nothing to self-correct SAST, secrets, SCA, and IaC scans run. The agent self-corrects a flagged dependency, re-runs, and passes within the bounded loop
3. AI review panel Skipped by T1 policy, because the Control 2 link check already verified the fix Full panel runs with repository context. The security and correctness seats flag an auth-scope concern on the retry path, which is verified and passed to the gate
4. Policy gate T1 policy: no important findings, fast-path to a single approver T3 policy: an important finding blocks, oversized-diff check passes, routed for full review
5. Human review One approver, light spot-check, merge Two human reviewers, and the auth-scope finding must be resolved, not only acknowledged. T3 adds the CodePipeline manual approval before production
6. Post-merge Nothing further Agent-generated suite-improvement tests on the touched module must clear the coverage bar before a human looks. Operational signals are watched after deploy

Conclusion

AI coding agents are accelerating code generation and making code review the constraint. Adding an AI reviewer doesn’t remove that constraint on its own. Outcomes depend on how humans and agents are wired together. In this post, we showed a pipeline that wires them together to speed up review while reducing risk. Deterministic rules catch the first issues. A verified panel reviews what remains and emits a structured signal, a deterministic gate applies your risk-tiered policy to that signal, and a human makes the final call on a pre-triaged change. The same pattern extends to generated tests and operations.

Before you implement this pattern, read the predecessor post, Balancing speed and safety: a control framework for AI coding agents, which covers the author-time controls this pipeline assumes. To implement Controls 1 and 2, explore Kiro steering files and agent hooks. For broader control guidance, see the AWS Well-Architected Agentic AI Lens. If you try this pattern, tell us what you learn in the comments.

If you’re attending AWS re:Invent 2026, join us in the workshop SEC416, where participants get hands-on experience building out this pattern.

 


About the authors

Owen Hawkins

Owen Hawkins

Owen is a Principal Solutions Architect at Amazon Web Services, working with independent software vendors in the UK. Building on more than 20 years in information security and digital banking, he now spends his time on agent identity and on helping engineering organizations improve their software development lifecycle with AI-driven approaches.

Trevor Schiavone

Trevor Schiavone

Trevor is a Senior Solutions Architect at Amazon Web Services where he partners with enterprise customers to design and implement cloud and AI solutions. With over 10 years of experience spanning software engineering, cloud architecture, and artificial intelligence, he brings a practical, customer-driven perspective on how organizations can innovate responsibly with AI.

Chris Williams

Chris Williams

Chris is a Senior Solutions Architect at AWS, based in London, where he supports independent software vendors (ISVs). A software engineer by background, he has been building on AWS for over a decade, with over five of those years at AWS. He specializes in the software development lifecycle (SDLC), helping engineering teams improve how they plan, build, test and ship software. His work covers everything from CI/CD and infrastructure as code to AI coding assistants such as Kiro and the AI-Driven Development Life Cycle (AI-DLC). DevOps has always been his passion.

How Rakbank built centralized observability at scale with Amazon OpenSearch Service

Post Syndicated from Georges Hamieh original https://aws.amazon.com/blogs/architecture/how-rakbank-built-centralized-observability-at-scale-with-amazon-opensearch-service/

In this post, we discuss how Rakbank retail digital banking platform ingests approximately 150 GB a day of telemetry across a cross-account, Multi-Availability Zone (Multi-AZ) Amazon OpenSearch Service design, with hot/warm/cold tiering, 7-year compliance retention backed by Amazon Simple Storage Service (Amazon S3), and approximately 55 percent cost savings over an all-hot cluster.

Context and workload profile

Rakbank’s retail digital banking platform runs as containerized microservices on Amazon Elastic Kubernetes Service (Amazon EKS), and its observability requirements are driven by a few hard numbers. The platform now generates roughly 150 GB of logs per day on average, up from about 5 GB/day before the migration. That produces around 9 TB retained in OpenSearch Service over a 60-day window (150 GB/day × 60 days), with the most recent 30 days directly searchable. Retention runs to seven years for compliance, aligned with Central Bank of the UAE (CBUAE) requirements and Rakbank’s internal data-retention policy. At an average of 150 GB per day, that archives approximately 54 TB of log data per year, or approximately 383 TB over seven years. On the consumption side, 25 dashboards serve about 25 concurrent users. The data itself has an important property: logs are append-only. After written, a log document is never updated or deleted, so there is no update or delete-by-query churn. (Where regulatory write-once-read-many immutability is required, the S3 archive bucket can enforce it with Amazon S3 Object Lock.)

The append-only pattern is architecturally significant: because indices are no longer written to once they roll over, force-merging them to a single segment per shard before warm migration is safe, and there is no update overhead as indices roll down the tiers.

Telemetry pipeline: Fluent Bit

Instrumentation follows an instrument once, standardize everywhere model on a Fluent Bit standard across all banking domains (retail, business, wholesale). Concretely:

  • Fluent Bit runs as a DaemonSet on the EKS cluster, tailing container stdout/stderr on each node and enriching records with Kubernetes metadata (pod, namespace, labels) before routing.
  • Fluent Bit performs a dual-write/parallel archive: one path ships to the OpenSearch Service ingest endpoint (hot), a parallel path lands raw log objects directly in Amazon Simple Storage Service (Amazon S3) for durable backup independent of the search tier.

Cross-account topology and private connectivity

The design separates the workload from its observability plane using two accounts:

Application account

  • Amazon EKS cluster running the app pods in the Application virtual private cloud (VPC).
  • Fluent Bit DaemonSet for container-log collection and routing.
  • A parallel archive path to Amazon S3 (Log Archive & Backup).

Observability account

  • A dedicated OpenSearch Service centralized logging domain in the OpenSearch Service VPC, spanning three Availability Zones.
  • OpenSearch Service Dashboards as the access/visualization layer, routed to the hot data nodes.

Connectivity. Cross-account log flow traverses an AWS Transit Gateway, keeping all communication private within AWS. No traffic egresses to the public internet. In practice, Transit Gateway route tables provide reachability between the application and OpenSearch Service VPCs. Access is scoped at the VPC boundary by security groups and network ACLs that permit only the required ingest traffic (HTTPS/443) to the domain.

The following diagram shows the full cross-account path: application pods write logs through a Fluent Bit DaemonSet, which both forwards them privately over AWS Transit Gateway to the OpenSearch Service domain and archives a parallel copy to Amazon S3.

Cross-account architecture showing Amazon EKS pods sending logs through Fluent Bit over AWS Transit Gateway to a Multi-AZ OpenSearch Service domain with Amazon S3 archival

Figure 1: Centralized observability platform showing cross-account log flow from the EKS application account across AWS Transit Gateway into the Multi-AZ OpenSearch Service domain with hot, UltraWarm, and cold tiering and Amazon S3 archival

In the Application account, three application pods on the Amazon EKS cluster write logs that a Fluent Bit DaemonSet collects. Fluent Bit ships one copy over AWS Transit Gateway to the Observability account and archives a parallel copy to the Amazon S3 Log Archive and Backup bucket. In the Observability account, the OpenSearch Service centralized logging domain spans three Availability Zones. Each zone has a dedicated cluster-manager node (m8g.large.search) and a hot data node (m8g.2xlarge.search) that ages out to an UltraWarm node (ultrawarm1.medium.search) and then to a shared, node-free S3-backed cold storage tier. OpenSearch Service Dashboards reads from the hot data nodes for visualization.

Identity and cross-account authorization flow

The platform spans two accounts, with access governed by the layered security model of OpenSearch Service: network isolation (VPC and private Transit Gateway connectivity), the domain’s resource-based access policy, and fine-grained access control (FGAC) on the VPC domain. End users reach OpenSearch Service Dashboards through Security Assertion Markup Language (SAML) 2.0 single sign-on federated to Rakbank’s corporate Active Directory. Access follows existing enterprise identities and group memberships, with no separate OpenSearch Service credentials. Log ingestion from the application account is authorized separately from user access, keeping the write path and the read path on distinct, least-privilege roles. Together these layers keep all telemetry flowing privately within AWS while access stays centrally governed in Active Directory.

Cluster topology (per-AZ node roles)

The domain is a 3-AZ deployment with dedicated cluster-manager nodes separated from data nodes:

Role Per-AZ instance Count Purpose
Cluster manager m8g.large.search 3 (1/AZ) Cluster state, shard allocation, no data
Hot data node m8g.2xlarge.search 3 (1/AZ) Active indexing + real-time query
UltraWarm node ultrawarm1.medium.search 3 (1/AZ) Read-only, S3-backed warm segments
Cold tier No nodes — Detached S3-backed storage, managed by OpenSearch Service

The hot data and cluster-manager nodes are Graviton (m8g) for better price/performance. Dedicated cluster-manager nodes isolate cluster-state management from indexing and query load, which matters after you’re pushing 150 GB/day through the hot tier.

Storage tiering: right data · right store · right cost

The core mechanism is OpenSearch Service multi-tier storage, with indices aging through tiers using Index State Management (ISM) policies keyed off index age:

Tier Backing Retention Access pattern Instance/store
Hot Amazon Elastic Block Store (Amazon EBS) (gp3) volumes on data nodes 0–15 days Real-time dashboards, active troubleshooting, alerting m8g.2xlarge.search
Warm (UltraWarm) Amazon S3 + local cache 15–30 days Read-only historical analysis. Cost-optimized, still fully searchable ultrawarm1.medium.search
Cold Amazon S3 (detached, no nodes) 30–60 days Older logs for on-demand investigation. Attach to UltraWarm when needed S3-backed, 0 compute at rest

How the lifecycle behaves:

  • Hot → UltraWarm: ISM transitions indices at approximately 15 days. UltraWarm keeps primary shard data in S3 while caching hot blocks locally, so queries still run, only at higher latency and far lower cost per GB. Because rolled-over indices are no longer written to, they are force-merged before migration for faster warm-tier read performance.
  • UltraWarm → Cold: At approximately 30 days, indices detach to the cold tier, which is pure S3 storage with no dedicated compute. Cold indices are not directly searchable: to query them, you selectively attach them back to UltraWarm nodes on demand. (Querying the raw S3 archive without reattaching is a separate path that uses Amazon Athena.)
  • Compliance archive (S3 + Athena): Everything also lands in a separate Amazon S3 bucket for the full 7-year window, and is queried with Amazon Athena, at the lowest cost per GB. This decouples how long data must be kept from how much hot compute is paid for.

Durability details called out in the design: The durability of Amazon S3 means the design can run 0 replicas on the warm/cold tiers and remain durable (S3 handles redundancy), which further cuts cost. UltraWarm is a read-only warm tier, and Graviton (m8g) powers the hot and cluster-manager nodes.

Alerting. Hot-tier data drives OpenSearch Service alerting with email and Microsoft Teams destinations for real-time operational alarms.

Production sizing and cost model

Sizing target: 150 GB/day average, 60-day retention (30 days directly searchable) (the cluster is provisioned with headroom for an approximately 200 GB/day peak, which is the basis for the node sizing that follows). Rakbank evaluated two topologies:

Option 1 — Hot + UltraWarm (recommended)

  • 3 × m8g.2xlarge hot data nodes.
  • 3 × ultrawarm1.medium.search + cold tier.
  • 3 × m8g.large dedicated cluster-manager nodes.
  • Approximately 55 percent savings compared to all-hot.

Option 2 — All Hot

  • 3 × r8g.4xlarge, approximately 8,320 GB each.
  • 3 × m8g.large admin, no warm tier.
  • Higher cost, all data resident hot.

Pricing is On-Demand. Reserved Instances reduce it further. The takeaway: for a 9 TB, 60-day window, the bulk of data is rarely queried after the first couple of weeks. Pushing older indices to an S3-backed warm/cold tier removes the need to keep the full working set on hot r8g nodes, which is where the approximately 55 percent delta comes from.

Scaling the observability architecture with OpenSearch Service

As the platform grew from approximately 5 GB/day to approximately 150 GB/day with 25 dashboards and approximately 25 concurrent users, the observability architecture had to meet three requirements:

Predictable cost at high ingestion volume, repeated dashboard queries without per-query cost coupling, and multi-tier retention spanning real-time access through to 7-year archival. OpenSearch Service meets these requirements with an instance-based model and hot/warm/cold tiering: ingestion and queries run on provisioned capacity, and older indices age into S3-backed tiers for long-term retention at a low cost per GB. This gives Rakbank a predictable, capacity-based cost model as data volume and dashboard usage grow.

Resilience: Multi-AZ and the Standby trade-off

Deployment option SLA Failover Nodes
Multi-AZ (no Standby) 99.9% out-of-the-box automatic 3 AZ · 3 data nodes + 3 dedicated cluster-manager nodes
Multi-AZ with Standby 99.99% < 1 min automatic on AZ failure 3 AZ · 2 data active + 1 standby

The trade-off to understand: with Multi-AZ with Standby enabled, only two of three data nodes serve search requests. The third is reserved for failover. That is a 33 percent reduction in active search capacity in exchange for the higher service level agreement (SLA). Standby also requires at least two replicas per index, which increases storage, and is supported only on specific instance families, so check the current list before planning it. If a 99.99 percent SLA is not a hard requirement, running without Standby keeps all data nodes serving search. Rakbank runs its production domain without Standby, with data nodes across all three Availability Zones and replica shards for redundancy.

AI-powered observability capabilities

Rakbank is evaluating newer, machine learning (ML) and agent-driven features of OpenSearch Service that can layer on top of the tiered store:

  • AI Assistant – Natural-language → query generation (for example, “Show error spikes in the last 24h”), backed by Amazon Bedrock.
  • MCP Server + Agent investigator – DevOps agents autonomously execute PPL queries for root-cause analysis. A Memory Store provides persistent context across agent conversations.
  • Direct Query – Query Amazon S3 data without ingesting it into OpenSearch Service, an option alongside Amazon Athena for the S3 archive.
  • Trace Correlation – Available as trace collection is added to the pipeline: unify logs, traces, and metrics in one view, with automatic trace/log correlation and service maps.
  • Query surface – PPL, DSL, SQL, PromQL. Integrates with Amazon Managed Service for Prometheus and Amazon OpenSearch Ingestion for high-performance ingest.

Outcomes

Running on the Fluent Bit standard, the platform now serves three audiences from a single pane of glass. Support operations get faster triage and guided troubleshooting, engineering teams use it for root-cause analysis and debugging across the request path, and the business gains journey trends and actionable insights.

Net results: lower mean time to resolution (MTTR), higher reliability, data-driven insights, and improved operational efficiency. In their own environment, Rakbank measured faster performance after upgrading across OpenSearch Service versions (1.3 → current), with single-digit-millisecond latencies for lexical and vector queries.

Engineering lessons learned

  1. Multi-tier from day one – Design hot/warm/cold up front. Retrofitting tiering onto a live 150 GB/day cluster is significantly harder than starting with ISM policies in place.
  2. Size for peak, not today – Ingestion grows as more microservices come online. Provision headroom in the hot tier and shard count.
  3. Model the Standby trade-off explicitly – 99.99 percent costs you 33 percent of active search capacity and requires two replicas per index. Decide per workload whether that SLA is worth it.
  4. Exploit the append-only advantage – Append-only logs are the recommended candidate for multi-tier storage: no update overhead, clean force-merge before warm migration, and predictable rollover.


About the authors

Georges Hamieh

Georges Hamieh

Georges is a Senior Technical Account Manager at AWS. He supports FSI customers across the Middle East and North Africa in building scalable and intelligent cloud solutions.

Tapas Kumar Mondal

Tapas Kumar Mondal

Tapas is the Executive Vice President & Chief Technology Officer in Digital & AI at Rakbank. He heads Rakbank architecture, design, and technology strategy, and is the CTO for digital channels and AI platforms.

Amit Pareek

Amit Pareek

Amit is a Senior Vice President and Enterprise architect in Archtecture, Design & Strategy at Rakbank. He leads the solution architecture practice at Rakbank.

Chandramouli Pitchaiyappan

Chandramouli is a Cloud Solution Architect – Architecture, Design and Strategy at Rakbank. He designs and runs Rakbank’s AWS platforms, focusing on Amazon EKS, observability at scale and cloud cost optimization.

Migrate Apache Solr to Amazon OpenSearch Service with the AI-driven Migration Assistant

Post Syndicated from Michael Torio original https://aws.amazon.com/blogs/big-data/migrate-apache-solr-to-amazon-opensearch-service-with-the-ai-driven-migration-assistant/

If you have run Apache Solr for years, you can offload its undifferentiated operational overhead: managing ZooKeeper quorums, patching JVMs, tuning garbage collection, and building custom plugins for features a managed service provides out of the box. Moving to a managed service with native AWS integrations and capabilities like vector search is attractive, but the migration itself is what keeps you on aging infrastructure. Schemas differ between Solr and OpenSearch. Application code is written against the Solr HTTP API, custom analyzers are baked in, and the project balloons into months of engineering work.

A 2024 AWS Big Data Blog post on migrating from Apache Solr to OpenSearch laid out the conceptual differences between the two engines and what to think about at a planning level. However, it left the execution to the reader. In this post, you execute a Solr-to-OpenSearch Serverless migration end to end using the Migration Assistant for Amazon OpenSearch Service from the AWS Solutions Library that runs on Amazon Elastic Kubernetes Service (Amazon EKS). It orchestrates the migration. The Migration Assistant Command Line Interface (CLI) includes a built-in interactive mode that guides you through the assessment and execution in plain language. If you’re only assessing a migration, you can run the AI advisor standalone from your development environment without provisioning infrastructure.

This walkthrough uses Apache Solr 9.6 as the source with a demo catalog of 600,000 synthetic product documents. The same flow applies if you are running Elasticsearch 5.x or later, or a self-managed OpenSearch cluster as your source.

Note: The prompts and responses shown in this post are directional. Because interactive mode uses natural language, your exact prompts and responses might vary by Migration Assistant version and your environment.

By the end of this post, you will have migrated a 600,000-document Apache Solr catalog to Amazon OpenSearch Serverless using the AI-driven agent mode in the Migration Assistant for Amazon OpenSearch Service, from assessment through validated backfill. On the target, you no longer maintain ZooKeeper quorums, JVMs, or custom plugins.

Solution overview

The Migration Assistant for Amazon OpenSearch Service guides you through the various phases of the migration, including deploying the necessary infrastructure components, such as an Amazon EKS cluster. The Migration Assistant guides you through three phases:

  • Assess – Inventory the source schema and query patterns. Check permissions and accessibility. Surface incompatibilities before any data moves.
  • Backfill – Snapshot the source into Amazon Simple Storage Service (Amazon S3), then stream the snapshot into the target using Reindex-from-Snapshot (RFS).
  • Validate – Compare document counts, mappings, sample query results, and replay consistency between source and target.
Migration Assistant architecture on Amazon EKS with RFS workers for backfill and capture proxies for live traffic

Figure 1: Migration Assistant architecture on Amazon EKS, showing the RFS workers for backfill and the capture proxies for live traffic

Prerequisites

Before starting, verify that you have the following:

  • A compatible coding assistant installed and configured. Agent Mode runs inside supported development environments.
  • AWS credentials configured for the target account (AWS IAM Identity Center, temporary credentials, or an AWS Identity and Access Management (IAM) role with sufficient permissions).
  • Account isolation – Use a dedicated non-production account for this walkthrough, or assume a scoped deployment role with short-lived credentials from AWS IAM Identity Center. Point the Migration Assistant at a non-production Solr, Elasticsearch, or OpenSearch source.
  • Deployment permissions – The deployment creates a VPC, a NAT gateway, an Amazon EKS cluster, IAM roles, an Amazon Elastic Container Registry (Amazon ECR) repository, and an Amazon S3 bucket through AWS CloudFormation, so the deploying principal needs permissions to create those resources and to pass roles (iam:PassRole). See the Migration Assistant required-permissions guidance for the exact policy.
  • Workflow pod scope – The migration workflow pods use Amazon EKS Pod Identity to assume a role limited to the snapshot and capture Amazon S3 bucket and the target OpenSearch Serverless collection, rather than broad account access.
  • AWS Command Line Interface (AWS CLI) v2 (latest 2.x release recommended) installed and configured.
    • Verify installation: aws --version.
  • kubectl and Helm installed (the agent uses kubectl to interact with the Amazon EKS-based Migration Assistant infrastructure, and the deployment installs the Migration Assistant as a Helm chart).
    • Confirm both are on your PATH: kubectl version --client && helm version.
  • Network access from your workstation to AWS APIs and, optionally, to the source cluster for assessment.
  • Source cluster details – Endpoint, version, and authentication method for your Solr, Elasticsearch, or OpenSearch cluster.

The tool will prompt you if any of the above aren’t configured.

Install the Migration Assistant CLI

Run the following command in your terminal:

curl -fsSL https://solutions-reference.s3.us-east-1.amazonaws.com/migration-assistant-for-amazon-opensearch-service/3.98.7/install.sh | bash

The install script comes from the official AWS Solutions release channel, the solutions-reference Amazon S3 bucket, and is published by the AWS Solutions release pipeline. For transparency, you can review the source for Migration Assistant for Amazon OpenSearch Service in the aws-solutions/migration-assistant-for-amazon-opensearch repository on GitHub. This post pins version 3.98.7 for repeatable results. Check the Migration Assistant documentation for the current release and substitute the latest version in the install URL.

The one-line command pipes a script straight into bash. The 3.98.7 script runs without sudo. It downloads a single platform binary into ~/.local/bin and runs chmod +x on it, but it doesn’t verify a checksum or signature, and checksums are not currently published for the binaries. The only protection is HTTPS from the AWS-owned Amazon S3 bucket. For a safer install, download the script first, review it, then run it:

curl -fsSL https://solutions-reference.s3.us-east-1.amazonaws.com/migration-assistant-for-amazon-opensearch-service/3.98.7/install.sh -o install.sh
less install.sh # review what the script does before running it
bash install.sh

The installer places the migration-assistant binary on your PATH and prompts you to launch the Migration Assistant by running the following:

migration-assistant

You’re given two options: Manual or Agent Mode. Choose Agent Mode for an AI-guided migration experience.

If you have more than one supported development assistant on your PATH, the CLI detects them and asks which one to use.

Select your preferred option to proceed with the migration.

The interactive mode then prompts you for what you want to accomplish. You can request:

  • An assessment – The agent connects to your source cluster (read-only), analyzes the schema, identifies compatibility gaps, and produces a migration assessment report.
  • A deployment – The agent deploys the Migration Assistant infrastructure (an AWS CloudFormation stack, Amazon EKS cluster, and Helm chart) into your AWS account.
  • A migration – The agent configures and runs the end-to-end migration workflow, including historical data backfill and optional live traffic capture and replay.

Describe your goal in plain language. For example, “Assess my Solr 9.6 cluster. I am evaluating a migration” or “Migrate my Solr 8.11 cluster to OpenSearch Serverless.”

Data handling in agent mode – Agent mode runs inside a third-party coding assistant. To reason about your migration, the agent sends context to that model, including your Solr schema and solrconfig.xml, sample queries, and your source and target endpoints. If you have data-handling rules, review what your coding assistant transmits before you use agent mode.

The agent doesn’t store your credentials and shows each command before it runs. The local ./migration-assistant-workspace/ folder holds migration state, logs, and the assessment report, so treat that folder as sensitive and protect it like other credential-adjacent artifacts.

Assessing a migration

The first step is to run a full assessment of the source cluster. In this phase, nothing changes on the source. The agent takes inventory and reports back on what is missing or incompatible. Tell Migration Assistant to perform the assessment:

“Run a migration assessment of my Solr collection. The source is Solr 9.6.1 in SolrCloud mode at https://solr.example.internal:8983/solr, collection name products, 600,000 docs.”

You provide the source location directly in the prompt. Give the agent the Solr endpoint (for SolrCloud, any node’s base URL, or your ZooKeeper connection string) along with the collection name and authentication method. If you leave out the endpoint, the agent asks for it before it connects, because the assessment phase needs to reach the source to read the schema and solrconfig.xml.

The agent connects to Solr in read-only mode, takes inventory of the collection, and prints a structured report covering:

  • Source – Endpoint, version, mode, collection size, authentication.
  • Schema/field types – Dield-type classes in use, language analyzers declared.
  • solrconfig.xml – Request handlers, search components, update processors.
  • Custom plugins – Custom Java plugins detected, with recommended OpenSearch equivalents.
  • Networking – Verifies Migration Assistant can reach the source and that the S3 snapshot repository is loaded in Solr.

The following screenshot shows the bottom of the assessment report, which details overall readiness based on what the agent found after examining source and target configurations.

Overall readiness section of the assessment report with source checks green and custom plugin remediation yellow

Figure 2: Overall readiness section of the assessment report, where source-side checks pass green and custom plugin remediation is yellow

Field types, document backfill (RFS), live replay transforms, and sample query coverage all pass green. Custom plugin remediation is listed as yellow because the assessment detected three custom Java plugins in the solrconfig.xml that don’t translate automatically and require refactoring by your team. The target-side checks show N/A because a target has not been configured yet. After you add a target endpoint, re-running the assessment populates those rows.

Deploying the Migration Assistant infrastructure

Before moving on, save the assessment report so the findings stay available as a reference during the migration. The agent stores the report in your workspace and can recall specific findings later when you configure the workflow.

A green assessment report indicates that migration is possible and does not move the data. Migration Assistant will be used to migrate the data and build necessary configurations. The Migration Assistant needs infrastructure deployed in your account before it can copy data from Solr to Amazon OpenSearch Serverless. Ask the agent to deploy that infrastructure:

“Deploy the Migration Assistant infrastructure in us-west-2”

When you start the deployment, the agent asks for a stage name. The stage is a label you choose, not a value from a fixed list. The agent uses it as the Kubernetes namespace for the pods, the Helm release name, and the suffix on the CloudFormation stack (MigrationAssistant-<stage>). Accept the default ma, or pick something more descriptive like dev, prod, or solr-migration.

Under the hood, the agent deploys a CloudFormation stack that provisions:

Total time to install the Migration Assistant is approximately 10–15 minutes. The agent monitors pod state and reports when the infrastructure is ready.

Backfilling Solr data

After addressing data-access gaps and confirming the assessment is green, you instruct the agent to run the backfill and give it the target endpoint:

“Run the backfill into my OpenSearch Serverless collection at”

You specify the target OpenSearch Serverless endpoint here, in the backfill request. If you leave it out, the agent asks for the collection endpoint and confirms the Region and SigV4 authentication before it builds the workflow. You review that configuration next.

Before starting the backfill, the agent generates a workflow configuration that captures the migration configuration in a single JSON document: source and target endpoints, authentication, snapshot location, and RFS worker settings. The agent prints the configuration for you to review and approve, so nothing runs until you confirm.

Workflow configuration JSON showing source cluster, S3 snapshot repository, target endpoint, and RFS worker settings

Figure 3: Workflow configuration JSON, part 1, showing the source cluster, S3 snapshot repository, target OpenSearch Serverless endpoint, and RFS worker settings

The JSON defines the source Solr cluster endpoint and version, the S3 bucket where the Solr snapshot is stored, and the target OpenSearch Serverless collection endpoint. Because the Migration Assistant uses Reindex-from-Snapshot, you point the s3RepoPathUri at the S3 bucket provided for storing the snapshot. The target can be either an Amazon OpenSearch Service domain or an OpenSearch Serverless collection.

This Solr cluster uses basic authentication. You can create a Kubernetes secret in the Migration Assistant namespace after deployment and reference that secret by name in the workflow configuration. You can ask the agent to create the secret, or run the command yourself:

kubectl create secret generic solr-basic-auth --namespace ma --from-literal=username='YOUR_SOLR_USERNAME' --from-literal=password='YOUR_SOLR_PASSWORD'

The preceding command passes the password with --from-literal, which leaves it in your shell history and the process list. For anything beyond a quick test, read the password without echoing it and pass it through a restricted-permission file that you delete afterward:

read -s SOLR_PASSWORD # prompt without echoing to the terminal
umask 077 # restrict permissions on files you create
printf '%s' "$SOLR_PASSWORD" > solr-password.txt
kubectl create secret generic solr-basic-auth --namespace ma \
--from-literal=username='YOUR_SOLR_USERNAME' \
--from-file=password=solr-password.txt
rm -f solr-password.txt # remove the file once the secret exists
unset SOLR_PASSWORD

As an alternative, store the Solr credential in AWS Secrets Manager and resolve it at deploy time instead of placing it in a shell command. Either approach keeps the password out of your shell history and the process list.

Use the stage name you chose during deployment as the namespace (ma is the default), and reference the secret name (solr-basic-auth) in the workflow configuration so the agent can authenticate the source.

Grant the target collection a data access policy

For an OpenSearch Serverless target, the Migration Assistant workflow pod role must be allowed to write to the target collection. Grant that access through a data access policy scoped to the target collection and index, and confirm the collection is reachable through its network policy. Scope the policy to the specific collection and index rather than *:

[
  {
    "Rules": [
      {
        "ResourceType": "index",
        "Resource": ["index/solr-migration/products"],
        "Permission": [
          "aoss:CreateIndex",
          "aoss:DescribeIndex",
          "aoss:WriteDocument",
          "aoss:ReadDocument"
        ]
      },
      {
        "ResourceType": "collection",
        "Resource": ["collection/solr-migration"],
        "Permission": ["aoss:DescribeCollectionItems"]
      }
    ],
    "Principal": [
      "arn:aws:iam::<account-id>:role/<migration-assistant-workflow-role>"
    ]
  }
]

Secure the snapshot and capture bucket

Reindex-from-Snapshot reads a Solr snapshot from Amazon S3, so the Solr nodes need write access to the snapshot bucket to create that snapshot. Attach an IAM policy scoped to only the snapshot bucket and prefix rather than a broad Amazon S3 grant:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["s3:PutObject", "s3:GetObject", "s3:ListBucket"],
      "Resource": [
        "arn:aws:s3:::migration-assistant-snapshots",
        "arn:aws:s3:::migration-assistant-snapshots/solr-migration/*"
      ]
    }
  ]
}

Turn on Amazon S3 Block Public Access for the bucket and turn on encryption at rest, either with Amazon S3 managed keys (SSE-S3) or AWS Key Management Service (AWS KMS) keys (SSE-KMS).

The same bucket also holds captured traffic tuples, which can contain real user queries and personally identifiable information (PII). Keep that data only as long as you need it for cutover validation, and delete it after cutover.

To capture live traffic updates as part of the migration, the configuration also provides a replayer. The replayer captures live traffic at the source through a proxy and mirrors it into the target. The Migration Assistant uses SolrToOpenSearchTransformProvider to read the Solr schema and config files to translate queries in real time.

Workflow configuration JSON showing the capture proxy and replayer with the SolrToOpenSearchTransformProvider

Figure 4: Workflow configuration JSON, part 2, showing the capture proxy and the replayer with the SolrToOpenSearchTransformProvider for live query translation

After you approve the workflow, the Migration Assistant control plane starts spinning up resources. Within about a minute, the migration-console pod reports that the metadata phase ran successfully and can create an index in the target collection.

If the tool can’t migrate a specific item, the tool logs the issue and continues where safe. Some issues are fatal, such as an index that already exists on the target or a field type the transformer can’t convert. These cause the phase to exit non-zero so you can fix the problem and rerun. The Migration Assistant skips already migrated items on retry.

Some categories are out of scope for the metadata phase and require separate planning: security configuration, ISM and ILM policies, ingest pipelines, Dashboards saved objects, data streams, and cluster level settings.

Metadata evaluation output showing zero issues and one products index to create on the target

Figure 5: Metadata evaluation output showing zero issues detected and one index, products, to create on the target

Open a second terminal to monitor the migration. Launch migration-assistant and select [1] Manual when asked how you want to drive the migration, which opens the migration-console. With the migration-console open, run the following command to confirm the target index was created with zero documents:

console clusters cat-indices --cluster target
cat-indices output showing the products index created with zero documents

Figure 6: cat-indices output showing the products index created with 0 documents, confirming the metadata migration succeeded

The agent confirms the mappings are correct, including the dynamic templates for Solr’s dynamic-field patterns, and asks for approval to start RFS. You approve, and RFS workers spin up on EKS. To watch documents flow into the target in real time, run a watch loop against the same cat-indices command in the migration-console:

watch -n 3 'console clusters cat-indices --cluster target'

The console command inside the migration console pod exposes utilities for driving and inspecting a migration outside the workflow CLI. In addition to clusters cat-indices, you have clusters connection-check, clusters curl, and snapshot, among others. Run console --help inside the pod to view the full list.

The document count climbs steadily as the three RFS worker pods stream the snapshot into the new index. The workflow configuration you approved earlier set three RFS worker replicas, so three pods run the backfill in parallel here. You can raise or lower that replica count to control how much the backfill parallelizes. The following screenshot shows the migration mid-flight at roughly the halfway point.

cat-indices output showing 304,441 documents migrated into the products index mid-migration

Figure 7: Mid-flight progress showing 304,441 documents migrated into the products index

After the backfill completes, you can confirm the final document count directly from OpenSearch Dashboards Dev Tools. The following query against the migrated collection returns the exact count:

OpenSearch Dashboards Dev Tools showing a document count query returning 600,000 documents

*Figure 8: OpenSearch Dashboards Dev Tools, where GET products/_count returns 600,000 documents, confirming the backfill is complete*

Validation and testing

With the backfill finished, ask the agent to run a validation check. The agent runs four checks and prints results:

Validation results showing doc count, query, mapping, and facet parity matching and end-to-end migration success

Figure 9: Validation results, where doc count, sample query, mapping, and facet parity all match, spellcheck shape differs, and the end-to-end migration succeeds

Four lines worth reading carefully:

  • Doc count parity (600k): MATCH – Solr has 600,000 documents and the OpenSearch Serverless collection has 600,000.
  • Sample query parity (9/9 result-shape tests): MATCH – The same queries that translated cleanly in the assessment returned matching results against the target.
  • Mapping spot-check (11 business fields): All correct types – The most-used product fields (title, brand, category, price, in_stock, rating, and others) ended up with the data types that their queries depend on.
  • Facet aggregation parity: MATCH with shard_size=200 – Facet results match when the shard_size parameter is set explicitly (the default produces approximate counts).

The one yellow line is Spellcheck shape: differs (known, app rewrite), which the assessment had already flagged. Application code that consumes spellcheck responses will need to be updated to handle the OpenSearch response format.

Running a query against your migrated data

Running a real query against the migrated collection confirms that translated query domain-specific language (DSL) works on the target. You don’t need to translate queries by hand.

In agent mode, give the agent your Solr query and ask for the OpenSearch equivalent, for example, “Translate my eDisMax lamp query to OpenSearch Query DSL.”

The agent returns the DSL for you to paste into OpenSearch Dashboards Dev Tools. This is interactive help for individual queries. The backfill workflow itself does not translate or replay Solr queries, so you still rewrite your application’s query layer.

To follow along, open Dev Tools and run one of the translated queries from the assessment: a multi-field text search with a field boost, a category filter, a price range, and a sort. The Solr version of that query, in its native URL form:

GET /solr/products/select?q=lamp&defType=edismax&qf=title^3 description&fq=category:electronics&fq=price:[0 TO 1000]&sort=rating desc&rows=10

The equivalent OpenSearch Query DSL:

GET products/_search
{
  "size": 10,
  "query": {
    "bool": {
      "must": [
        {
          "multi_match": {
            "query": "lamp",
            "fields": ["title^3", "description"],
            "type": "best_fields"
          }
        }
      ],
      "filter": [
        { "term": { "category": "electronics" } },
        { "range": { "price": { "gte": 0, "lte": 1000 } } }
      ]
    }
  },
  "sort": [
    { "rating": "desc" }
  ]
}

The translation is mechanical: Solr’s q=lamp becomes a multi_match clause, fq filters become bool.filter entries, and sort keeps the same shape. The following screenshot shows both queries side by side in Dev Tools, along with the OpenSearch response.

OpenSearch Dashboards Dev Tools showing the translated query and response with 2,356 matching documents

Figure 10: OpenSearch Dashboards Dev Tools showing the translated OpenSearch query and its response, returning 2,356 matching documents

The response shows 2,356 matching documents returned in 170 milliseconds, with the top hits sorted by rating, all queryable through the new OpenSearch Serverless endpoint.

Updating your application code

The Migration Assistant moves your data and schema, and it can also mirror live Solr traffic to the target during migration. The capture proxy records requests to your source, and the replayer sends them to OpenSearch using the SolrToOpenSearchTransformProvider you configured earlier. It reads your Solr schema and solrconfig.xml to translate queries in a field-type-aware way. That translation covers common Solr query and update patterns. It returns an error on features it doesn’t support rather than translating them incorrectly, so check the Migration Assistant documentation for the current list of supported behavior. This path is built for migration and cutover validation, not as a permanent production query layer. Because Solr and OpenSearch differ in query syntax, request handlers, and response shape, you still rewrite your application’s query layer for production. Two AI-driven paths are available:

AWS Transform is a collaborative IT transformation workbench that accelerates cloud migration, application modernization, and technical debt reduction. AWS Transform delivers high-quality, repeatable transformations without requiring specialized automation expertise. You can also handle the refactoring using available development tools your team uses for application development to help rewrite the relevant Solr client calls to use the OpenSearch client.

An AI coding assistant can also handle the refactoring. Any AI coding assistant that your team uses for application development can read your repository and rewrite the relevant Solr client calls to use the OpenSearch client. For better results, AWS provides integration tools that help. These tools reference AWS documentation and include Solr to Amazon OpenSearch Service capabilities that the Migration Assistant uses. This approach is less structured than AWS Transform but can be done with your existing development tools.

As you plan the query rewrite: devise a strategy for each of the following areas:

  • Query parser differences – Solr’s eDisMax qf/pf/bf/bq/mm don’t map 1:1 to OpenSearch. multi_match with type: best_fields or most_fields is the closest analogue, but boost math (bf) and phrase-field boosting (pf) require rewrites.
  • Request handler configs – Solr solrconfig.xml request handlers (with defaults, appends, invariants) become search templates or application logic on OpenSearch.
  • Response format – Solr’s response.docs compared to OpenSearch’s hits.hits.
  • Function queries and score modifications – Solr’s _val_, bf, and function query syntax must be rewritten as function_score or script_score. Semantics are close but rarely identical, and BM25 compared to Solr’s TF-IDF (or BM25 in newer Solr) produces different absolute scores.
  • Faceting – Solr facet.field, facet.range, and facet.pivot become OpenSearch aggregations.
  • Highlighting, fl field selection, and cursorMark pagination – All have OpenSearch equivalents with different names and semantics.

Bonus: Improve search relevance with Automatic Semantic Enrichment

After your data lands in an OpenSearch Serverless collection, you have access to capabilities that weren’t available on Solr such as vector based search and semantic enrichment. One option is Automatic Semantic Enrichment. Automatic Semantic Enrichment uses a pre-trained sparse encoder (opensearch-neural-sparse-v2) to expand each document with weighted co-occurring terms at indexing time. It then matches incoming queries against the expanded representation. You get relevance improvements without hosting a model or running inference at query time.

Consider a query like “durable rain jacket” against a product catalog. A keyword-only search returns documents that contain those literal words. With Automatic Semantic Enrichment activated, the same query also surfaces related items like waterproof shells, hardshells, and weatherproof coats, without anyone writing or maintaining synonym files. Automatic Semantic Enrichment is configured at index creation time and can’t be activated by changing the mapping afterward. After activation, sparse vectors are generated automatically for every ingested document. The AI assistant will help you set up a semantically enriched field as part of the migration.

Cost

The Migration Assistant infrastructure costs approximately $0.40–0.70 per hour while running. The target OpenSearch Serverless collection has a separate baseline cost. OpenSearch Serverless can scale compute to zero when idle, so you pay only for storage when the collection is not handling requests, and it provisions faster than previous generations.

Clean up

When you finish testing, remove the resources you created so you don’t keep paying for them:

  • Delete the AWS CloudFormation stack MigrationAssistant-<stage>, which removes the VPC, NAT gateway, Amazon EKS cluster, Amazon ECR repository, and IAM roles it created.
  • Empty and delete the Amazon S3 bucket that holds the snapshot and the captured traffic tuples.
  • Delete the Kubernetes secret solr-basic-auth and remove the container images from the Amazon ECR repository.
  • Remove any temporary access you granted on the Solr source, and revoke the data access policy entry you added to the target OpenSearch Serverless collection.

Conclusion

The Migration Assistant reduces the manual engineering effort required to move from Apache Solr to Amazon OpenSearch Serverless. The Migration Assistant handles orchestration and guides you through assessment, backfill, and validation, while development tools can help reduce the effort needed to rewrite application code.

Try the Migration Assistant for Amazon OpenSearch Service in your own AWS account. Point it at a non-production Solr, Elasticsearch, or self-managed OpenSearch cluster and describe your goal in language, for example, “Deploy Migration Assistant in us-west-2 so I can start testing” or “Run the historical data migration for my Elasticsearch 7.10 cluster.” Run an assessment and take a workload through backfill and validation to see how the Assistant handles the process for you. As you use the Migration Assistant on your own projects, tell us what worked and where you encountered challenges, so we can keep improving the assessment, translation, and validation experience.

 


About the authors

Michael Torio

Michael Torio

Michael is an OpenSearch Specialist Solutions Architect based in Mountain View, CA. He works with customers across every stage of their data analytics journey, helping them design, scale, and operate OpenSearch in production.

Jon Handler

Jon Handler

Jon is a Senior Principal Solutions Architect at AWS based in Palo Alto, CA. Jon works closely with OpenSearch and Amazon OpenSearch Service, providing help and guidance to a broad range of customers who have vector, search, and log analytics workloads that they want to move to the AWS Cloud. Prior to joining AWS, Jon’s career as a software developer included 4 years of coding a large-scale, ecommerce search engine. Jon holds a Bachelor’s of the Arts from the University of Pennsylvania, and a Master’s of Science and a PhD in Computer Science and Artificial Intelligence from Northwestern University.

Analyze Anthropic usage, spend, and access with AWS Glue, Amazon S3 Tables, and AWS Quick

Post Syndicated from Daniyal Alam original https://aws.amazon.com/blogs/big-data/analyze-anthropic-usage-spend-and-access-with-aws-glue-amazon-s3-tables-and-aws-quick/

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.

Solution architecture showing AWS Glue reading Anthropic data through the connector, writing Apache Iceberg tables to Amazon S3 Tables, and Amazon Athena and AWS Quick querying the results

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:

  1. You store your Anthropic API keys in AWS Secrets Manager, where the AWS Glue connection references them.
  2. 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.
  3. 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.
  4. 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.
  5. 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.

  1. Open AWS Secrets Manager.
  2. Choose Store a new secret and enter your API key.

    AWS Secrets Manager Store a new secret page with the Anthropic API key entered

    Figure 2: Storing an Anthropic API key in AWS Secrets Manager

  3. Choose Next and name your new secret.
  4. Optionally, configure automatic rotation.
  5. Afterwards, choose Next and then Store.

Create the connections

  1. On the AWS Glue console, choose Data connections, then Create connection.
  2. For Data source, choose Anthropic.

    AWS Glue Create connection page with Anthropic chosen as the data source

    Figure 3: Choosing Anthropic as the data source in AWS Glue

  3. For Authentication, choose the secret that contains your Admin API key.

    AWS Glue connection authentication step with the Admin API key secret selected

    Figure 4: Selecting the secret that holds the Admin API key

  4. Name the connection, for example anthropic-admin, and create it.
  5. 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.

AWS Glue connection detail page showing a successful Test connection result

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.

AWS Glue console previewing Anthropic entity records and schema for a connection

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.

Amazon S3 Table buckets page with Integration with AWS analytics services turned on

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:

Dataset Columns Example row
workspace_business_unit workspace_name, business_unit Customer Service, Customer Service
support_outcomes_daily outcome_date, business_unit, conversations, completed_resolutions, qa_score_pct 2026-10-30, Customer Service, 1216, 990, 96
hr_directory email, employment_status (active or departed) [email protected], departed

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:

s3://<bucket-name>/<prefix>/workspace_business_unit/workspace_business_unit.csv
s3://<bucket-name>/<prefix>/support_outcomes_daily/support_outcomes_daily.csv
s3://<bucket-name>/<prefix>/hr_directory/hr_directory.csv

The ETL job reads each folder and loads it into a table with the same name in the reference namespace.

Note: If your datasets or columns differ, update REFERENCE_DATASETS in the ETL script and the materialized view definitions to match.

Grant the AWS Glue role access

Both jobs use the IAM role for AWS Glue from the prerequisites. Make sure that the role can do the following:

  • Read the Secrets Manager secrets that store your Anthropic API keys.
  • Read the job scripts and reference data in your S3 bucket.
  • Read and write the table bucket and its tables in the AWS Glue Data Catalog, as described in Amazon S3 Tables integration with AWS analytics services.
  • 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:

View Built from Answers
weekly_spend_by_business_unit fact_cost_daily, dim_workspace, workspace_business_unit Which business units are driving AI spend?
unit_cost fact_cost_daily, dim_workspace, workspace_business_unit, support_outcomes_daily Is the spend paying off?
access_review dim_api_key, dim_user, dim_workspace, fact_usage_daily, hr_directory 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:

spark.sql.extensions=org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions --conf spark.sql.catalog.s3tables=org.apache.iceberg.spark.SparkCatalog --conf spark.sql.catalog.s3tables.type=glue --conf spark.sql.catalog.s3tables.glue.id=<account-id>:s3tablescatalog/amzn-s3-demo-table-bucket --conf spark.sql.catalog.s3tables.glue.account-id=<account-id> --conf spark.sql.catalog.s3tables.glue.region=<region> --conf spark.sql.catalog.s3tables.client.region=<region> --conf spark.sql.catalog.s3tables.warehouse=s3://amzn-s3-demo-table-bucket/warehouse/

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

  1. On the AWS Glue console, choose ETL jobs, and then choose Script editor.
  2. For Engine, choose Spark. Choose Upload script, select anthropic_usage_etl.py, and choose Create script.
  3. 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.
  4. Expand Advanced properties. Under Connections, choose the Admin connection and each workspace connection that you created in Part 1.
  5. 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
  1. Choose Save.

Create the materialized view job

  1. On the AWS Glue console, choose ETL jobs, and then choose Script editor.
  2. For Engine, choose Spark. Choose Upload script, select anthropic_usage_mvs.py, and choose Create script.
  3. 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).
  4. 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.
  5. Choose Save.

For more information about job parameters, see Using job parameters in AWS Glue jobs.

Run and schedule the pipeline

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;
Athena query results for the unit_cost view showing daily spend and cost per resolution for Customer Service

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;
Athena query results for the access_review view listing active API keys whose creators have left the company

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:

  1. In AWS Quick, open Manage account.
  2. Under Permissions, choose AWS resources.
  3. Select Amazon S3 Tables, choose Select S3 table buckets, select the amzn-s3-demo-table-bucket table bucket, and choose Finish.

    AWS Quick Manage account permissions page granting access to the Amazon S3 table bucket

    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:

  1. Choose Data, then Create dataset, and then Create data source.
  2. 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.
  3. For Namespace, choose mart. Select weekly_spend_by_business_unit and choose Select.
  4. Choose Directly query your data, and then Edit/Preview data. Check the preview and choose Save & publish.
  5. Repeat these steps for unit_cost, and select the anthropic-usage data source that you created instead of creating a new one.
AWS Quick dataset creation using the Amazon S3 Tables data source and the mart namespace views

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.
AWS Quick Generate analysis page with the weekly AI spend review prompt entered

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.

AWS Quick analysis outline proposing sheets, filter controls, and visuals before generation

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.

AWS Quick Spend sheet showing weekly AI spend by business unit with a KPI and bar charts

Figure 14: The Spend sheet showing AI spend by business unit

The Value sheet shows whether the spend is paying off.

AWS Quick Value sheet showing cost per resolution, QA score, and spend against completed resolutions for Customer Service

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.

Advanced AWS Quick dashboard comparing price per million tokens across models, prompt caching savings, and API keys to revoke

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.


About the authors

Daniyal Alam

Daniyal Alam

Daniyal is a Software Development Engineer at AWS. He is passionate about the data foundation behind generative AI, building data integration services that connect customers’ SaaS applications, databases, and data warehouses to their analytics and AI workloads on AWS. Outside of work, Daniyal enjoys cooking, driving, weightlifting, and getting outdoors to snowboard and hike.

David Zhang

David Zhang

David is a Senior Specialist Solutions Architect specializing in Data & AI at AWS. He focuses on designing and implementing open lakehouse architectures and agentic AI solutions. He is an active speaker at AWS events and contributes to technical publications and open-source initiatives. He is also the co-author of Apache Iceberg on AWS book. Outside of work, David enjoys staying active through volleyball, tennis, and basketball.

Kamen Sharlandjiev

Kamen Sharlandjiev

Kamen is a Pr. Big Data and ETL Solutions Architect, MWAA and AWS Glue ETL expert. He’s on a mission to make life easier for customers who are facing complex data integration and orchestration challenges. His secret weapon? Fully managed AWS services that can get the job done with minimal effort.

Shrey Malpani

Shrey Malpani

Shrey is a Senior Product Manager Technical at Amazon Web Services (AWS), where he works at the intersection of distributed data processing and data integration. He is focused on building and scaling data integration and data management capabilities across services like AWS Glue, Amazon EMR, and Amazon Redshift that help customers build AI-ready data platforms for their analytics and machine learning workflows.

Joju Eruppanal

Joju Eruppanal

Joju leads engineering teams at AWS, building foundational capabilities for agentic data processing. He helps customers and their agents process and work with data in the cloud. Outside of work, Joju enjoys spending time with his family.

Introducing enhanced snapshots for Amazon Managed Service for Apache Flink

Post Syndicated from Francisco Morillo original https://aws.amazon.com/blogs/big-data/introducing-enhanced-snapshots-for-amazon-managed-service-for-apache-flink/

An Apache Flink application that runs operations such as aggregations, joins, and windows builds up state as it processes events, and Amazon Managed Service for Apache Flink saves that state in snapshots. Until now, a snapshot belonged to the application that created it, so you could restore it only into that same application, in the same Region.

Today, we’re announcing general availability of enhanced snapshots. An enhanced snapshot is an AWS resource with its own Amazon Resource Name (ARN), decoupled from the application that created it. You can start a different application from it in the same account and Region. You can also export it to an Amazon Simple Storage Service (Amazon S3) bucket you own. In the other direction, you can import an Apache Flink savepoint from Amazon S3 as a new enhanced snapshot and start an application from it.

With enhanced snapshots, you can deploy updates to a stateful application without a long pause in processing, recover in a second Region, and move a self-managed Flink job to the managed service with its state. In this post, we walk through these three use cases. We then show how to turn on enhanced snapshots, start one application from another’s state, export and import snapshots, and set up permissions. For the full reference, see Enhanced snapshots in the Amazon Managed Service for Apache Flink Developer Guide.

Use cases

These three use cases all build on the same concept: making an application’s state reusable across applications.

Support blue/green deployments for stateful applications

Deploying new code to a stateful application normally means stopping it, restarting it from a snapshot, and waiting while the new version catches up. A blue/green deployment avoids a long outage and reprocessing all the data. You run the current version (blue) and the new version (green) side by side, and you keep blue running until you have checked green’s output. For a stateful application, the hard part is bootstrapping green from blue’s existing state, and that is what enhanced snapshots provide.

Take an enhanced snapshot of blue, then start green from that snapshot with the new code. Green begins with blue’s state and processes only the data written since the snapshot. When green has caught up, point downstream consumers at its output and stop blue. If green has a problem, blue is still running.

While both run, each application reads the source and writes its own output, and you pay for the compute of both. Green reprocesses the events written since the snapshot, so its output overlaps with blue’s. Downstream consumers must tolerate duplicates or deduplicate them when you cut over, because this pattern doesn’t give you exactly-once delivery across the switch. You can also use the same flow to A/B test a change against production state, or to clone a running application’s state to reproduce a bug without touching the live job.

Disaster recovery in a second Region

If a Region becomes unavailable, a standby application in another Region can take over with recent state. It doesn’t need to start empty and rebuild its state from the source. Export and import run in the Region where the snapshot lives. To recover in a second Region, export snapshots on a schedule to a bucket in the primary Region. Then replicate that bucket to the standby Region with Amazon S3 Cross-Region Replication. When you need to fail over, import the latest replicated snapshot in the standby Region and start the standby application from it. More frequent exports mean less data to process after failover and a faster recovery, at the cost of more export operations and more Amazon S3 storage and replication. Choose the export interval from your recovery time objective (RTO).

Moving a self-managed Flink job to a managed service means starting it with empty state and replaying history to rebuild it. With enhanced snapshots, the job moves together with its state. Take a savepoint of the job on your self-managed Flink cluster. Copy it to an S3 bucket in the account and Region where the new application will run. Import the savepoint as an enhanced snapshot, then start an Amazon Managed Service for Apache Flink application from it.

Import validates the savepoint before it restores, so the source objects must meet the documented requirements, including a full-object CRC-64/NVME (CRC64NVME) checksum. See the Developer Guide for the full list of import prerequisites.

The new application starts from the savepoint’s state and resumes reading the source from the savepoint’s offsets. It processes only the data written since the savepoint instead of replaying history. For the import to work, the savepoint must come from a supported Flink version and your job’s operator IDs (UIDs) must match the ones in the savepoint. Check the new application’s output before you shut down the self-managed job. An imported snapshot has no source application, so it does not appear when you list snapshots by application name. Track the snapshots you import by calling ListSnapshots with SnapshotInitiatorOperation set to ImportSnapshot when you need them for cleanup or inventory.

How it works

Because an enhanced snapshot is an AWS resource of its own, separate from the application that created it, it has its own IAM permissions, which the last step covers.

Turning on enhanced snapshots and restoring from them takes a handful of API calls and one new application setting. The following steps cover each one, from turning on the feature through the permissions you need. The examples use the AWS Command Line Interface (AWS CLI). If you receive errors when running AWS CLI commands, make sure that you’re using the most recent version of the AWS CLI. If you work with a coding agent, the Agent Skill described at the end of this post gives it the same guidance.

Turn on enhanced snapshots

Enhanced snapshots work with applications on Apache Flink 1.20 and later. For a new application, set SnapshotMode to ENHANCED_SNAPSHOTS in ApplicationSnapshotConfiguration when you create it. You can switch an existing application in place while it is running, and it keeps its state:

aws kinesisanalyticsv2 update-application \
  --application-name orders-enrichment \
  --current-application-version-id 7 \
  --application-configuration-update '{
    "ApplicationSnapshotConfigurationUpdate": {
      "SnapshotsEnabledUpdate": true,
      "SnapshotModeUpdate": "ENHANCED_SNAPSHOTS"
    }
  }'

You can undo the switch with RollbackApplication, but only before you update the application again. After that, you can’t change the mode back. Once you switch, CreateApplicationSnapshot returns an error, so move any scripts that you use to periodically take snapshots of the application to CreateSnapshot first. Take an enhanced snapshot right after you switch, because that is the application’s first snapshot that another application can start from or that you can export.

Start one application from another’s state

Create a snapshot of the running application:

aws kinesisanalyticsv2 create-snapshot \
  --application-name orders-enrichment \
  --snapshot-name orders-enrichment-2026-11-02

Snapshot creation is asynchronous. Call describe-snapshot until SnapshotStatus is READY. The response also returns the SnapshotArn. Then start the green application, created with enhanced snapshots turned on, from that ARN:

aws kinesisanalyticsv2 start-application \
  --application-name orders-enrichment-green \
  --run-configuration '{
    "ApplicationRestoreConfiguration": {
      "ApplicationRestoreType": "RESTORE_FROM_CUSTOM_SNAPSHOT",
      "SnapshotArn": "arn:aws:kinesisanalytics:us-east-1:123456789012:snapshot/orders-enrichment-2026-11-02"
    }
  }'

RESTORE_FROM_CUSTOM_SNAPSHOT already exists for application snapshots, which you select with SnapshotName. For an enhanced snapshot, you pass SnapshotArn instead. The new application restores the saved state only if its operator UIDs, state types, and maxParallelism are compatible with the job that wrote the snapshot. It must also run a compatible Flink version.

Enhanced snapshots stay until you delete them with DeleteSnapshot, including after you delete the application that created them.

Export and import

Export and import read from and write to your bucket through an IAM role that you pass in the request. The service assumes that role, so the Amazon S3 permissions belong on the role rather than on the caller. The role’s trust policy allows the kinesisanalytics.amazonaws.com service principal, scoped with aws:SourceAccount and aws:SourceArn. The bucket must be in the same account and Region as the snapshot. For the full trust and permissions policies for these roles, see Export and import permissions in the Developer Guide.

To export a snapshot:

aws kinesisanalyticsv2 export-snapshot \
  --snapshot-name orders-enrichment-2026-11-02 \
  --export-destination-configuration '{
    "DestinationType": "S3",
    "ExportRoleArn": "arn:aws:iam::123456789012:role/MsfSnapshotExportRole",
    "DestinationS3PrefixLocation": {
      "BucketARN": "arn:aws:s3:::amzn-s3-demo-bucket",
      "KeyPrefix": "flink-snapshots/"
    },
    "DestinationEncryptionConfiguration": {
      "KeyType": "CUSTOMER_MANAGED_KEY",
      "KeyId": "arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab"
    }
  }'

End KeyPrefix with a slash. Each export writes to a new folder under the prefix, and the service reports the exact location as ExportedPrefix when you describe the operation. When you import an exported snapshot, point KeyPrefix at that exact folder, not at the parent prefix. The import looks for the savepoint metadata there, and a prefix that does not contain it fails.

To import a savepoint copied from a self-managed cluster:

aws kinesisanalyticsv2 import-snapshot \
  --snapshot-name orders-enrichment-migrated \
  --import-source-configuration '{
    "SourceType": "S3",
    "ImportRoleArn": "arn:aws:iam::123456789012:role/MsfSnapshotImportRole",
    "SourceS3PrefixLocation": {
      "BucketARN": "arn:aws:s3:::amzn-s3-demo-bucket",
      "KeyPrefix": "savepoints/savepoint-1a2b3c/"
    }
  }'

To import a snapshot you exported instead, set KeyPrefix to its ExportedPrefix.

Both calls are asynchronous and return a SnapshotOperationId. Track progress with describe-snapshot-operation, which also returns error details if the operation fails:

aws kinesisanalyticsv2 describe-snapshot-operation \
  --snapshot-name orders-enrichment-migrated \
  --snapshot-operation-id <operation-id>

Export and import use AWS Key Management Service (AWS KMS) keys for both the snapshot and the S3 objects. Specify each key as a full key ARN, because key IDs and aliases are rejected. For key policies, encryption settings, and the encryption context, see Encryption for enhanced snapshots in the Developer Guide.

Set up permissions

Enhanced snapshots are their own IAM resource type, with ARNs of the form arn:aws:kinesisanalytics:region:account-id:snapshot/snapshot-name. Two of the new actions are permission-only, with no API of the same name, so you might overlook them. With kinesisanalytics:RestoreFromSnapshot on the snapshot ARN, a caller can start, update, or roll back an application from a snapshot, including a snapshot the same application created. kinesisanalytics:CreateSystemSnapshot on the application ARN covers the automatic snapshots the service takes when you stop, update, or start an application that has snapshots turned on. Keep it in the policy even if you never stop the application, because the start path checks it too.

With the following policy, a caller can run one application, snapshot it, and start from its snapshots:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "ManageApplication",
      "Effect": "Allow",
      "Action": [
        "kinesisanalytics:StartApplication",
        "kinesisanalytics:UpdateApplication",
        "kinesisanalytics:StopApplication",
        "kinesisanalytics:CreateSnapshot",
        "kinesisanalytics:CreateSystemSnapshot"
      ],
      "Resource": "arn:aws:kinesisanalytics:us-east-1:123456789012:application/orders-enrichment"
    },
    {
      "Sid": "ReadAndRestoreSnapshots",
      "Effect": "Allow",
      "Action": [
        "kinesisanalytics:DescribeSnapshot",
        "kinesisanalytics:DescribeSnapshotOperation",
        "kinesisanalytics:ListSnapshotOperations",
        "kinesisanalytics:RestoreFromSnapshot"
      ],
      "Resource": [
        "arn:aws:kinesisanalytics:us-east-1:123456789012:snapshot/orders-enrichment-*",
        "arn:aws:kinesisanalytics:us-east-1:123456789012:snapshot/SYSTEMSNAPSHOT-*-orders-enrichment-*"
      ]
    },
    {
      "Sid": "ListSnapshots",
      "Effect": "Allow",
      "Action": "kinesisanalytics:ListSnapshots",
      "Resource": "*"
    },
    {
      "Sid": "CustomerManagedKey",
      "Effect": "Allow",
      "Action": [
        "kms:DescribeKey",
        "kms:Decrypt",
        "kms:GenerateDataKey"
      ],
      "Resource": "arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab"
    }
  ]
}

The orders-enrichment-* pattern matches the snapshots you create, assuming you start their names with the application name. The SYSTEMSNAPSHOT-*–orders-enrichment-* pattern matches the system snapshots the service takes for this application. This policy scopes to a single application. A blue/green or migration setup that starts a second application needs the same StartApplication and CreateSystemSnapshot grants on that application’s ARN too. System snapshots inherit the application’s tags, and you can scope access by tags with aws:ResourceTag conditions on the snapshot actions. ListSnapshots lists across the account, so its resource is *. Leave out the KMS statement if the application uses an AWS owned key. For export and import, the caller also needs kinesisanalytics:ExportSnapshot or kinesisanalytics:ImportSnapshot on the snapshot ARN, and iam:PassRole for the role, scoped with iam:PassedToService set to kinesisanalytics.amazonaws.com.

Now available

Enhanced snapshots are available today in all AWS Regions where Amazon Managed Service for Apache Flink is available, for applications on Apache Flink 1.20 and later. For the number of export and import operations you can run at a time, see Quotas in the Developer Guide.

Enhanced snapshot storage is priced the same as application snapshots, and there is no additional charge for export or import. Amazon S3 charges for storage, requests, and replication in your own buckets. Enhanced snapshots and the system snapshots the service takes on stop, update, and start are kept until you delete them. They keep accruing storage charges after the application that created them is gone, so delete snapshots you no longer need. To learn more, visit the Amazon Managed Service for Apache Flink pricing page.

To get started, see Enhanced snapshots in the Amazon Managed Service for Apache Flink Developer Guide.

If you use a coding agent, install the developing-applications-on-managed-service-for-apache-flink Agent Skill with the AWS CLI. For setup details, see the Agent Toolkit for AWS Skill Installation Guide. For example:

aws configure agent-toolkit
aws agent-toolkit add-skill --skill-name developing-applications-on-managed-service-for-apache-flink

We also recommend that you install the AWS MCP Server in your developer tool of choice. It gives coding agents tools to search AWS documentation, blog posts, and Agent Skills at runtime. They can then work from current AWS guidance and find and install skills more easily. To install it, see Setting up the AWS MCP Server.

 


About the authors

Francisco Morillo

Francisco Morillo

Francisco is a Sr. Streaming Solutions Architect at AWS, specializing in real-time analytics architectures. With over five years in the streaming data space, Francisco has worked as a data analyst for startups and as a big data engineer for consultancies, building streaming data pipelines. He has deep expertise in Amazon Managed Streaming for Apache Kafka (Amazon MSK) and Amazon Managed Service for Apache Flink.

Mayank Juneja

Mayank Juneja

Mayank is a Senior Product Manager at AWS, leading Amazon Managed Service for Apache Flink. He lives at the intersection of real-time data streaming and AI, previously driving Flink SQL and AI inference products at Confluent. A recognized voice in the streaming community, Mayank has taken the stage at industry conferences including Kafka Summit, Current, and Flink Forward.

Upgrading and troubleshooting Amazon MWAA with AWS agent skills

Post Syndicated from Kamen Sharlandjiev original https://aws.amazon.com/blogs/big-data/upgrading-and-troubleshooting-amazon-mwaa-with-aws-agent-skills/

Amazon Managed Workflows for Apache Airflow (Amazon MWAA) is a managed service for Apache Airflow that you can use to set up and run data pipelines in the cloud at scale, without managing the underlying infrastructure. Amazon MWAA also helps simplify upgrading the Airflow version your environment runs on, with the managed offering including built-in upgrade functionality. Keeping your DAGs current is the harder part. As Airflow innovates, teams struggle to upgrade their DAGs at the same pace, and the work demands deep Airflow expertise and constant switching between tools. The result is a familiar cycle: upgrade efforts often yield broken code and bugs, and debugging them takes time to find and fix. Teams then postpone upgrades and fall further behind. The 2.x-to-3.x jump makes this especially painful, with breaking changes, a Python transition, and a required stepping-stone version.

Apache Airflow version upgrade lifecycle, moving from Airflow 2.x through the required 2.11.x stepping-stone to Airflow 3.x

Figure 1: Apache Airflow version upgrade lifecycle

Automated tools promise to speed this up. But Airflow users quickly find that standard automation approaches often aren’t trained on the latest Airflow syntax or mix concepts between Airflow versions, producing code that fails in exactly the ways you’re trying to avoid.

AWS now publishes a set of MWAA agent skills as part of the open source AWS agent toolkit: skills authored by AWS that your coding assistant uses to better plan, execute, and debug MWAA version upgrades. In this post, you’ll learn what each MWAA skill does, how to install the skills, and how to start using them with sample prompts for upgrades, troubleshooting, and authoring. By the end, you’ll have a complete picture of what the MWAA agent skills are, how to install them in your Airflow project, and how to put them to work on real upgrade and troubleshooting tasks.

What are AWS agent skills?

An agent skill is an instruction package that guides a coding assistant through a specific task. The MWAA skills follow the open Agent Skills standard, so they work across assistants that support it, including Kiro, Claude Code, Cursor, and Codex. The assistant loads a skill authored by AWS and follows its steps, which keeps it current with Airflow and MWAA behavior.

The skills run AWS Command Line Interface (AWS CLI) commands to interact with your resources. The Agent Toolkit for AWS also provides the AWS Model Context Protocol (MCP) Server, and the plugin install bundles its configuration with the skills. The skills use it to fetch current AWS documentation at runtime and to run AWS CLI commands with sandboxed execution and audit logging.

The MWAA skills

The aws-data-analytics plugin ships four Amazon MWAA skills:

  • authoring-mwaa-workflow: Authors and deploys Airflow DAGs for provisioned environments and YAML workflows for MWAA Serverless.
  • testing-mwaa-workflow: Triggers a deployed DAG or workflow, monitors it to completion, and retests after fixes. It can also call the debugging and authoring skills when a run fails.
  • debugging-mwaa-workflow: Finds the root cause of failed runs and tasks, DAGs that don’t appear, import errors, worker out-of-memory errors, and AWS Identity and Access Management (IAM) permission errors.
  • upgrading-mwaa-environments: Upgrades a provisioned environment to a newer Airflow version, including 2.x to 3.x, using a blue/green or in-place strategy. It also updates and tests your DAG code so it runs on the new version. When the source is older than 2.11.x, it plans the route through the latest 2.11.x version on 2.x, which is a bridge for an in-place upgrade to Airflow 3 for provisioned environments.

Provisioned environments use Python DAGs and MWAA Serverless uses YAML files. All four skills work with provisioned environments, and the authoring, testing, and debugging skills also work with MWAA Serverless.

Note: agents using these skills make changes, not only recommendations. Depending on the task, they can edit and deploy DAG files. Try the skills on a development environment first, keep your DAGs under version control, and verify each proposed change.

Prerequisites

  • An AWS account with an existing MWAA provisioned environment. This post starts from Airflow 2.11.x (see the following setup section).
  • An AI coding assistant that supports the Agent Skills standard (for example, Kiro or Claude Code).
  • IAM permissions for the MWAA action namespaces you use, scoped to your resources: the airflow namespace for provisioned environments and the Apache Airflow REST API, and the airflow-serverless namespace for MWAA Serverless workflows and runs.
  • Least-privilege credentials for investigation steps. Grant write access only for the confirmed change steps.

Installing the MWAA skills

The MWAA skills are part of the aws-data-analytics plugin in the Agent Toolkit for AWS. How you install them depends on your assistant. There are two common paths.

Option A: Install the plugin (Claude Code, Codex)

Install the aws-data-analytics plugin from the claude-plugins-official marketplace. First update the marketplace so the latest plugin version is available, then install it. For example, in Claude Code:

/plugin marketplace update claude-plugins-official
/plugin install aws-data-analytics@claude-plugins-official

If you install without updating the marketplace first, you may see an error such as “Plugin ‘aws-data-analytics’ not found in marketplace ‘claude-plugins-official’”. Running the preceding marketplace update command resolves it. The Anthropic plugin directory may still list an older version, so install from claude-plugins-official to get the MWAA skills. Codex and other plugin-based assistants follow the equivalent plugin install in Getting started.

Option B: AWS MCP Server, then add the skills (Kiro)

For Kiro, add the AWS MCP Server to your configuration (~/.kiro/settings/mcp.json). Copy the current configuration from the Kiro section of Getting started in the Agent Toolkit for AWS User Guide, and set AWS_REGION to the Region of your MWAA environment. Then add the skills from the repository:

npx skills add aws/agent-toolkit-for-aws/skills

Alternatively with AWS CLI, run aws configure agent-toolkit. It detects the AI coding assistants you have installed, installs default AWS skills and configures the AWS MCP Server.

After installation, the skills are selected automatically based on your prompt, so you don’t need to name a skill. For step by step setup instructions for each assistant, follow Getting started in the Agent Toolkit for AWS User Guide and Using agent skills in MWAA in the Amazon MWAA User Guide.

Sample prompts to check the setup

  • What AWS Regions are available? – A list of regions means the AWS MCP Server is connected.
  • What can MWAA Skills help me with? – This confirms your assistant can see the skills.

Setting up an example environment

To demonstrate the steps the skills take, we provide two walkthroughs with sample prompts to help you get started. Walkthrough 1 discusses the upgrade process from 2.x to 3.x and Walkthrough 2 shows how to troubleshoot a failed DAG.

Walkthrough 1: Upgrading a provisioned environment from Airflow 2.x to 3.x

Prompt the assistant in natural language, the upgrading-mwaa-environments skill then drives a structured, confirmation-gated process:

  1. Plan the version path. The skill computes an ordered list of version jumps from source to target, inserting the required 2.11.x stepping-stone and the Python-transition step when the path crosses the 2.x-to-3.x boundary.
  2. Choose a strategy. Based on whether run history and the same environment URL/ARN must be kept, the skill selects a new-environment (blue/green) upgrade, a rehearsed in-place upgrade validated on a test copy, or a direct in-place upgrade.
  3. Validate the DAGs. For 3.x moves, the skill runs Ruff scanning and deprecation-warning log scans, plus Docker validation, surfacing breaking changes.
  4. Deploy and switch over, saving a resumable plan so a multi-session upgrade can be paused and continued.

Safety is built in: the skill never creates an environment, changes an Airflow version, or modifies your current environment without per-action confirmation, and every version jump is confirmed individually.

Sample prompts that you can use

  • Upgrade <environment_name> from Airflow 2.7.2 to the latest 3.x. We don’t need the run history.
  • Upgrade <environment_name> from 2.10.3 to 2.11.x. We must keep run history and the same URL. It has a large number of DAGs.
  • Upgrade <environment_name> from 2.11.0 to 3.2.1 in place. Skip the test copy, we don’t have budget. Some DAGs import airflow.datasets and one runs ‘airflow db clean’ in a BashOperator.

Walkthrough 2: Troubleshooting a failed DAG

Upgrades surface failures, a DAG that no longer imports, or one that stops appearing in the Airflow UI. The debugging-mwaa-workflow skill walks through the common MWAA failure modes and identifies the root cause. Next, you can either manually fix the problem or ask the authoring skill to update your DAG.

Sample prompts that you can use

  • DAG <dag_name> on <environment_name> started failing this morning with ModuleNotFoundError: No module named ‘snowflake’. Nobody changed the DAG code.
  • My serverless workflow arn:aws:airflow-serverless:<region>:<accountid>:workflow/<workflowname> failed on its last run. Why?
  • Task <taskname> in DAG <dag_name> on <environment_name> fails with AccessDenied on s3://<s3_bucket>/inbound/. Fix the permissions.

Authoring and testing workflows

The MWAA skills cover both flavors of MWAA. While the upgrade skill applies to provisioned environments only, the authoring, testing, and debugging skills all work with MWAA Serverless, where you define workflows in YAML rather than Python DAGs. To show this, we use authoring-mwaa-workflow to build a YAML workflow, testing-mwaa-workflow to run it to completion, and the debugging skill if a run fails.

Sample prompts you can use

  • Write a Python DAG for my MWAA environment <environment_name> that runs an Athena query against <db>.<table>, writes results to s3://<s3bucket>/orders/, and sends an SNS alert on failure. Then deploy and test it.
  • Create an MWAA Serverless workflow that runs Glue job orders-clean, then a Python step that uses pyarrow to validate the Parquet output row count. Run it nightly. Deploy only, don’t run it yet.
  • Smoke-test DAG <dagname> on <environment_name> (Airflow 3.0.6). It was just uploaded and is still paused.
  • Run arn:aws:airflow-serverless:<region>:<accountid>:workflow/<workflow_name> and confirm it succeeds. If it fails, fix it and retry up to 5 times.

Best practices

  • Test in a development environment first. Before an in-place production upgrade, rehearse on a test copy, and prefer a new-environment (blue/green) upgrade when you don’t need to keep run history.
  • Keep the assistant in a confirm-before-act posture for any environment-changing operation, and review each version jump.
  • Use read-only credentials for investigation and troubleshooting; scope write access to the confirmed change steps, and scope IAM to the airflow / airflow-serverless namespaces you use.
  • Install the AWS MCP Server alongside the skills so the assistant fetches current AWS docs at runtime and runs CLI commands with sandboxed execution and audit logging.
  • Keep DAGs and requirements under version control so you can review and roll back any changes these skills makes.

Conclusion and next steps

The MWAA agent skills give your AI coding assistant AWS-authored procedures for the operational work that slows Airflow teams down: upgrading Airflow versions, debugging failed runs, and authoring and testing workflows. You describe the goal, and the assistant plans the work, asks before it changes your environment, and tests the result.
To get started:
  1. Install the skills from the Agent Toolkit for AWS and connect the AWS MCP Server, as described in Getting started.
  2. Try the sample prompts in this post against a development environment.
  3. For more example prompts, see Using agent skills with Amazon MWAA in the Amazon MWAA User Guide. If you’re planning a move to Airflow 3, also read Best practices for migrating from Apache Airflow 2.x to Apache Airflow 3.x on Amazon MWAA.

Cleanup

If the walkthrough created a new environment (blue/green), a rehearsal copy, or a Serverless workflow, delete those resources when you’re done to avoid ongoing charges.


About the authors

Kamen Sharlandjiev

Kamen Sharlandjiev

Kamen is Principal Big Data and ETL SA. He’s on a mission to make life easier for customers who are facing complex data integration and orchestration challenges. His secret weapon? Fully managed AWS services that can get the job done with minimal effort. Follow Kamen on LinkedIn to keep up to date with the latest MWAA and AWS Glue features and news!

Harshawardhan Kulkarni

Harshawardhan Kulkarni

Harsh is a Partner Technical Account Manager at AWS, Amazon MWAA Subject Matter Expert. Based in Dublin Ireland, he partners with Enterprise Customers across EMEA to help navigate complex workflows and orchestration challenges while ensuring best practice implementation. Outside of work, he enjoys traveling and spending time with his family.

Boyko Radulov

Boyko Radulov

Boyko is a Senior Cloud Support Engineer at Amazon Web Services (AWS), Amazon MWAA and AWS Glue Subject Matter Expert. He works closely with customers to build and optimize their workloads on AWS while reducing the overall cost. Beyond work, he is passionate about sports and travelling.

Aritra Ghosh

Aritra Ghosh

Aritra is a Senior Product Manager at Amazon Web Services (AWS), where he leads product development for Amazon Managed Workflows for Apache Airflow (Amazon MWAA) and Amazon SageMaker Unified Studio. Outside of work, Aritra enjoys playing squash and hitting the gym.

Ashish Goel

Ashish Goel

Ashish Goel is a Principal Engineer at AWS who has supported Amazon Managed Workflows for Apache Airflow (Amazon MWAA) since its inception in 2019, guiding the Amazon development teams and the Open-Source team that contributes directly to Apache Airflow. Outside of work, Ashish enjoys tennis and nature.

PHP2Shell: Using AWS Transform to move legacy PHP onto a patched runtime

Post Syndicated from Armando Barrales original https://aws.amazon.com/blogs/devops/php2shell-using-aws-transform-to-move-legacy-php-onto-a-patched-runtime/

On October 21, 2026, the PHP project fixed two critical vulnerabilities in the PHP engine, CVE-2026-109618 and CVE-2026-109619, which are known together as PHP2Shell. Both vulnerabilities have a Common Vulnerability Scoring System (CVSS) v4.0 score of 9.2 because either one can let an unauthenticated caller run code on any server that handles PHP requests. The U.S. Cybersecurity and Infrastructure Security Agency (CISA) has since added both of them to its Known Exploited Vulnerabilities catalog.

These vulnerabilities don’t affect AWS services, but they can affect workloads running on AWS that serve PHP. The potential exposure is significant because PHP remains widely used across websites, with many sites still running PHP 8.1 or older versions.

If you run PHP 8.1 or older, you cannot patch PHP2Shell in place because no PHP release fixes those branches. Moving to a supported version isn’t always straightforward either, because legacy code often breaks on newer PHP releases. As a result, upgrading the code becomes the real blocker to patching the runtime.

With AWS Transform continuous modernization, you can remove that blocker by finding legacy PHP across your repositories and upgrading to PHP 8.4 or 8.5. AWS Transform analyzes your repositories on a schedule and flags end-of-life runtimes and other technical debt before they become urgent.

In this post, you learn how to use AWS Transform to find and upgrade legacy PHP, confirm that the upgrade was validated on a patched PHP runtime, and then patch and restart the runtime to remediate the vulnerabilities.

This post focuses on moving your code onto a patched runtime. For detection and mitigation guidance, refer to the AWS WAF post and the community checklist Find It, Patch It, Watch It. Compromise assessment is out of scope, so if a system was exposed while it was unpatched, investigate it separately and rotate any credentials the application could read.

Understand the PHP2Shell vulnerabilities

Before you start the upgrade, review which PHP releases are affected and which releases contain the fix, because this determines whether you only need to patch the runtime or whether you must also upgrade your code. The GHSA-w8hw-w9fx-j79w and GHSA-6wmf-4rv5-p3rp advisories describe the two vulnerabilities, and the following table summarizes the affected and fixed releases.

PHP branch Affected First fixed
8.5 8.5.0 to 8.5.11 8.5.12
8.4 8.4.0 to 8.4.26 8.4.27
8.3 8.3.0 to 8.3.35 8.3.36
8.2 8.2.0 to 8.2.34 8.2.35
5.4 to 8.1 all No release fixes these branches. Migrate to 8.4 or 8.5

Source: AWS Security Bulletin 2026-143-AWS. The bulletin recommends that you migrate to a supported branch, and this post recommends PHP 8.4 or 8.5 based on their support dates on the PHP supported versions page. Amazon Threat Intelligence identified an exploitation attempt on October 17, 2026, four days before the fixes were released. It has reported broad exploitation attempts since then. The disclosure date isn’t necessarily the earliest date of exploitation. The report advises you to start your investigation no later than October 17, 2026.

Your next action depends on the PHP branch that you run. The following table shows what to do for each branch.

You run What to do
PHP 8.2, 8.3, 8.4, or 8.5 These versions are vulnerable until you patch to 8.2.35, 8.3.36, 8.4.27, or 8.5.12. Your code doesn’t need to change. Patch the runtime and restart all running workers.
PHP 8.1 or older No release fixes these branches. PHP published minimal source backports for 7.4 to 8.1 as a stopgap for people who build from source. First, check whether your distribution or LTS vendor ships backported fixes. Otherwise, migrate to 8.4 or 8.5. PHP 8.2 reaches end of life on December 31, 2026, and PHP 8.3 reaches end of life on December 31, 2027. Until you migrate, apply the interim controls in the bulletin and the AWS WAF post. Your code might need changes first. The rest of this post covers those changes.
PHP you cannot find Build the inventory first. Use Amazon Inspector, AWS Systems Manager Inventory, and your container registries.

For PHP 8.1 or older, upgrading the code doesn’t fix the CVEs by itself. Instead, the upgrade removes the blocker that prevents you from updating the runtime, which is an application that breaks on a supported PHP version.

Solution overview

The solution works in three steps. Continuous modernization first analyzes your repositories and returns findings. A managed transformation then upgrades the code from those findings and validates the result on a patched PHP runtime. Finally, you patch and restart the runtime itself, which is the step that remediates the CVEs. The following diagram shows the flow.

Diagram showing repositories analyzed by AWS Transform continuous modernization, findings remediated by a managed PHP upgrade transformation, the upgraded branch validated on a patched PHP release, and the runtime patched and restarted.

Figure 1: Analysis, upgrade, and patch flow with AWS Transform continuous modernization

The walkthrough covers the following steps:

  1. Analyze your repositories for end-of-life PHP.
  2. Upgrade the code from the findings.
  3. Patch and restart the runtime.

Explore the sample application

This walkthrough uses a sample application so that you can follow along. Later, you can apply the same three steps to your own code. The sample is a PHP 7.4 application that represents common pre-8.0 codebases, with five small classes and seven PHPUnit tests. It includes the three kinds of breakage that you find in real code. The following table shows these kinds of breakage.

Kind Example in the sample What PHP 8 does
Removed or stricter, fails to parse or run $text{0}, create_function(), each(), count(null) Parse error, fatal error or TypeError
Silent behavior change 0 == "abc" in Matcher::isZeroLike No error, a different result. Only a test notices
Deprecated Implicit nullable parameter, dynamic properties, "${var}" Deprecation notices on 8.2 to 8.4

Silent behavior changes are the hardest to detect. The code runs without errors, but it returns a different result.

Prerequisites

To follow this walkthrough, you need the following:

  • An AWS account and the AWS Transform CLI 3.20.0 or later (check with atx --version) in a supported AWS Region. For setup and authentication, refer to Getting started with continuous modernization.
  • AWS credentials with the AWSTransformCustomFullAccess managed policy.
  • Node.js 22 or later, Git, and jq. You also need Docker, or a patched PHP on your target branch, on the machine that runs step 2: the transformation validates its work on one of them.
  • The transformation installs nothing on the host. If the machine has no PHP and no Docker, or its only PHP is on a branch older than your target, the preflight stops the run before any migration work and names what is missing. If its only PHP is an unpatched release of your target branch and there is no Docker, it validates on that PHP instead, writes NOT a patched … interpreter and reports Success with warnings. Install Docker or a patched PHP to avoid both cases.
  • Throwaway clones of your repositories. You also need a disposable machine for step 2 because the agent runs commands there unattended. AWS/php-version-upgrade is in public early access, so test it in a non-production environment first.
  • A target branch of 8.4 or 8.5. Export it as TARGET because every command in this post uses it.

The sample application lives in the guide folder, so clone it once:

git clone https://github.com/aws-samples/aws-transform-custom-samples
export GUIDE="$PWD/aws-transform-custom-samples/community-sourced-transformations/php2shell-patch-and-verify"
export TARGET=8.5 # or 8.4; see "Check the upgraded branch before you ship"

A local continuous modernization source is a folder of Git repositories. Create that folder first. The following commands set it up with the sample application. To use your own code instead, point REPO at your own repository folder.

mkdir -p ~/repos
cp -R "$GUIDE/samples/legacy-php-app" ~/repos/
export REPO=legacy-php-app # your repository folder name under ~/repos
git -C ~/repos/$REPO init -q
git -C ~/repos/$REPO add -A
git -C ~/repos/$REPO commit -qm "baseline before the upgrade"

If you use a host PHP instead of Docker, install the patched release on Amazon Linux 2023:

sudo dnf install -y --releasever=2023.12.20261021 php$TARGET-cli php$TARGET-xml php$TARGET-mbstring composer
php -v # 8.5.12 or later (8.4.27 or later for 8.4)

Step 1: Analyze your repositories for end-of-life PHP

In this step, you connect your repositories to continuous modernization and run two analyses. You use the atx ct command group, which runs continuous modernization.

To run the analysis

Add the folder as a source and scan it. Then run the rapid and comprehensive analyses and list the open findings:

atx ct source add --name my-php --provider local --path ~/repos
atx ct discovery scan --source my-php
atx ct analysis run --type rapid-techdebt-analysis --source my-php --wait # 1 to 2 minutes
atx ct analysis run --type tech-debt-comprehensive --source my-php --wait # 5 to 10+ minutes
atx ct findings list --source my-php --status open --json

Run both analyses because they answer different questions. The rapid scan reads only composer.json and takes 1 to 2 minutes per repository, which makes it a good first sweep to find the repositories in your estate that run an end-of-life PHP version. The comprehensive analysis reads the code itself and takes 5 to 10 minutes or more, but it’s the analysis that finds the silent behavior changes.

On the sample, the rapid scan returned one high-severity finding named “PHP Version Upgrade” with AWS/php-version-upgrade as its fix. The comprehensive analysis returned between 6 and 11 findings, depending on the run, including removed constructs such as create_function() and each(), silent behavior changes, and the end-of-life php >=7.4 constraint in composer.json.

Most findings name a transformation in their fix field, although some recommend a manual change instead, and step 2 acts on the findings that name AWS/php-version-upgrade.

The analysis leaves each repository on its own branch and writes an ATXDocumentation/ folder into it. Step 2 doesn’t run on a repository with uncommitted changes. Switch back to your branch, remove that folder, and confirm that the working tree is clean before you continue:

cd ~/repos/$REPO
git checkout <your-branch> # switch back from the analysis branch
rm -rf ATXDocumentation # remove the folder the analysis wrote
git status --short # commit, stash or delete anything listed
git status --porcelain # must print nothing before you continue

Step 2: Upgrade the code from the findings

In this step, you start the upgrade from the step 1 findings by using AWS/php-version-upgrade, an AWS managed transformation that is in public early access. A continuous modernization remediation passes the findings to the transformation, so the run plans around the findings and not only around the target version.

To create a remediation from the findings

Confirm the account has version 2026-11-02 or later, then collect the IDs of open findings whose fix is AWS/php-version-upgrade and create a remediation:

atx custom def list | grep -i php # AWS/php-version-upgrade, version 2026-11-02 or later
IDS=$(atx ct findings list --source my-php --status open --fix-transform AWS/php-version-upgrade --json | jq -r '[.[].id] | join(",")')
if [ -z "$IDS" ]; then echo "No open findings name AWS/php-version-upgrade: rerun step 1"; else
atx ct remediation create --ids "$IDS" --name php-upgrade \
  --transformation-name AWS/php-version-upgrade \
  -g "{\"additionalPlanContext\":\"The target PHP version is $TARGET\"}"
fi

The -g flag is accepted only together with --transformation-name. Without both, the remediation migrates to PHP 8.5 regardless of TARGET.

The command returns when the run ends, which took about 8 minutes on the sample. The atx ct remediation status --id <id> command then shows the repository as pr_open and the findings as change_ready. Do not interrupt the run, because an interrupted run stays in the running state until you cancel it. On a local source, the job runs on your machine and trusts every tool. Use the disposable machine from the prerequisites, with Docker or a patched PHP and no production credentials.

A remediation has no cost cap and no opt-out of knowledge-item extraction. If you need either, run the transformation directly:

atx custom def exec -n AWS/php-version-upgrade -p ~/repos/$REPO -x -t -d --limit 300 \
  -g "{\"additionalPlanContext\":\"The target PHP version is $TARGET\"}"

The -d flag opts the run out of knowledge-item extraction, and the --limit flag caps the agent minutes (300 is a ceiling of $10.50, not the expected cost). On the 13-file sample the direct runs used 64 to 79 agent minutes, so budget at least 100 even for a small project and raise it for a real application. A run that reaches the cap stops with exit code 2. The CLI help says it can be resumed with a higher limit, but the resume command it prints (atx --conversation-id <id> -t --limit <n> ) has to be run attended, because it cannot be combined with -x (seen on CLI 3.21.0). Otherwise rerun on a fresh clone with a higher limit, and do not merge the branch a stopped run leaves. This direct run doesn’t read the findings.

Either way, the result is a new branch. Two of its edits follow. The first replaces a construct that PHP 8 removed:

--- a/src/Initials.php
+++ b/src/Initials.php
class Initials {
    public function first($text) {
-        return $text{0};
+        return $text[0];
    }
}

The second changes the test instead of the production code, because PHP 8 returns a different result here:

--- a/tests/MatcherTest.php
+++ b/tests/MatcherTest.php
public function testZeroLikeValues() {
    $m = new Matcher();
    $this->assertTrue($m->isZeroLike(0));
-    $this->assertTrue($m->isZeroLike('abc'));
+    $this->assertFalse($m->isZeroLike('abc'));
}

Review the full diff before you merge it. The first edit is mechanical. The second is a behavior change that the upgrade made deliberately: PHP 8 changed loose comparisons on purpose, to close a class of bug that causes authentication bypasses, so ‘abc’ == 0 is now false. Version 2026-11-02 kept the PHP 8 result in all five test runs and listed the changed assertion under Behaviour changes in its run summary. Read that item, because a caller that relied on the old result changes behavior too. If the upgrade ever keeps a pre-PHP-8 result on purpose, it records the site under Security review required. Either way, check every ==, switch statement, and non-strict in_array call that handles user input.

Check the upgraded branch before you ship

Version 2026-11-02 of the managed transformation validates the upgrade for you. Confirm three things on the branch before you ship it.

The transformation validates its own work on a patched runtime. Version 2026-11-02 selects the interpreter it validates on: a host PHP on your target branch at or above that branch’s patched release, or else the official Docker image of the patched release. It installs nothing on the host. Across five test runs on November 6, 2026, every run validated on 8.4.27 or 8.5.12, and a host PHP of 8.5.3 was rejected. After the run has finished (a direct run exits with code 0, or a remediation shows the repository as pr_open), check out the upgraded branch and find the Validated on PHP line in the commit message. Set BASE to the branch you started the run from:

git branch --show-current # must be the upgraded branch, not BASE
BASE=main
git log --format=%B "$BASE..HEAD" | grep -oE 'Validated on PHP.{0,120}|NOT a patched.{0,40}'

The output must name a patched release of your target version, for example Validated on PHP 8.4.27 (security floor 8.4.27). If it prints nothing, names an unpatched release, or prints NOT a patched …, do not ship yet: run the independent verify check in the sample folder (step 3 of its README). Empty output also happens when BASE doesn’t exist or when you are still on BASE, so treat it as not verified, never as fine. The line tells you which PHP the run tested on, not which PHP you deploy on.

The transformation also writes a constraint that excludes unpatched releases. Version 2026-11-02 wrote ^8.5.12 for target 8.5 and ~8.4.27 || ^8.5.12 for target 8.4 in all five runs, and added no config.platform.php pin. Earlier versions wrote branch-level constraints such as “>=8.5”, which still admit the vulnerable releases, so check the value if you ran an older version. Confirm that your branch uses one of these constraints. Details are in the GitHub README.

Set require.php to ^8.5.12 for target 8.5, or to ~8.4.27 || ^8.5.12 for target 8.4. If composer.json sets config.platform.php, set that value to 8.5.12 (or 8.4.27), and then run composer update --lock. Composer’s generated platform_check.php file checks only the lowest version in require.php. With ^8.5.12, the application refused to start on both 8.5.11 and 8.4.27. With ~8.4.27 || ^8.5.12 it refused to start on 8.4.26 but still started on 8.5.11. In both cases, the manifest prevents an install on older PHP, although it doesn’t replace the runtime patch.

Step 3 is required whatever the run summary says, and the run summary file might not exist at all. The constraint is enforced when Composer installs, but at run time Composer’s platform_check.php checks only the lowest bound. The 8.4 outputs of the test runs booted on PHP 8.5.11, which is vulnerable (the 8.5 outputs refused it). Only step 3 closes that gap.

Step 3: Patch and restart the runtime

The previous steps prepare your code, but this step is the one that remediates the CVEs. The following table shows the action to take for each place where PHP runs.

Where PHP runs Action
Amazon Linux 2023 Upgrade every PHP package of your branch to the release in the advisory (command that follows)
Containers Rebuild on a base image with a fixed release (for example php:8.4.27-fpm) and redeploy
AWS Elastic Beanstalk Updated PHP platform versions exist for 8.2 to 8.5. Managed platform updates apply them in the next maintenance window. Otherwise update the platform version yourself
Amazon Lightsail No in-place update: create new instances from the updated blueprint and migrate
Debian, Ubuntu, RHEL, LTS builds Use your vendor’s package. The version string might not change: trust the vendor advisory
AWS Lambda No managed PHP runtime. If the runtime is yours (a custom runtime or a container image), rebuild it with a patched release and redeploy

On Amazon Linux 2023, upgrade every installed package for your branch with a quoted wildcard such as ’php8.5*’. The advisories are ALAS2023-2026-3301 for 8.2, -3302 for 8.3, -3303 for 8.4, and -3304 for 8.5. Use the quoted wildcard because dnf upgrades only installed packages, so a bare name such as php8.4 can match nothing and leave the host unpatched.

To upgrade PHP on Amazon Linux 2023

Set your branch and advisory from the table, and upgrade:

B=8.5; A=ALAS2023-2026-3304 # 8.5 shown; set your branch and advisory. Keep this shell open: later checks reuse $A
sudo dnf upgrade -y --releasever=2023.12.20261021 "php$B*"

Set session.upload_progress.enabled=0, and keep it set after patching. A separate vulnerability, CVE-2026-115560, affects session upload progress in an uncommon configuration and was still unpatched as of October 26, 2026. Because the setting is on by default, PHP recommends that you keep it disabled until its next regular release. The following paths are for Amazon Linux, and you can find yours by running php --ini and checking “Scan for additional .ini files”. A pool setting overrides php.ini, so check the pools too:

echo 'session.upload_progress.enabled=0' | sudo tee /etc/php.d/99-php2shell.ini
grep -rn 'upload_progress' /etc/php-fpm.d/ /etc/php-fpm.conf # remove any line that turns it back on
Restart every PHP-FPM pool, every web server that loads PHP, and every queue, consumer or long-running cron PHP worker, because a package upgrade does nothing for processes already in memory. Then confirm the patch. On Amazon Linux 2023, the package changelog doesn’t list the CVE IDs, so check the advisory instead. With Apache mod_php, check the version of the package that provides the Apache module and restart httpd. If the updateinfo command prints nothing on a host you believe is patched, run it again with the
--releasever value you used for the upgrade, and rely on the rpm and php-fpm -v checks.
sudo systemctl restart php-fpm httpd # use your web server's unit (nginx, for example) instead of httpd
/usr/sbin/php-fpm -v # the binary that serves requests
dnf updateinfo list --installed | grep "$A" # the advisory for your branch is installed
rpm -qf --qf '%{NAME}-%{VERSION} installed %{INSTALLTIME:date}\n' /usr/sbin/php-fpm
ps -o lstart= -p "$(pgrep -o -f 'php-fpm: master')" # must be later than the install time from the rpm command
/usr/sbin/php-fpm -i | grep session.upload_progress.enabled # Off

We ran these steps in Amazon Linux 2023 containers that started on php8.4-fpm 8.4.26 (B=8.4) and on php8.5-fpm 8.5.11 (B=8.5). Containers have no systemd, so we restarted php-fpm by starting it again directly. The workers came back on 8.4.27 and 8.5.12, with the matching advisory installed and upload progress set to Off.

Clean up

To avoid unneeded resources and charges, remove what this walkthrough created:

# The branch that the step 1 analysis wrote into each repository
cd ~/repos/$REPO && git branch # find the analysis branch, then: git branch -D <branch>
# Container images the upgrade pulled to validate on a patched PHP
docker image ls | grep -E '^(php|composer) ' # then: docker image rm <image>

If you no longer need the my-php source in continuous modernization, remove it in this order. Deleting a finding on its own requires it to be dismissed or obsolete, so --cascade-findings is simpler, and the source cannot be removed while any repository still references it:

atx ct analysis list --json | grep my-php # note each analysis id
atx ct analysis delete --id <analysis-id> --cascade-findings
atx ct repository delete --repo "my-php::<repo>" --source my-php
atx ct source remove --name my-php

Then delete the throwaway clones. Terminate the disposable machine from step 2 because it ran an agent with -t, which trusts its tools. Keep the upgraded branch until it’s reviewed and merged.

Cost

AWS Transform bills per agent minute ($0.035 as of November 6, 2026). For current rates, refer to AWS Transform pricing.

On the 13-file sample, as measured in the project’s BENCHMARKS.md on GitHub, version 2026-11-02 used about 64–79 agent minutes ($2.24–2.76) per upgrade. That’s more than earlier versions used with a host PHP (21 to 38 agent minutes). The transformation’s own instructions say its Docker path takes about three times as long as a host PHP. A larger application costs more, so start from --limit 300 and raise it for larger code. A remediation started from findings has no cost cap. Measured results per run are in the GitHub README.

Limitations

  • This solution doesn’t patch your servers or detect a compromise. Step 3 is yours. If a system was exposed while unpatched, investigate separately and rotate credentials the application could read.
  • The upgrade doesn’t prove identical behavior. Its validation runs your tests and a lint pass on a patched PHP, so it catches what your tests cover. Review the diff, and the Behaviour changes item in the run summary or commit message. Treat a missing item as unknown, not as none, before you merge.
  • The upgrade runs an AI agent with your tools trusted. Use throwaway clones and a disposable machine, review every diff, and use the inventory step to find PHP outside your connected repositories.

Conclusion

In this post, you learned how to use AWS Transform continuous modernization to find legacy PHP across your repositories, upgrade it with a managed transformation that validates the result on a patched PHP runtime, and then patch and restart the runtime. Because the analysis keeps running on a schedule, the same setup flags the next end-of-life runtime before it becomes urgent.

Of the three steps, the runtime patch and restart is the one that remediates the CVEs. The analysis and the managed upgrade are what make that patch possible for legacy code.

To get started, clone the sample from the GitHub repo and run it end to end. Then connect your own repositories to AWS Transform continuous modernization. If you have questions about applying this pattern in your organization, contact your AWS account team.

For more information, refer to the following resources:

Related posts:


About the authors

Armando Barrales

Armando Barrales

Armando is a Senior Migration and Modernization Solutions Architect at AWS, based in Mexico. Over more than 20 years in IT, he has helped organizations across Latin America and worldwide move legacy systems to the cloud. Today he focuses on application modernization and generative AI, helping customers go from idea to working solution.

Nishant Agarwal

Nishant Agarwal

Nishant is a Principal Go-to-Market Lead for AWS Transform. He helps customers use agentic AI to modernize their applications, reduce tech debt and keep their software secure and current.

Venugopalan Vasudevan

Venugopalan Vasudevan

Venugopalan is a Principal Specialist Solutions Architect at AWS. He leads generative AI initiatives that focus on Kiro, and AWS Transform. He helps customers adopt and scale AI-powered developer and modernization solutions to accelerate innovation.

Optimizing PySpark UDFs on AWS Glue 6.0 with native Arrow UDFs

Post Syndicated from Iván Fernández Perea original https://aws.amazon.com/blogs/big-data/optimizing-pyspark-udfs-on-aws-glue-6-0-with-native-arrow-udfs/

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.

Benchmark workflow on AWS

Figure 1: Benchmark workflow running each UDF variant as an AWS Glue 6.0 job

The high-level steps are:

  1. Set up the prerequisite AWS Identity and Access Management (IAM) role and Amazon Simple Storage Service (Amazon S3) bucket.
  2. Deploy and run the AWS Glue 6.0 job, which generates the dataset and runs the variants.
  3. 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.

How each UDF crosses the JVM–Python 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.

PySpark UDF approaches across volumes

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.

Transport and computation, as a 2×2

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:

  1. 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.
  2. 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).
  3. 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.
  4. 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.
  5. 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.
  6. For iterative or data-dependent logic (the pyheavy case), 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.
  7. 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.
  8. 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.
  9. 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.

To learn more, see Optimize user-defined functions in AWS Prescriptive Guidance and the AWS Glue documentation.


About the author

Iván Fernández Perea

Iván Fernández Perea

Iván is a Senior Specialist Solutions Architect in Analytics at AWS, helping customers design data and analytics platforms. He combines a software engineering background in cloud and big data with years of experience as a lecturer in big data and cloud computing at universities and business schools in Spain.

Build a self-healing ETL pipeline with Amazon Bedrock AgentCore

Post Syndicated from Kevin Tinn original https://aws.amazon.com/blogs/big-data/build-a-self-healing-etl-pipeline-with-amazon-bedrock-agentcore/

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 S3 (including Amazon S3 Vectors), AWS Glue, Amazon Bedrock.
    • Amazon Elastic Container Registry (Amazon ECR), AWS CodeBuild, AWS Lambda.
    • 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).
  • AWS CDK CLI installed (npm install -g aws-cdk@latest) with Python 3.10+.
  • 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:

Architecture diagram showing the full end-to-end pipeline flow: data producers upload to the S3 raw zone, AWS Glue validates and transforms records, error records route to the Bedrock AgentCore multi-agent system for correction, persistence, and remediation, with SNS notifications for manual intervention

Figure 1: End-to-end architecture of the self-healing ETL pipeline

Here’s how data flows through the pipeline:

  1. 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.
  2. 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.
  3. 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.
  4. 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:

AgentCore multi-agent workflow: the orchestrator receives error records from Glue, invokes the correction agent (backed by the Knowledge Base and S3 correction files), checks the confidence threshold, then routes to the persistence agent (writing both data lake zones) and remediation agent (submitting repository pull requests), or to SNS when confidence is too low

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.

def _query_knowledge_base(error_record: dict) -> dict:
    """Query Amazon Bedrock KnowledgeBase for correction strategies."""
    query_text = (
        f"How to correct a {error_record.get('error_type')} error "
        f"in a {error_record.get('schema_type')} weather record? "
        f"Error details: {error_record.get('error_details')}"
    )
    response = bedrock_agent_runtime.retrieve(
        knowledgeBaseId=KNOWLEDGE_BASE_ID,
        retrievalQuery={"text": query_text},
        retrievalConfiguration={"vectorSearchConfiguration": {"numberOfResults": 3}},
    )

    results = response.get("retrievalResults", [])
    top_result = results[0]
    score = top_result.get("score", 0.0)
    content = top_result.get("content", {}).get("text", "")
    source = top_result.get("location", {}).get("s3Location", {}).get("uri", "unknown")
    return {"strategy": content, "score": score}

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:

Two-source correction decision flow: the correction agent queries the Knowledge Base and S3 correction files in parallel, selects the higher-confidence strategy, applies the correction if the score meets the 0.7 threshold, or returns failure triggering an SNS notification

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:

  1. Reads the source repository – Connects to the repository using credentials stored in AWS Secrets Manager.
  2. Analyzes root cause – Correlates the error type, schema type, and correction applied to identify which upstream code produced the bad data.
  3. Generates a code change – Produces recommended changes that preserve existing logic (it does not recommend disabling validation or removing functionality).
  4. 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.
def _create_mcp_client(auth_token: str):
    return MCPClient(
        lambda: streamable_http_client(
            GIT_MCP_URL,
            http_client=create_mcp_http_client(headers=headers),
        ),
        startup_timeout=GIT_MCP_TIMEOUT,
    )

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

git clone https://github.com/aws-samples/sample-self-healing-etl-pipeline.git
cd sample-self-healing-etl-pipeline

python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

Step 2: Bootstrap CDK and deploy infrastructure

Deploy all stacks with a single command. CDK handles dependency ordering, container image builds, knowledge base creation, and runtime provisioning automatically:

# Bootstrap CDK (first time only)
cdk bootstrap aws://$(aws sts get-caller-identity --query Account --output text)/us-east-1

# Deploy all stacks
cdk deploy --all \
  --require-approval broadening \
  -c aws_region=us-east-1 \
  -c aws_account=$(aws sts get-caller-identity --query Account --output text) \
  -c [email protected] \
  -c git_repo_url=https://github.com/aws-samples/sample-self-healing-etl-pipeline

CDK deploys the following stacks in dependency order:

Stack Resources
WeatherDataLakeStack S3 output bucket (transformed + corrected zones)
WeatherIngestionStack S3 raw landing bucket
WeatherGlueStack Crawler, Data Catalog, ETL job, automatic script upload
WeatherKnowledgeBaseStack S3 Vector bucket + index, Amazon Bedrock Knowledge Base + Data Source, automatic document upload + ingestion, agent vector buckets with generated lookup files
WeatherAgentCoreStack ECR repos, IAM roles, SNS topic, Secrets Manager, CodeBuild projects with automatic ARM64 image builds
WeatherAgentCoreRuntimeStack Four AgentCore Runtime resources

To pass repository credentials for the optional remediation step:

./scripts/set_git_token.sh --token <your_github_token>

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:

{
  "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"
  }
}

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:

$ aws s3 ls s3://$OUTPUT_BUCKET/corrected/ --recursive

2026-08-04 11:51:12  720  corrected/precipitation_measurement/2026-08-04/0bde2ae3-....json
2026-08-04 11:56:28  758  corrected/pressure_observation/2026-08-04/ce2ea549-....json
2026-08-04 12:01:44  783  corrected/temperature_observation/2026-08-04/24050a62-....json
2026-08-04 12:06:59  716  corrected/wind_observation/2026-08-04/d894ac43-....json

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:

End-to-end trace of a single error record: validation failure in Glue, routing to the orchestrator, two-source correction with confidence scores, persistence to both data lake zones, and a repository pull request for the root cause fix

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:

  1. WeatherAgentCoreRuntimeStack.
  2. WeatherAgentCoreStack.
  3. WeatherKnowledgeBaseStack.
  4. WeatherGlueStack.
  5. WeatherIngestionStack.
  6. 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.


About the authors

Kevin Tinn

Kevin Tinn

Kevin is a Senior Application Modernization Delivery Consultant at AWS Professional Services. He helps enterprise customers migrate and modernize their applications on AWS, with a focus on event-driven architecture and data processing. With over 20 years in the industry, his background spans software engineering, consulting, and team transformation.

Utsab Roy

Utsab Roy

Utsab is a Senior Delivery Consultant at AWS Professional Services. He helps enterprise customers design, build, and modernize cloud-native applications on AWS, with a focus on containers, DevOps, and application security. With over 15 years in the industry, his background spans software engineering and cloud architecture.

Choose the right streaming ingestion path for Apache Iceberg tables on AWS

Post Syndicated from Mazrim Mehrtens original https://aws.amazon.com/blogs/big-data/choose-the-right-streaming-ingestion-path-for-apache-iceberg-tables-on-aws/

Choosing the streaming ingestion path to write to Apache Iceberg tables is a key step in building low-latency, high value data lakes. Organizations are building AI agents, operational dashboards, and powering analytics that demand real-time data to create actionable insights. Apache Iceberg lets these workloads share a single table format, but reducing ingestion latency depends on choosing the right streaming path into those tables.

Choosing that path is a trade-off between operational and technical requirements. Operationally, it determines how much infrastructure you manage, whether you write configuration or application code, how fresh your data can be, and how portable your solution is. Technically, it determines whether you can apply row-level updates and deletes, who runs compaction, how your pipeline handles schema changes from upstream producers, and what you pay per GB ingested. These decisions are expensive to reverse because they live in your pipeline code, IAM model, and operational runbooks, not in the table itself.

In this post, we compare five AWS ingestion paths that write to Iceberg tables: streaming tables for Apache Iceberg (native delivery from Amazon Managed Streaming for Apache Kafka (Amazon MSK) and Amazon Kinesis Data Streams), Amazon MSK Connect with the Apache Iceberg sink connector, Amazon Data Firehose, Amazon Managed Service for Apache Flink, and Apache Spark Structured Streaming on Amazon EMR. We evaluate each against eight technical criteria, call out production caveats, and close with a decision framework you can apply to your own workload.

This is a live blog post, and we will evolve it as new features are released in this space to simplify and evolve Iceberg integration for real-time analytics use cases.

Operational considerations for evaluating an Iceberg sink

When you design a real-time analytics solution on Apache Iceberg, a handful of questions shape which approach fits your workload best. Before diving into the eight technical criteria that shape your decision, it is important to consider the non-technical considerations for choosing an ingestion path. These operational considerations inform the path that you need for your specific team and organizational goals:

  • Do you want a fully managed solution? If so, streaming tables for Apache Iceberg and Amazon Data Firehose are your best options.
  • Do you prefer to manage configurations, or write applications? If you prefer configurations, streaming tables, Amazon Data Firehose, and MSK Connect are the best options. If you prefer writing applications, Managed Service for Apache Flink and Apache Spark Structured Streaming on Amazon EMR are the best.
  • Do you require sub-minute data freshness? If so, Managed Service for Apache Flink and Apache Spark Structured Streaming on Amazon EMR are the only options that can support sub-minute data freshness, while also managing the data compaction needed for most sub-minute workloads.
  • Do you require a portable, open source solution? If so, MSK Connect, Managed Service for Apache Flink, and Apache Spark Structured Streaming on Amazon EMR are the best options.

Eight technical criteria for evaluating an Iceberg sink

After you decide your operational considerations, your technical requirements inform what path is supported for your needs. These considerations are subject to change over time as each solution releases new versions and features to support more Iceberg workloads. However, because they drive what is possible for each path, they must factor into your decision with your operational goals. These technical considerations will be the focus of this post, as they are the primary factors which drive which solution is feasible for your workload, in addition to the operational considerations in the previous section.

Criteria Description
Upsert behavior Is your workload append-only, or do you need row-level UPDATE and DELETE? A change data capture (CDC) workload usually wants the Iceberg table to mirror the current state of the source. When a record changes in the database, it should change in the table. A logging or IoT workload is the opposite: every event is appended as it arrives, and past events are never modified.
Table maintenance How do you want to handle Iceberg table maintenance? Amazon S3 Tables, a capability of Amazon Simple Storage Service (Amazon S3), compacts files, expires snapshots, and removes orphan files for you automatically. Or, you can run maintenance yourself to run more frequently, as part of the sink pipeline itself.
Schema evolution What should happen to your Iceberg table when a producer adds, renames, drops, or retypes a field?
Message serialization Which input formats do you use: JSON, Avro, Protobuf? Do you use a schema registry, and if so, which one?
Source and destination support Which stream sources are you working with: Amazon MSK, Kinesis Data Streams, or direct API calls to Amazon Data Firehose? And where do you need the data to land: in fully managed Amazon S3 Tables, where AWS handles compaction and maintenance, or in self-managed Iceberg tables in your own S3 bucket, catalogued through the AWS Glue Data Catalog?
Scalability and performance How does the writer scale as throughput grows, and how much tuning does that scaling require?
Fan-out to multiple tables Does each source stream or topic map to a single Iceberg table, or do you need to route records into several destination tables based on their content?
Data transformation and analytics Do you need to filter, enrich, aggregate, or reshape records in flight? If so, what kind of processing?

After you know your requirements for these eight criteria, you can decide on the best solution for writing your real-time data to Iceberg tables.

Reference architecture

The following reference architecture outlines the high-level solution for writing real-time data to Iceberg tables based on your requirements. The differentiating features we will discuss in this post are the Stream Processor, which takes your data from Stream Storage (Amazon MSK or Amazon Kinesis Data Streams), and writes the data to your stream sink (Apache Iceberg tables).

Five-stage streaming ingestion flow from stream sources through storage and processing to Iceberg tables and analytics

Figure 1: Five-stage streaming ingestion pattern for Apache Iceberg on AWS

The architecture works as follows:

  1. Stream sources: Applications built with the AWS SDKs and libraries, log files, IoT events, change data capture (CDC) from a database, and event-driven applications produce records.
  2. Stream storage: Producers write records to Amazon MSK or Amazon Kinesis Data Streams. Alternatively, producers can skip stream storage and send records straight to Amazon Data Firehose using Direct PUT.
  3. Stream processing: One of the five stream processing options covered in this post reads the records and writes them to Iceberg tables.
  4. Stream sink: The ingestion option writes the data to Iceberg tables in Amazon S3 Tables or in a general-purpose Amazon S3 bucket.
  5. Analytics. Users query the Iceberg tables with Amazon Athena.

Side-by-side comparison

The following matrix summarizes all five options against the eight criteria. Each solution will be discussed in-depth in the next section.

Criterion Option A:
Streaming tables
Option B:
MSK Connect Iceberg sink
Option C:
Amazon Data Firehose
Option D:
Managed Service for Apache Flink
Option E:
Apache Spark on Amazon EMR
Upsert behavior No No Full Full Partial
Iceberg table maintenance Full Partial Partial Full Partial
Schema evolution No Full Partial Full Full
Message serialization Partial Full Partial Full Full
Source support Full Partial Full Full Full
Scalability and performance Full Full Partial Full Full
Fan-out to multiple tables No Full Full Full Full
Data transformations No Partial Full Full Full

Option A: Streaming tables for Apache Iceberg

Streaming tables are a native delivery capability of Amazon MSK Express brokers and Amazon Kinesis Data Streams On-Demand mode. You select a topic or stream, point the delivery at a schema registered in AWS Glue Schema Registry and choose an S3 table bucket as the destination, and the service continuously materializes the data as a queryable Iceberg table. There are no connectors to manage, no pipeline code, and no consumer applications to deploy or scale.

The delivery pipeline reads records, buffers them to the configured data freshness interval, validates and converts each record against the registered schema, performs inline compaction into optimized Parquet files, and commits them to the table. Records that fail validation are routed to a dead-letter queue in Amazon S3. Because the destination uses S3 Tables, the managed S3 Tables maintenance jobs (compaction, snapshot expiration, and unreferenced file removal) apply to it, and you can configure record expiration on the partition column to enforce data retention automatically.

When to choose it

Choose streaming tables when you want a query-ready Iceberg table from an MSK Express topic or a Kinesis Data Streams On-Demand stream, with nothing to build or operate. There’s no connector, consumer application, or compaction job to manage, and delivery doesn’t use your stream’s read capacity. It’s a good fit for append-only workloads such as event logs, clickstream, and telemetry, and for raw landing zones that feed downstream processing.

What stands out

  • Lowest operational effort. There’s no infrastructure to operate. You enable delivery from the AWS Management Console, the Amazon MSK and Kinesis APIs, or your infrastructure-as-code templates.
  • Lower cost. Delivery costs up to 60% less than running a self-managed pipeline to achieve the same result. Because the service writes optimally sized files, downstream engines scan less data per query, which reduces query costs by up to an additional 30%. For details, see the AWS Big Data Blog: Deliver real-time data to streaming tables for Apache Iceberg with Amazon Kinesis Data Streams.
  • Fully managed maintenance. The small-file problem is handled at the source: records are compacted inline during ingestion rather than in a separate job afterward. S3 Tables then continue to optimize the table over its lifetime.
  • Built-in write coordination. Write coordination and exactly-once delivery semantics are built in, eliminating the concurrent-writer conflicts that otherwise surface as failed commits.
  • No impact on your consumers. Delivery doesn’t compete with your applications for resources. On MSK, it runs on the Express broker backend, so it uses none of your broker’s read capacity and adds no cross-Availability Zone transfer charges. On Kinesis, it doesn’t consume your stream’s read limits or enhanced fan-out (EFO).
  • Not limited to Iceberg. When Iceberg isn’t required, you can deliver to general purpose S3 buckets in the source format, which is useful for archival, backup, or machine learning (ML) training data.

Caveats to plan for

For an up-to-date list of the supported configurations for streaming tables, refer to the Key concepts and Supported configurations. At the time of writing, some caveats are:

  • Append-only, and read-only. Streaming tables are append-only, and read-only to you. All write operations from your own engines are not permitted, and individual rows cannot be deleted outside the record expiration job. If your workload needs CDC with update and delete operations, the pipeline cannot apply them, and instead will append all operations to the table.
  • No fan-out or transformation. All records in a topic land in a single table, and there is no in-flight transformation. You can deliver one topic to several tables, but only as duplicate copies rather than content-based routing.
  • Fixed partitioning and minute-level freshness. Partitioning is time-based on an hourly granularity, data freshness is configurable between 5-15 minutes, and cross-Region delivery is not supported.

Option B: Amazon MSK Connect with the Apache Iceberg sink connector

The Apache Iceberg sink connector is a Kafka Connect connector that runs on Amazon MSK Connect. You configure it rather than write code, and it can scale automatically by adding tasks as your topic partitions grow. It can create destination tables for you and can fan out records from a single topic to multiple Iceberg tables. If your team already runs Kafka Connect, it fits neatly into how you operate today.

Web application change data capture flowing through Amazon MSK Connect Iceberg sink connector into Iceberg tables

Figure 2: Web app data capture into Iceberg using Iceberg sink connector on Amazon MSK Connect

When to choose it

MSK Connect is a good fit when you’re already running Kafka Connect and want multi-table routing without writing code. It suits append-only ingestion, or raw change data capture (CDC) that you merge downstream. Choose it when you’re prepared to own compaction separately.

What stands out

  • No application code. You configure the connector rather than build and version an application.
  • Scales with the topic. Task parallelism follows topic partitions, so throughput scaling is predictable and mostly automatic.
  • Automatic table creation and schema evolution. The connector can create tables it needs and propagates schema changes from the Kafka schema into the Iceberg table.
  • Full serialization coverage. Avro, JSON, and Protobuf through the standard Kafka Connect converters, with schema registry support.
  • Fan-out supported. Records from one topic can be routed into several destination tables based on record content.

Caveats to plan for

  • Insert-only writes. The connector does not support UPDATE or DELETE. As with streaming tables, mutable CDC workloads rule this option out unless you add a downstream merge step.
  • No embedded table maintenance. There’s no built-in compaction, snapshot expiration, or orphan-file cleanup, so you orchestrate and schedule separate Spark or Flink jobs. Continuous Kafka Connect commits produce many small files, and without an aggressive compaction schedule, query performance degrades over time.
  • Limited transformations. Only Simple Message Transformations are available, with no joins, aggregations, or stateful logic at ingestion time.
  • No branch writes. You can’t write to Iceberg branches, which limits staged commits and safe promotion workflows.
  • Kafka-only, with worker overhead. Kafka sources only and you own connector plugin versions, worker scaling, and upgrades.

Option C: Amazon Data Firehose

Amazon Data Firehose is the serverless path. It supports the widest range of sources of any option: Amazon MSK, Kinesis Data Streams, and direct API PUT from applications and the AWS SDK, with no cluster or application to size. Firehose also handles row-level mutations: it routes records from a single stream into different Iceberg tables and applies inserts, updates, and deletes automatically, using JQ expressions for routing and unique keys for matching. You can enforce table-level and column-level access control through AWS Lake Formation, and you can invoke an AWS Lambda function to transform records in flight.

When to choose it

Firehose is a good fit when you want serverless simplicity with JSON producers, need modest change data capture (CDC) support without writing code, or need Direct PUT ingestion. Choose it after you’ve committed to an external compaction strategy up front, since Firehose won’t manage file layout for you.

What stands out

  • Broadest source support. Firehose reads from MSK, Kinesis Data Streams, and Direct PUT, so producers that aren’t already on a stream can write to it directly.
  • CDC without code. Firehose applies inserts, updates, and deletes automatically from routing metadata, which is uncommon for a no-code sink.
  • Multi-table routing. A single stream can feed many Iceberg tables through JQ-based routing expressions.
  • Transformation and governance hooks. Use a Lambda function to reshape records in flight, and Lake Formation for fine-grained access control on the destination tables.
  • Automatic scaling for append-only workloads. Set the AppendOnly flag to true on CreateDeliveryStream, and Firehose scales automatically to match throughput for insert-only workloads.

Caveats to plan for

  • Firehose produces small files. Firehose can’t aggregate across input shards. It doesn’t shuffle or hash-distribute records before writing, so you can’t control how records are grouped into files the way you can with Flink or Spark. The result is many small, loosely organized files, so plan a compaction strategy accordingly.
  • No built-in table maintenance or inline compaction. Firehose has no embedded compaction or snapshot management, which can lead to small files that increase cost and degrade query performance. Plan to use S3 Tables or use AWS Glue Data Catalog automatic compaction and storage optimization from day one to optimize query performance.
  • Throughput trades off against partition count. Firehose is optimized for either many partitions or very high throughput, but not both. As ingest throughput rises, the number of partitions you can actively write to decreases. Throughput is measured after any Lambda transformation, so a function that expands records can push you into a lower partition tier. For the current throughput-to-partition limits, see Considerations and limitations in the Amazon Data Firehose documentation.
  • JSON in, Parquet out. Input must be JSON and output is always Parquet. Avro or Protobuf producers need a conversion layer or a Lambda function, and each record can contain only one JSON object.
  • Strict column matching, additive-only schema evolution. Column names and types in the source must match the target table exactly. Extra fields are skipped, and mismatches send records to the S3 error bucket. Schema evolution is limited to adding columns. Renames, deletions, and type changes require manual intervention. There’s no schema registry enforcement, which raises the risk of bad data landing in your tables.
  • Update cost and single-writer guidance. Each update writes a delete file followed by a data file, which incurs Amazon S3 PUT charges and makes update-heavy workloads more expensive than they first look. Avoid pointing multiple Firehose streams at the same table: Iceberg uses optimistic concurrency control, so only one writer commits at a time. Note also that Amazon MSK Serverless isn’t supported as a source.

Amazon Managed Service for Apache Flink is a flexible and feature-rich option across all eight criteria. It reads from both Amazon MSK and Kinesis Data Streams and writes to Iceberg tables through the Flink Iceberg sink. You get the Flink programming model in SQL, Java, Python, or Scala.

The main difference is Flink’s stream-native execution model. It processes records one at a time rather than in micro-batches, and it carries first-class event-time semantics with watermarks. This matters for correctness when events arrive late or out of order: a windowed aggregation keyed on event time produces the same result no matter what order the events arrive in, which micro-batch engines can only approximate. Exactly-once delivery comes from aligning Iceberg commits with Flink checkpoints.

When to choose it

Choose Managed Service for Apache Flink when you need change data capture (CDC) with updates and deletes, event-time correctness, transformation at ingest, or fan-out to multiple tables, and you’d rather not operate separate compaction jobs. For demanding, long-lived pipelines, it’s the default choice.

What stands out

  • Full upsert support. Equality deletes and changelog streams give you genuine CDC semantics, including deletes, without a downstream merge job.
  • Embedded table maintenance. With the Iceberg 1.10 or later sink, Flink can run compaction as part of the streaming pipeline.
  • Fan-out with content-based routing. A single application can write to many Iceberg tables and route records among them based on content, using multiple sinks or a SQL statement set. For details, see the AWS Big Data Blog: Build a dynamic streaming data lake with Apache Iceberg and Apache Flink.
  • Rich in-flight transformations. Joins, windowed aggregations, enrichment from reference data, and stateful pattern detection all run in the ingestion path, so the table you land is already in the shape your consumers want.
  • Broad serialization and schema evolution. Flink supports Avro, JSON, and Protobuf with AWS Glue Schema Registry integration, and the sink evolves the table schema as the stream’s schema changes.

Caveats to plan for

  • Highest operational complexity. This is the only option that requires you to write and maintain an application. You own Flink job configuration, dependency versions, parallelism and scaling, and fine-tuning for your workload.
  • Tune the checkpoint interval. The checkpoint interval controls how often Flink commits, which in turn controls file size. Commit too frequently and you generate small files. Commit too infrequently and data freshness suffers. This is the setting that most affects downstream query performance.
  • Small files still accumulate between compaction cycles. Even with embedded maintenance, streaming workloads produce small files between cycles. Embedded compaction reduces the problem, but doesn’t eliminate it.
  • Team expertise. Teams without Flink experience should plan for ramp-up on state, watermarks, and backpressure. The Managed Service for Apache Flink Agent Skill shortens this by generating idiomatic application code.

Option E: Apache Spark Structured Streaming on Amazon EMR

Spark Structured Streaming on Amazon EMR is a natural fit if your data engineering practice is already built on Spark. It reads from both Amazon MSK and Kinesis Data Streams and writes to Iceberg tables. You get full MERGE INTO support for upserts, you can express transformations in SQL, Python, or Scala, and a single job can write to multiple tables. Because batch and streaming share the same DataFrame API, the same transformation code can serve both a nightly reprocessing job and a continuous pipeline.

When to choose it

Spark on Amazon EMR is a good choice when your team already runs Spark at scale, you need MERGE semantics, and latency in the range of minutes is acceptable. It also makes sense when you’d rather extend a platform you already operate than introduce a new runtime. One requirement to plan for: deduplicate your records before every MERGE.

What stands out

  • Full Iceberg feature access. You get MERGE INTO and the complete set of Iceberg Spark procedures, including rewrite_data_files, expire_snapshots, and remove_orphan_files.
  • Compaction in the pipeline. You can configure Spark to compact files as part of the pipeline, using fanout writes and distribution modes, which gives you more control over file layout than Firehose or MSK Connect offer.
  • Existing team skills carry over. Your skills, libraries, notebooks, and CI/CD pipelines work as-is. For many teams, this is the deciding factor.

Caveats to plan for

  • Deduplicate before every MERGE. If a source batch contains more than one row for the same key, MERGE INTO is ambiguous. Spark might apply one of the duplicate rows non-deterministically (so the same query returns different results on different runs), or it might detect the conflict and fail the batch with a “multiple matching rows” error. To avoid this, deduplicate or rank your change records before the MERGE (for example, by event timestamp within each key). This is a correctness requirement, not a performance optimization.
  • Micro-batch latency. Spark’s micro-batch model puts a latency floor in the range of tens of seconds to minutes. It also approximates the event-time semantics that Apache Flink handles natively.
  • Higher cost at comparable throughput. Cluster overhead and the micro-batch model typically make Spark more expensive than an equivalent Flink application for the same continuous workload.
  • Read parallelism matches your source partition count. Spark creates one task per source partition, one per Kinesis shard, or one per MSK topic partition. When the source has few partitions, you get few tasks, so adding executors doesn’t raise throughput, and your pipeline stalls on an under-partitioned source. When the source has many partitions, Spark caching is not automatically tuned, and significant performance degradation can occur as consumers are churned in the Spark cache. To add parallelism, add more shards or partitions, repartition early in the micro-batch, and make sure you tune the consumer cache size to your workload requirements.
  • Self-managed maintenance. In-pipeline compaction is configuration you own and tune. It isn’t a managed behavior of the sink, so you’re responsible for scheduling and maintaining it.

Conclusion

In this post, we compared five AWS paths for writing to Apache Iceberg tables: streaming tables for Apache Iceberg, Amazon MSK Connect with the Apache Iceberg sink connector, Amazon Data Firehose, Amazon Managed Service for Apache Flink, and Apache Spark on Amazon EMR. We evaluated them on two layers. The operational considerations (how much you want to run, how fresh your data must be, and how portable your pipeline needs to be) change slowly. The technical criteria (upsert behavior, table maintenance, schema evolution, serialization, source and destination support, scalability, fan-out, and transformation) change as each service releases features. Both are key aspects of how you choose your path to write real-time data to Apache Iceberg.

Start with operational considerations, because they narrow the field before you consider a single feature. If you want the lowest cost, lowest overhead solution to deliver real-time data for your use case, then we recommend streaming tables for Amazon MSK and Amazon Kinesis Data Streams. If you want to have full control over your pipeline, with a portable solution that can run anywhere, then consider Amazon Managed Service for Apache Flink or Apache Spark Structured Streaming on Amazon EMR.

Then, consider the technical specifications of your solution. For technical considerations, two questions narrow the field fast. First, what is your write pattern: append-only, or do you need row-level updates and deletes? Second, who owns compaction: the service, or your team? Answer those two and you are usually down to one or two options. Append-only workloads that want the lowest operational effort start with streaming tables. Change data capture with updates and deletes points toward Managed Service for Apache Flink.

Matching the right path to your workload gives you a low-cost, low-maintenance route from stream to queryable table, without the small files, failed commits, and unmet CDC requirements that surface later. Whether you are ingesting ecommerce clickstreams, financial transactions, or IoT device telemetry, start with those two questions, then dive into the linked solution guides for the path you choose.


About the authors

Mazrim Mehrtens

Mazrim Mehrtens

Mazrim is a Sr. Specialist Solutions Architect for messaging and streaming workloads. Mazrim works with customers to build and support systems that process and analyze terabytes of streaming data in real time, run enterprise Machine Learning pipelines, and create systems to share data across teams seamlessly with varying data toolsets and software stacks.

Ayan Majumder

Ayan Majumder

Ayan is a Specialist Solutions Architect at AWS who focuses on Data and AI. He works with customers to design, migrate, and modernize their data platforms on AWS. His expertise lies in designing robust, scalable, and efficient cloud solutions. When he’s not working, Ayan enjoys traveling, photography, and outdoor activities.

Per-customer invoice management with Amazon EventBridge Scheduler

Post Syndicated from Rana Kiziltoprak German original https://aws.amazon.com/blogs/compute/per-customer-invoice-management-with-amazon-eventbridge-scheduler/

Many software as a service (SaaS) platforms need to bill each customer on their unique billing cycle, based on the date they signed up. This creates a complex scheduling problem: an individually timed invoice generation event per customer, each followed by precisely timed payment reminders. On a large platform, that adds up to millions of events.

In this post, we show you how to use Amazon EventBridge Scheduler as the time-aware backbone of a per-customer billing system. You learn how to create recurring schedules for invoice generation, spawn one-time schedules for payment reminders, and manage the full customer billing lifecycle, all without building or operating scheduling infrastructure.

Overview

This solution uses the following AWS services:

Prerequisites

To follow along with this post, you need:

  • An AWS account.
  • The AWS Command Line Interface (AWS CLI) configured with appropriate credentials.
  • Python 3.12 or later with Boto3. Python 3.9 has reached end of support as a Lambda runtime, so use a current runtime for new functions.
  • An AWS Identity and Access Management (IAM) role with permissions to create Amazon EventBridge Scheduler schedules and invoke Lambda functions.
  • A DynamoDB table named billing-reminder-log with idempotency_key as its partition key, and time to live (TTL) enabled on the ttl attribute so that old reminder records expire on their own.
  • A verified sending identity in Amazon SES. If your account is still in the SES sandbox, request production access before you send to arbitrary customer addresses, because the sandbox only allows sending to verified addresses.
  • An SQS queue to use as the dead-letter queue for failed schedule invocations.

The problem

You run a SaaS platform. Each customer signs up on a different day, and their billing cycle starts from that signup date. Customer A signed up on March 3, so they get invoiced on the 3rd of every month. Customer B signed up on the 17th, and they get invoiced on the 17th. You have 500,000 customers, each with their own billing anchor date.

Now layer on payment reminders: 7 days before the invoice is due, 3 days before, and the day it is due. That is four scheduled actions per customer per billing cycle, which comes to millions of events every month.

How do you build this?

The traditional approach (and why it breaks)

Most teams consider one of these patterns:

  1. A cron job that scans the database every hour: Query all customers, check whether anyone is due for an invoice or a reminder, and process them. This works at small scale but becomes a bottleneck fast. The job takes longer as your customer base grows. If it crashes mid-run, you miss invoices. If it runs slowly, reminders arrive late.
  2. A queue with delayed messages: An appealing idea at first glance, but Amazon SQS caps DelaySeconds at 15 minutes (900 seconds), which rules it out for billing events scheduled days or weeks ahead.

Both approaches share the same drawback: you are building and operating scheduling infrastructure instead of focusing on your billing product.

The building block: Amazon EventBridge Scheduler

Amazon EventBridge Scheduler is purpose-built for this problem. It is a fully managed scheduling service that handles billions of one-time and recurring invocations. You create a schedule, tell it when to fire and what to invoke, and walk away. There is no infrastructure to manage, no polling, and no worker fleets.

For per-customer billing, Scheduler becomes the time-aware backbone of your invoicing system:

  • Each customer gets their own recurring schedule for invoice generation.
  • Each billing cycle spawns one-time schedules for payment reminders.
  • Scheduler handles the timing, and your application handles the business logic.

Architecture

The following diagram shows the end-to-end flow, from customer signup through invoice generation and payment reminders.

At signup, the application creates a recurring monthly schedule for the customer’s signup day. On each billing day, this schedule invokes the invoice generation Lambda function. The function sends the invoice through Amazon SES and sets up three one-time payment reminders: 7 days before the due date, 3 days before, and on the due date. Each reminder invokes the Send Payment Reminder Lambda function, which notifies the customer only if the invoice is still unpaid. When a payment arrives, a separate handler deletes any outstanding reminders so no further messages go out.

Architecture diagram showing customer signup creating a recurring invoice schedule, which invokes the invoice generation Lambda function, which creates one-time reminder schedules that invoke the payment reminder Lambda function and send email through Amazon SES.

Figure 1: Invoice generation and payment reminders with Amazon EventBridge Scheduler

Implementation

The complete implementation is available in the accompanying GitHub repository. The AWS Serverless Application Model (AWS SAM) template provisions the DynamoDB tables, SQS dead-letter queue, Amazon EventBridge Scheduler groups, AWS Key Management Service (AWS KMS) key, and AWS Lambda functions described in this section. The rest of this section walks through the design of each component.

Step 1: Create schedule groups

Before creating any schedules, make sure the schedule groups exist. The sample declares them in the AWS SAM template so they are provisioned once at stack deploy time.

Step 2: Create a recurring invoice schedule at signup

When a customer signs up, the signup handler creates a recurring schedule based on their signup date. For customers who sign up on the 29th, 30th, or 31st, the sample clamps the billing day to the last day of each month using the L cron special character, so no customer is skipped in February or in 30-day months. The handler is idempotent: if the schedule already exists (for example, after a retry), it updates the schedule instead of failing.

Step 3: Generate the invoice and schedule reminders

The invoice generation Lambda function, GenerateInvoice, does the billing work and then creates one-time schedules for the payment reminders. It includes an idempotency check to prevent duplicate invoices if Scheduler delivers the event more than once.

Step 4: Send reminders with idempotency

The reminder Lambda function, SendPaymentReminder, checks whether the invoice is still outstanding and whether this specific reminder was already sent, which prevents duplicate reminders on retry.

Step 5: Cancel reminders on payment (event-driven)

Instead of checking payment status only when a reminder fires, a payment handler cancels outstanding reminders immediately when a payment is received. Your payment processing system triggers this handler (for example, through an Amazon EventBridge event or an SQS message from your payment gateway).

Step 6: Handle customer lifecycle changes

When a customer cancels, upgrades, or changes their billing cycle, update or delete their schedule accordingly. One thing to be careful of: UpdateSchedule replaces the entire schedule configuration rather than merging changes, so any field you leave out is lost. Always read the existing schedule first, then apply your changes and write it back in full.

Why Scheduler is the right building block

The following table compares the do-it-yourself (DIY) approach with Amazon EventBridge Scheduler for each operational concern.

Concern DIY Approach With Scheduler
Per-customer timing Complex database queries to find who is due Each customer has their own schedule, so no queries are needed
Reminder precision Polling interval determines accuracy Fires at the minute you specify, within the flexible time window you configure
Scale More customers = more polling load, more workers Scheduler handles millions of schedules natively
Missed executions Crashed cron host = missed invoices Fully managed, built-in retries with a dead-letter queue
Early payment Reminders fire anyway, or you build cancellation logic into your poller Delete the schedule and it does not fire
Lifecycle changes Update database records, hope the poller picks up the change Update or delete the schedule directly
Operational overhead Manage worker fleets, monitor queue depth, handle clock skew Zero infrastructure to manage

Operational considerations

Before you run this design in production, consider the following operational factors.

Schedule groups for organization

Use schedule groups to organize and manage schedules by function:

  • billing-invoices: All recurring invoice generation schedules.
  • billing-reminders: All one-time payment reminder schedules.

With schedule groups, you can tag a set of schedules for organization and access control, list schedules by category, and delete all schedules in a group if needed (for example, during testing).

Quotas and request rates at scale

Service quotas matter once you move past a test account. One quota is the number of schedules. The default limit is 10 million schedules per account per Region, and it is adjustable through Service Quotas. The CreateSchedule and UpdateSchedule APIs also have request rate quotas, which matters if you backfill existing customers in a single migration. Spread that backfill over time if you do not need to backfill immediately.

Scheduler also throttles invocations, with a default of 500–1,000 transactions per second (TPS) depending on the Region and adjustable to tens of thousands of TPS. To deal with an invocation spike (for example, the majority of your customers having invoices due at the same time), we recommend using the Flexible Time Window feature. In this post, we use it to spread each burst over 15 minutes, which smooths the load on your downstream Lambda functions and on Amazon SES without changing what the customer sees on their invoice.

Monitoring

Monitor schedule health with Amazon CloudWatch metrics, and capture any failed invocations in a dead-letter queue.

  • CloudWatch metrics: Monitor InvocationAttemptCount, InvocationDroppedCount, InvocationThrottleCount, and TargetErrorCount per schedule group.
  • Dead-letter queue: Configure a dead-letter queue on your schedules to capture failed invocations that exhaust retries, and alarm on the InvocationsSentToDeadLetterCount metric so a failed delivery pages you instead of sitting silent in the queue.
  • Invoice audit trail: Log every invoice generation and reminder send to an Amazon DynamoDB table or Amazon CloudWatch Logs for compliance.

Retry policy

The retry policy and dead-letter queue are applied to every schedule target the sample creates. This retries transient Lambda failures up to three times over 1 hour, and permanently failed invocations land in the SQS dead-letter queue for investigation.

Cost at scale

Amazon EventBridge Scheduler pricing is based on invocations, and the AWS Free Tier covers 14 million invocations per month. The 500,000-customer example in this post generates four scheduled events per customer per month (one invoice and three reminders), which is 2 million invocations, so the scheduling layer costs nothing at that scale. Scale the same design to 10 million customers and you generate 40 million invocations per month, of which 26 million are billable at $1.00 per million, so the scheduling layer costs roughly $26 per month.

The costs that grow with this design sit in the targets rather than in the scheduling:

  • AWS Lambda charges for each invocation and its duration.
  • Amazon SES charges per email, so the three reminders per customer per cycle are the largest line item in this workload.
  • Amazon DynamoDB charges for the reminder log writes and reads, which the TTL setting keeps from accumulating.

Check the pricing page for each service for current rates in your AWS Region.

Cleanup

To avoid incurring charges, delete the resources you created. If you deployed the accompanying SAM sample, run sam delete --stack-name <stack-name>, which removes the Lambda functions, DynamoDB tables, SQS queue, KMS key, and IAM roles in one command. Before deleting the stack, delete any schedules the sample created at runtime, because schedule groups cannot be deleted while they still contain schedules. If you deployed the resources manually, delete them in this order:

  1. Delete the schedule groups. Deleting a group also deletes the schedules it contains.
  2. Delete the Lambda functions (GenerateInvoice and SendPaymentReminder).
  3. Delete the IAM roles (SchedulerInvoiceRole and SchedulerReminderRole).
  4. Delete the SQS dead-letter queue.
  5. Delete the billing-reminder-log DynamoDB table.

Conclusion

Billing is inherently time-driven. Every customer has a cycle, every invoice has a due date, and every reminder has a send time. When you build billing infrastructure, you are building scheduling infrastructure whether you set out to or not.

With Amazon EventBridge Scheduler, you can stop building scheduling infrastructure and focus on your billing logic. Each customer’s billing lifecycle becomes a set of schedules, created at signup, updated when plans change, and deleted at cancellation. The timing is managed for you, the service scales to millions of schedules per Region, and the operational burden of running the scheduler moves to AWS.

If your application has per-customer timing, Scheduler is the building block that makes it straightforward.

To deploy this solution, use the accompanying AWS SAM project on GitHub, which provisions the Lambda functions, DynamoDB tables, Amazon EventBridge Scheduler groups, and SQS dead-letter queue described in this post. For more information about the service, see the Amazon EventBridge Scheduler documentation and the Amazon EventBridge Scheduler product page. For more serverless learning resources, visit Serverless Land.


About the authors

Rana Kiziltoprak German

Rana Kiziltoprak German

Rana is a Senior Technical Account Manager at Amazon Web Services, where she supports the Enterprise Support customers to build scalable, cost-optimized, resilience and secure architectures to prepare the workloads to the production scale. She specializes on the AWS Serverless services and Event-Driven Architecture.

Oluwaseun Ademuwagun

Oluwaseun Ademuwagun

Oluwaseun is a Software Development Manager at Amazon Web Services, where he leads engineering teams responsible for event-driven and scheduled applications. Outside of work, he loves traveling, cooking, and playing football.

Tugce Konuklar Dogantekin

Tugce Konuklar Dogantekin

Tugce is a Technical Account Manager at Amazon Web Services based in Germany. She brings more than a decade of software development experience to this work, and her technical focus is serverless, AIOps and observability.

Inside an enterprise AI agent: A governed, observable loop architecture

Post Syndicated from Rushabh Lokhande original https://aws.amazon.com/blogs/architecture/inside-an-enterprise-ai-agent-a-governed-observable-loop-architecture/

An enterprise AI agent isn’t a bigger chatbot. A chatbot answers one message at a time. An agent keeps working toward a goal: it reads what the user is asking for, breaks the work into steps, pulls in the knowledge it needs, weighs the evidence, calls external tools, and checks the results before it decides whether to keep going or hand back an answer. Every one of those steps touches real systems and real data, so governance, observability, and trust controls must live at each step. Most chatbot designs don’t provide them.

This post lays out a reference architecture for that kind of agent, organized as five layers: an API gateway that handles identity and policy, a five-phase agent runtime (Understand, Plan, Retrieve, Reason, and Act and Observe), a knowledge and state tier that gives the agent memory, a platform-services layer for models and tools, and a trust and control framework that runs across all of them. Each layer maps to AWS managed services. We also cover the design patterns that work and the mistakes we have seen teams make.

The rise of enterprise AI agents

Enterprises are moving past single-turn question-and-answer interfaces for business reasons. They want to automate more of the routine work so their people can spend time elsewhere, ship products and customer experiences faster, and get more done without adding headcount. Those goals justify the investment, but reaching them requires moving from single-turn chatbots to agents that can carry out multi-step work on their own. That jump brings new problems to solve in orchestration, memory, and governance, and the rest of this section is about what those problems demand of the architecture.

From chatbots to agents

Enterprise AI is shifting from systems that answer a question and stop to agents that plan, use tools, and come back with an outcome you can verify. The difference is the loop. Rather than returning one response, an agent cycles through understanding, planning, retrieval, reasoning, and action, and it keeps cycling until it either reaches the user’s goal or decides a human needs to step in.

At AWS re:Invent 2025, Werner Vogels said that the developers who succeed think in systems and build with precision. The teams pulling ahead with agents aren’t the teams that moved first or chose the newest model. They are the ones who treat the whole thing as a system and understand that a choice made in one layer shows up in every layer around it.

What is an AI agent? An AI agent uses a foundation model (FM) as its reasoning core and adds tools, memory, and guardrails so it can take on work that takes more than one step. Where a single-turn chatbot answers and forgets, an agent holds onto state, reasons across several steps, and acts in systems outside itself.

The enterprise imperative: Governed, observable, trustworthy, cost-aware

A capable model is the more straightforward part. Running agents in an enterprise means putting governance, observability, trust controls, policy enforcement, and cost controls around every step they take. Cost matters as much as capability: many enterprises find token spend growing faster than the productivity gains it delivers, so an agent must also be designed to spend inference where it adds value. That is what this architecture is built to do:

  • Governed – Every action clears a policy gate, an approval workflow, or a guardrail before it runs.
  • Observable – Each step emits a trace (latency, tokens, tool status, and execution path) for later audit.
  • Trustworthy – Confidence scoring, evaluations, and human checkpoints sit between the agent and the user.
  • Iterative – The loop sharpens its understanding on each pass as tool results come back.

What this post covers

What follows is a reference architecture for enterprise AI agents on AWS, walked through layer by layer from the first request to the verified result, with diagrams, the AWS services that implement each piece, and the patterns worth copying and avoiding. The aim is to give architects and engineering leaders a shared vocabulary and a mental model for designing these systems.

Architecture overview: The governed agent loop

The AWS Well-Architected Framework Generative AI Lens organizes generative AI workloads around six pillars (operational excellence, security, reliability, performance efficiency, cost optimization, and sustainability), each with its own practices and controls. We split the agent into layers that line up with those pillars, so every layer owns a clear responsibility that traces back to a recognized standard instead of a one-off choice. Teams can change, secure, and scale one layer without disturbing the others while keeping the end-to-end governance the Lens requires.

Layered architecture design

The design is layered and loop-based, with five tiers that each do one job. The agent runtime sits in the middle. It’s a five-phase loop that turns a user’s goal into a verified outcome. Around it sit the layers for knowledge, platform services, trust controls, and the governance that cuts across everything.

Reference architecture diagram

Figure 1 shows the five layers together. Read it top to bottom: the API gateway takes the request and enforces identity and policy, then the flow moves down through the agent runtime, the knowledge and state tier, and the platform services, with the trust and control framework running alongside on the right.

Five-layer enterprise AI agent reference architecture: API gateway, agent runtime, knowledge and state, platform services, and a cross-cutting trust and control framework

Figure 1: Inside an enterprise AI agent, reference architecture

Design principles

Five principles shaped this design, and each one left a mark on the layers you will see later in concrete ways. Zero trust is why identity context travels through every phase of the loop. Observable by default is why there is a dedicated step-level tracing tier instead of leaning on application logs.

These principles aren’t ad-hoc. They come directly from the AWS Well-Architected Framework Generative AI Lens. The Lens’s security guidance maps closely to the following five principles. Least-privilege access across models, data stores, endpoints, and workflows is what zero trust and defense in depth rest on. Securing the data and the traffic between components is separation of concerns in practice. Watching and enforcing the boundaries between the control and data planes is observable by default doing its job. And constraining what the agent is allowed to do, through guardrails and clear limits, is where fail-safe defaults come from. Because it builds on the Lens, this design follows recognized AWS guidance rather than a single team’s convention. It also reflects what AWS Professional Services has implemented and run in production with enterprise customers across industries such as retail and technology: lessons learned in the field that we apply on every engagement, not a set of theoretical best practices. For the full security guidance, see the Generative AI Lens security pillar in the AWS Well-Architected documentation.

Principle Description
Zero trust Every request is authenticated and authorized before reaching the runtime. User identity flows through every phase.
Defense in depth Multiple layers of controls (API gateway, policy gate, trust and control, governance) facilitate no single point of failure.
Separation of concerns Each architectural layer has clear boundaries and responsibilities. Knowledge is separated from compute. Trust is separated from execution.
Observable by default Every step produces telemetry. Tracing, metrics, and logs are first-class architectural concerns, not afterthoughts.
Fail-safe defaults When uncertain, the agent defaults to the safest action: clarify with the user or escalate to a human.

Entry point: User goal and API gateway, identity and policy

Layer 1 of 5 · Entry point: API gateway, identity, and policy (see Figure 1)

Every interaction starts with a user goal: a request in plain language that kicks off the loop. Before it reaches the runtime, it goes through the API gateway and the identity and policy layer, where the zero-trust posture is enforced.

User goal

The user goal starts with a business objective that drives the top-level intent, stated in natural language. It might be as small as “What was our Q3 revenue?” or as involved as “Book a meeting with Sarah, check her calendar availability, and send a summary of our last project discussion.” The agent’s first job is to read that intent and work out the most efficient way to deliver it.

API gateway

The API gateway is the front door for every interaction. It terminates TLS, routes requests (REST, plus WebSocket for streaming responses), applies rate limits, and validates input. On AWS, this is usually Amazon API Gateway with WebSocket APIs for real-time streaming.

Identity and authentication

No request reaches the runtime unauthenticated. The identity layer checks OAuth 2.0 / OpenID Connect (OIDC) tokens, resolves who the caller is, and attaches their context (role, permissions, organization, and session ID) to the request. That context rides along through every later phase, so each tool call and data lookup stays within the caller’s permissions.

Policy enforcement

The policy layer handles role-based access control (RBAC), tool-level permissions, data scoping, and usage quotas. It decides which tools the agent might call for a given user, which data it might touch, and how many tokens it might use in a session.

Component Responsibility AWS service
API gateway TLS termination, request routing, WebSocket streaming, rate limiting Amazon API Gateway, Application Load Balancer (ALB)
Identity Token validation, OAuth 2.0/OIDC, user context injection, session management Amazon Cognito, AWS Identity and Access Management (IAM)
Policy RBAC, tool permissions, data scoping, usage quotas IAM policies, AWS Organizations

Design principle: Zero trust. The gateway authenticates and authorizes every request before it reaches the runtime. The user’s identity, role, and permissions ride on the session context and stay with the request through every phase of the loop.

The agent runtime: Five-phase cognitive loop

Layer 2 of 5 · Agent runtime: the five-phase cognitive loop (see Figure 1)

The runtime performs the core work of the agent. It runs a continuous loop of five phases that track how a careful professional handles a hard task: understand what is being asked, plan an approach, gather the information you need, reason through the choices, then act and watch what comes back before going around again. (see Figure 2)

A note on the model. We aren’t claiming a new theory of agent cognition here. These five phases combine proven ideas under one vocabulary. They draw on the sense, plan, act loop from robotics, the reasoning and acting pattern from ReAct prompting, and the self-reflection step from approaches such as Reflexion (a technique in which the model critiques its own previous attempt and uses that feedback to improve the next one). The enterprise contribution is naming the phases out loud, so you have a clear place to attach governance, observability, and trust controls at each one. If you already think in three or four steps, say plan, act, observe, these phases map directly onto that model.

The five-phase agent loop: Understand, Plan, Retrieve, Reason, and Act and Observe, cycling with feedback

Figure 2: The five-phase cognitive loop: Understand, Plan, Retrieve, Reason, Act and Observe

Passes through the loop can end in a final answer, or they can go around again with new evidence from a tool result, an error to handle, or extra context. This ability to refine its work separates an agent from a single large language model (LLM) call.

Phase 1: Understand (intent, context, and constraints)

Understand is the agent’s perception step. It reads the user’s input and pulls out three things:

  • Intent – What the user is actually trying to do. The agent classifies the request type (retrieve information, perform an action, or generate content) and identifies the domain.
  • Context – A working picture built from several sources: the conversation so far (short-term memory), the user’s profile and permissions from the gateway, session state, and relevant history from earlier interactions (long-term memory).
  • Constraints – The boundaries it has to respect: time limits, data access tied to the IAM role, token budgets, which tools are available, and organization-specific policies.

On AWS. Understand usually runs on Amazon Bedrock with a foundation model such as Anthropic Claude or Amazon Nova doing the intent classification. For model availability by AWS Region, refer to Supported models by AWS Region in Amazon Bedrock. The system prompt carries the agent’s persona, its tools, and its behavioral guardrails, and Amazon Bedrock Guardrails filter the input before the model ever sees it.

Phase 2: Plan (decompose, select tools, and define success criteria)

With the intent clear, the agent moves to Plan, where the foundation model breaks the goal into steps.

Sub-step Description Output
Decompose Break the user’s goal into a sequence of sub-tasks. Complex goals might require multiple tool calls and intermediate reasoning steps. Ordered task graph (directed acyclic graph, or DAG)
Select tools For each sub-task, select the appropriate tool(s) from the tool registry using tool descriptions and few-shot examples. Tool-to-task mapping
Success criteria Define what “done” looks like for each sub-task. The Reason phase uses this to evaluate whether a tool call succeeded. Evaluation rubric

No tool runs straight from the plan. Each call first passes through the tool gateway and policy enforcement layer, which checks permissions, inspects the input parameters, applies governance policy, and confirms the request is within budget.

Re-planning. Plan is not a one-shot step. When Reason sees that a sub-task failed or came back wrong, the agent can revise the plan by reordering the task graph, choosing a different tool, or splitting a stubborn step into smaller ones.

Phase 3: Retrieve (knowledge, memory, and session state)

In Retrieve, the agent grounds its reasoning in facts from three sources:

  • Knowledge base (Retrieval Augmented Generation, or RAG) – Semantic search over enterprise documents using embeddings and vector retrieval, with reranking for precision and access filtering for security.
  • Memory – Short-term (the conversation buffer), long-term (preferences and facts it has learned), and episodic (how past tasks turned out).
  • Session state – The current interaction’s tool-result cache, intermediate computations, and external API responses.

The RAG pipeline runs in four stages:

  1. Query rewriting: Optimize the natural language query for search, optionally generating multiple queries for different facets.
  2. Embedding and search: Embed the query and match against the vector index using approximate nearest neighbor (ANN) search.
  3. Reranking: A cross-encoder model reranks initial results for precision, filtering out false positives.
  4. Access filtering: Results are filtered based on the user’s identity and data access policies.

On AWS. Amazon Bedrock Knowledge Bases is the fully managed RAG capability. It handles chunking, embedding with Amazon Titan Embeddings, and vector storage in Amazon OpenSearch Serverless. For memory, Amazon DynamoDB holds session state and Amazon ElastiCache caches recent results for low-latency reads.

Phase 4: Reason (model routing, decide, and reflect)

Reason is where the model turns evidence into a decision. With the retrieved context in hand, it does three things:

  • Model routing – Pick the right model for this step. Simple work goes to smaller, faster models. Complex reasoning goes to a larger, more capable model. That keeps cost and latency down, and it’s one of the most effective cost-optimization levers in the architecture.
  • Decision – Combine what was retrieved with the plan to decide the next tool call, the parameters to pass, whether the plan needs changing, or whether to ask a clarifying question.
  • Reflection – Look at the result of each action. Did the call succeed? Does the output match what was expected? Does the plan need to change?

Anti-pattern: Infinite loops. Knowing when to stop is a core design problem. With no safeguards, an agent can get stuck reasoning in circles. The usual defenses are a cap on iterations, a timeout budget, classifying errors as transient or permanent, and a path to escalate to a human. Getting this wrong costs more than one unfinished task. A looping agent keeps calling the model and its tools, so token spend and compute climb with every wasted pass and nothing gets done. The effects compound. Latency rises and service level agreements (SLAs) slip. Downstream APIs and model endpoints absorb redundant load, which can trigger throttling for other workloads. The user waits on a request that never completes, which erodes the trust this architecture exists to protect. Caps on iterations, time, and tokens, plus an escalation path, keep a confused agent from turning into a runaway bill.

Phase 5: Act and observe (APIs, code, data, and MCP tools)

Act and Observe is where the agent reaches into the outside world. It carries the most governance risk because it changes real systems.

  • Tool execution – The agent calls external tools through standard interfaces (REST APIs, code sandboxes, data connectors, and Model Context Protocol (MCP) tools) and logs every call with its full request and response.
  • Observation – Each result is parsed, validated, and fed back into context: structured returns, error messages, status codes, side effects.
  • Approval gate – Before a destructive action runs (a write, delete, or send), it goes through the policy and approval gate. Depending on the risk and the organization’s policy, that is an automated check, a human sign-off, or both.

The feedback loop

When a tool returns success, an error, or partial data, the result flows back into Understand and becomes part of the context for the next pass. Each pass through the loop uses this new context to move closer to the right answer. What flows back includes:

  • Tool results: Structured data, API responses, and computation outputs.
  • Errors: Error messages, timeouts, and permission denials that inform replanning.
  • New evidence: Information discovered during tool execution that changes the understanding of the task.

Tool gateway and policy enforcement

The tool gateway sits between the runtime and the platform services, and it’s the single checkpoint every tool call goes through. It runs the RBAC checks, validates input, applies governance policy, and enforces rate limits and cost budgets. On AWS, that maps to Amazon Bedrock Agent action groups with IAM-based authorization, and you can add AWS Lambda authorizers when you need custom policy logic.

Knowledge and state layer

Layer 3 of 5 · Knowledge and state (see Figure 1)

The knowledge and state layer gives the agent two things it cannot work without: factual grounding and memory that survives across sessions. It’s organized as four tiers:

Tier Purpose AWS service
Enterprise search Full-text and semantic search across organizational knowledge bases, documentation, and wikis. Amazon Kendra, Amazon OpenSearch Service
Vector index Embeddings store for RAG retrieval. Supports approximate nearest neighbor search for semantic similarity. Amazon OpenSearch Serverless, Amazon Aurora PostgreSQL (pgvector), Amazon S3 Vectors
Short-term memory Conversation buffer and session context window. Provides continuity within a single interaction. Amazon ElastiCache, Amazon DynamoDB (time to live, or TTL)
Long-term memory User preferences, learned patterns, facts, and knowledge graph. Persists across sessions. Amazon DynamoDB, Amazon Neptune

Platform services layer

Layer 4 of 5 · Platform services (see Figure 1)

The platform services layer is the shared infrastructure the runtime depends on. These managed services keep operational complexity out of the agent.

Model gateway

The model gateway is one interface in front of many foundation models. It routes each task to the right model, falls back to another when one fails, and handles rate limiting, token metering, and response caching. Because it hides each provider’s API behind a common schema, you can swap models without touching agent code.

On AWS, Amazon Bedrock is that gateway, with serverless access to a growing lineup of foundation models including Anthropic Claude, Amazon Nova, Meta Llama, and Mistral. For model availability by Region, refer to Supported models by AWS Region in Amazon Bedrock. To run custom models, use Amazon SageMaker endpoints for managed inference with automatic scaling.

Tool registry

The tool registry is the catalog of every API, function, and connector the agent can call, along with their schemas, permissions, descriptions, and versions. Plan reads this registry to choose tools for each sub-task. Each tool is registered with an OpenAPI schema that spells out its inputs, outputs, and side effects.

On AWS, Amazon Bedrock Agent action groups hold those schemas and wire them to AWS Lambda functions or API endpoints, giving you a governed, versioned catalog the agent can discover and call.

Secrets and IAM

This is where API keys, database credentials, and OAuth tokens live and get rotated. Fine-grained IAM policies decide which agents can reach which secrets, so credentials don’t leak into a trace or a log. AWS Secrets Manager handles the rotation, and IAM enforces least privilege.

Event bus

The event bus moves agent lifecycle events (start, tool call, completion, and error) asynchronously, which lets monitoring, alerting, and downstream integrations stay decoupled from the agent. Amazon EventBridge is the backbone, with Amazon Simple Notification Service (Amazon SNS) and Amazon Simple Queue Service (Amazon SQS) for fan-out and queuing.

Observability: Step-level tracing

Watching an agent isn’t like watching a normal application. An agent runs a non-deterministic loop. The number of steps varies, tool calls branch, and plans change mid-execution. Step-level tracing must capture the full execution graph, not only the request and response.

At every step, the observability layer captures four kinds of signal:

Signal What it captures Why it matters
Step-level tracing Parent-child span relationships, phase transitions, decision branching points Debug non-deterministic behavior. Trace root cause of incorrect outputs
Latency Per-step wall clock time, model inference time, tool round-trip time Identify bottlenecks. SLA compliance. Performance optimization
Tokens Input and output tokens per model call, context window utilization, cumulative usage Cost attribution and optimization (per user, tenant, and workflow). Context overflow prevention. Prompt optimization
Tool status Tool call success/failure rates, response codes, retry counts, payload sizes Tool reliability scoring. Automatic fallback decisions. SLA monitoring

On AWS – Use AWS X-Ray with custom segments for the agent’s steps, Amazon CloudWatch for metrics and alarms, and Amazon CloudWatch Logs Insights to query trace data. Amazon Bedrock logs model invocations natively, with the input and output payloads and token counts.

Trust and control framework

Layer 5 of 5 · Trust and control, with cross-cutting governance (see Figure 1)

A lack of trust is the main barrier to deploying enterprise agents. This layer sits between the runtime and the final output and runs each action through a series of gates to confirm it meets the organization’s standards before it ships. These controls also help organizations meet the obligations of emerging regulatory frameworks such as the EU AI Act, helping reduce exposure to penalties and keep AI use compliance-aware and responsible. (see Figure 3)

Grounded in recognized standards. The four gates aren’t an arbitrary sequence. Each one maps to a responsible-AI control that already exists. They track the responsible-AI dimensions of the AWS Well-Architected Generative AI Lens (safety, veracity and robustness, controllability, transparency, and governance) and the risk functions in the NIST AI Risk Management Framework (govern, map, measure, manage). The mapping is direct. Gate 1, guardrails, is the safety gate: it filters harmful content and the output-handling risks in the OWASP Top 10 for LLM Applications. Gate 2, evaluations, is where veracity and robustness get checked, through groundedness and hallucination tests. Gate 3, confidence scoring, is the transparency gate. It surfaces uncertainty and shows the source of each claim. Gate 4, human approval, is what keeps a person in control as the system scales. Measured against standards like these, the pipeline is auditable on terms reviewers and regulators already know, rather than an internal checklist.

Four-gate trust and control pipeline: guardrails, evaluations, confidence scoring, and human approval

Figure 3: Trust and control, four-gate verification pipeline

Gate 1: Guardrails

Content filtering, personally identifiable information (PII) detection, toxicity checks, and topic deny-lists. Guardrails work on the output, scanning the agent’s response before the user sees it. On AWS, Amazon Bedrock Guardrails gives you configurable filters for hate, insults, sexual content, violence, and misconduct, plus your own denied topics and PII redaction.

Gate 2: Evaluations

This gate checks whether the retrieved content supports the response. This gate covers groundedness, hallucination detection, and format validation, and it can hand the output to a separate “judge” model to score the primary model’s work.

Gate 3: Confidence scoring

The agent rates its own confidence, attributes its key claims to sources, flags where it is unsure, and checks that confidence against a threshold. Anything below the line goes to a human instead of straight to the user.

Gate 4: Human approval (HITL)

For high-risk actions, such as moving money, modifying data, or sending external communications, the agent routes through a human-in-the-loop (HITL) approval step. The reviewer sees the proposed action, the agent’s reasoning, and the confidence score, and can approve it, change it, or reject it. Every decision is logged.

Verified outcomes

After an action clears the gates, it ends up as one of four outcome types, each with its own governance bar:

Outcome Description Risk level Governance
Respond Generate a natural language response to the user. Lowest risk: guardrails and content filters are sufficient. Low Guardrails only
Write Create or modify data in an external system (database record, document, configuration). Medium Policy gate + logging
Trigger workflow Initiate an automated workflow or pipeline (deployment, data pipeline, notification chain). High Policy + HITL approval
Escalate / HITL Agent determines that human intervention is needed: confidence too low, action too risky, or request out of scope. Critical Full approval chain

Cross-cutting governance

Governance is the layer underneath everything else. It helps the organization operate within its legal, regulatory, and ethical requirements at every level, and it rests on five pillars (see Figure 4):

Five pillars of agent governance: security, observability, audit, cost, and compliance

Figure 4: Five pillars of agent governance

  • Security: Encryption at rest and in transit, virtual private cloud (VPC) isolation, AWS WAF and AWS Shield protection, data classification, and network segmentation.
  • Observability: Distributed tracing, metrics dashboards, anomaly detection, alert routing, and SLA monitoring across all agent operations.
  • Audit: Immutable audit logs, decision trails, tool call records, data lineage tracking, and automated compliance reports.
  • Cost: Token metering per user and team, model tiering for cost optimization, budget alerts, per-user quotas, and cost attribution dashboards.
  • Compliance: Considerations such as data residency, retention policies, and mechanisms to support data subject requests (for example, access and deletion) that your organization might need to address under regulations like GDPR or CCPA. If your workload processes protected health information, use HIPAA eligible services and review your responsibilities under the AWS Shared Responsibility Model. AWS compliance programs such as SOC 2 cover the underlying AWS services, not your application. See AWS Services in Scope by Compliance Program.

Design patterns and best practices

The following patterns and anti-patterns come from AWS Professional Services engagements in which we built and ran enterprise agents in production with customers, not from a whiteboard.

Teams already run architectures like this in production on AWS. One of these is Druva, a data security provider, which built DruAI, a multi-agent system on Amazon Bedrock AgentCore where specialized agents handle telemetry analysis, investigation guidance, and recovery workflows. According to the Druva case study, 68 percent of customer issues are now resolved through agent workflows, support-assisted resolution is 58 percent faster, and cyber investigations that once took 30–60 days now finish in minutes. Separately, Cox Automotive used Amazon Bedrock AgentCore to move 17 agentic solutions into production in under a year, with seven more in development. This architecture reflects patterns from these deployments.

These patterns answer design questions that keep coming up when teams build enterprise agents. Each pattern stands on its own. Adopt the ones that fit your workload and leave the rest.

Pattern: Graduated autonomy

Start agents read-only and widen their write access a step at a time as they earn trust. Use feature flags or IAM role escalation to set the autonomy level per user, team, or use case. That way the organization builds confidence in the system before handing it broader permissions.

Pattern: Fail-safe defaults

When the agent encounters a missing tool, an API timeout, or an ambiguous request, it should take the safe route: ask a clarifying question instead of guessing, or escalate to a human instead of risking a bad action. Encode this in the system prompt and back it up in the trust and control layer.

Pattern: Multi-model strategy

Match the model to the phase. Small, fast models can handle intent classification and simple routing (Phase 1). Larger models justify their cost in planning and reasoning (Phases 2 and 4). Specialized models do the evaluations in the trust layer. Teams that route this way usually cut cost while keeping quality where it counts, though the actual savings depend on your mix of work, your model choices, and your traffic. Benchmark against your own use cases before you commit to a target.

Pattern: Structured tool interfaces

Give every tool an explicit OpenAPI schema that defines input and output types, error codes, rate limits, and declared side effects. That is what lets Plan pick tools intelligently and lets Observe check what came back against what was promised.

Anti-patterns to avoid

These are the traps we have watched teams fall into early. Recognizing them early reduces rework.

Anti-pattern: Monolithic agent

Resist the urge to build one agent that does everything. Split the work into specialized agents (for example, calendar, code, and data analysis) coordinated by a supervisor agent. You get better reliability, straightforward testing, and the freedom to scale and deploy each one on its own.

Anti-pattern: Unbounded loops

Put a hard ceiling on loop iterations. A common production setting is 3 to 5 iterations against a total token budget. Past that, the agent should summarize where it got to and either escalate or ask the user what to do. Without that ceiling, a confused agent can spend tokens indefinitely and still get nowhere.

Anti-pattern: Trust-later architecture

Don’t file implementing governance, guardrails, and observability under “later.” They must be primitives from day one. Bolting trust controls onto an agent that is already in production costs more and introduces more defects than building them in from the start.

Bringing this architecture to life on AWS

This section takes the Figure 1 reference architecture and grounds it in concrete AWS services, mapping each layer of the five-layer loop to the managed services that implement it. Treat it as a set of sensible starting points, not a fixed bill of materials. Your scale, data residency, latency, and cost requirements will push some of these choices around, so use the mappings as a baseline, check them against the AWS Well-Architected Generative AI Lens, and tune for your own workload.

Mapping architecture layers to AWS services

Walking Figure 1 from the entry point down to verified outcomes, here is how each layer lands on AWS.

Layer 1: Entry point.

Configure Amazon API Gateway with a WebSocket API for streaming agent responses. Attach an Amazon Cognito user pool for OAuth 2.0/OIDC authentication. Define IAM policies that scope tool access by user role.

Layer 2: Agent runtime.

Create an Amazon Bedrock Agent with a system prompt that encodes your agent’s persona, behavioral guardrails, and the list of available tools. Define action groups that map to AWS Lambda functions or API endpoints. Enable Amazon Bedrock Guardrails for input and output filtering.

Layer 3: Knowledge and state.

Create an Amazon Bedrock Knowledge Base backed by Amazon Simple Storage Service (Amazon S3) as the data source and Amazon OpenSearch Serverless as the vector store. Configure Amazon DynamoDB tables for session state (with TTL for automatic expiry) and long-term memory. Optionally, add Amazon ElastiCache for low-latency result caching.

Layer 4: Platform services.

Amazon Bedrock acts as the model gateway. Register tools as Amazon Bedrock Agent action groups with OpenAPI schemas. Store API keys and credentials in AWS Secrets Manager with automatic rotation enabled. Configure Amazon EventBridge rules for agent lifecycle events.

Layer 5: Observability and governance.

Turn on Amazon Bedrock model invocation logging. Configure AWS X-Ray tracing for AWS Lambda functions. Set up Amazon CloudWatch dashboards for token usage, latency percentiles, and tool success rates. Turn on AWS CloudTrail for audit logging and AWS Config rules for compliance checks.

From baseline to production. These mappings give you a governed starting point, but most of the engineering effort goes into hardening this baseline into a production-grade agent tuned to your security, compliance, cost, and scale requirements. If you want to accelerate that journey, AWS Professional Services and AWS Partners can help you design, build, and operate this architecture for your own workloads. Learn more about engaging AWS Professional Services or finding an AWS Partner. Work with your security and legal teams to meet your organizational security, regulatory, and compliance requirements before deployment. Under the AWS Shared Responsibility Model, you are responsible for configuring and operating these services to meet those requirements.

Conclusion

The hard part of an enterprise agent was never the model. It’s everything around the model. That includes the identity that follows a request, the memory that persists, the gates an action clears, and the traces that show what happened. Get those right and the agent becomes something a business can actually rely on. Skip them and you have a clever demo that no one will put in front of a customer.

The governed, observable loop in this post is a reference point for teams moving past basic chatbots toward agents they can trust in production.

A few things worth holding onto:

  1. Governance isn’t a feature. It belongs in every layer, not bolted on at the end.
  2. You can’t govern what you cannot see. Step-level tracing is what makes reliable agent operations possible.
  3. The loop is the point. The five-phase loop, with feedback on every pass, is what distinguishes an agent from a chatbot.
  4. Trust is earned in steps. Start narrow and read-only, then widen as the system proves itself.
  5. The pieces are already on AWS. Amazon Bedrock for models and guardrails, Amazon EventBridge for event-driven observability, and AWS IAM for access control. Every component maps to a managed service.

Next steps

Further reading

For a service-by-service reference that maps these architectural layers to AWS offerings, refer to the AWS Prescriptive Guidance on agentic AI: Foundations of Agentic AI on AWS covers the conceptual foundations, and Enterprise Multi-Account Architecture for Agentic AI covers production infrastructure. Because managed services evolve, these guides are kept current with the recommended services for each layer.


About the authors

Rushabh Lokhande

Rushabh Lokhande

Rushabh Lokhande is a Senior Data and AI Engineer at AWS Professional Services, where he helps enterprise customers design, build, and scale generative and agentic AI solutions on AWS. He specializes in taking LLM workloads from prototype to production, with a focus on governance, observability, and cost optimization.

Paul Tamburello

Paul Tamburello

Paul is the Data & AI Leader at AWS Professional Services in North America. He supports customers to modernize and transform their business utilizing AI on AWS. He focuses on enterprise Data and AI strategy for all industries, leveraging the latest in AI technologies.

Migrating from Apache Hudi-based data lake to Apache Iceberg-based data lake

Post Syndicated from Nitin Kumar original https://aws.amazon.com/blogs/big-data/migrating-from-apache-hudi-based-data-lake-to-apache-iceberg-based-data-lake/

A cloud data lake is a scalable, low-cost place to store data from many different sources. Over the years, data lakes built on Amazon Simple Storage Service (Amazon S3) have become a common home for enterprise data, used by teams who query it for analytics and machine learning. However, data lakes have historically made it hard to update and delete records, keep transactions isolated, and handle concurrent changes safely. Open table formats such as Apache Hudi, Delta Lake, and Apache Iceberg were created to solve these problems. They add ACID transactions and row-level updates and delete, along with snapshot history and schema enforcement that make data lakes easier to audit and govern.

As organizations’ data architectures mature and evolve, the need to migrate between these table formats becomes increasingly common. This transition is often driven by changing requirements, performance considerations, or the desire to use newer features. Among these migrations, the shift from Apache Hudi to Apache Iceberg has gained particular attention, as organizations seek to capitalize on Iceberg’s modern architecture and advanced capabilities.

In this post, we show how to convert Apache Hudi tables to Apache Iceberg, using a Jupyter notebook running on AWS Glue 5.1 interactive sessions.

Benefits of migration to Iceberg

Enhanced partition evolution

Iceberg supports dynamic changes to partitioning schemes without requiring complete data rewrites. This capability is valuable in evolving data environments where query patterns change over time. You can adjust your partitioning strategy to optimize performance, reducing the operational overhead traditionally associated with such changes. Your data lake can adapt to changing business requirements without costly reorganization efforts.

Hidden partitioning

In addition to standard partitioning on an existing column, Iceberg supports hidden partitioning, which decouples the physical partition layout from the columns that queries filter on. The table specification declares a partition transform, which is a rule that tells Iceberg how to derive the partition value from a source column, such as a time bucket or a hash of the column value. The transform is defined once at the table level, and Iceberg applies it automatically on every write. This removes a long-standing source of friction on both sides of the table: writers no longer need to extract and maintain a separate partition column alongside the real one at ingestion time, and queries no longer need to carry an extra predicate on that derived column to get good performance.

Openness with the Iceberg REST Catalog

The Iceberg REST Catalog specification defines a standard HTTP protocol for catalog operations. Any engine that speaks the protocol can talk to any catalog that implements it, without a catalog-specific client library or implementation JAR on the class path. Integration moves from a code and dependency problem to a configuration problem, making Iceberg a strong fit for multi-engine data architectures.

Deep integration with AWS services

Iceberg has native integration across the AWS analytics ecosystem. Amazon Athena, Amazon Redshift, Amazon EMR, and AWS Glue all read and write Iceberg tables directly. The AWS Glue Data Catalog provides catalog and metadata management for these tables, and Amazon SageMaker builds on the same open Lakehouse foundation, letting analytics and artificial intelligence and machine learning (AI/ML) workloads share a single copy of data across Amazon S3 data lakes (including Amazon S3 Tables), with SageMaker Feature Store supporting an Iceberg offline store for faster training dataset extraction. On the ingestion side, Amazon Data Firehose delivers data into Iceberg tables from sources such as Direct PUT, Amazon Kinesis Data Streams, Amazon Managed Streaming for Apache Kafka (Amazon MSK), Amazon CloudWatch Logs, and AWS IoT, with optional on-the-fly record transformation by using AWS Lambda. No-code Streaming Tables map a single Kinesis Data Streams stream or a single Amazon MSK (Express brokers) Kafka topic to a single Amazon S3 Tables Iceberg table, with the target table auto-created and partitioning configured on the delivery channel.

AWS managed features

AWS provides managed capabilities specifically designed for Iceberg. These managed features reduce operational overhead while maintaining performance and cost efficiency, so teams can focus on deriving insights rather than managing infrastructure.

  • AWS Glue Iceberg table optimizer – Automated compaction, snapshot management, and orphan file cleanup without manual intervention on Iceberg tables in General S3 buckets.
  • Amazon S3 Tables – Fully managed Iceberg tables with automatic optimization and maintenance.
  • Zero-ETL integration – Managed, incremental replication from Amazon DynamoDB and third-party enterprise applications such as Salesforce, SAP, ServiceNow, and Zendesk into Iceberg tables in Amazon S3 (self-managed or Amazon S3 Tables), with no custom pipeline or connector code to maintain. Source changes are applied incrementally, so the target stays in sync without full reloads.
  • Iceberg materialized views – SQL-defined views materialized as native Iceberg tables, refreshed on an automatic schedule and incrementally when the source tables allow it, with change detection handled for you. Well suited to consumption-layer tables that feed dashboards, APIs, and downstream pipelines, since the work shifts from query time to the managed refresh.

These benefits make Apache Iceberg a strong choice for modern data lake implementations, offering advantages in performance, manageability, and scalability compared to traditional table formats.

In the context of migrating data to Apache Iceberg, two primary approaches exist: in-place migration and full table migration. We previously covered both in the blog post “Migrate an existing data lake to a transactional data lake using Apache Iceberg” which walks through the methodology for traditional Hive-style tables, meaning partitioned Apache Parquet, Apache ORC, or Apache Avro datasets registered in a Hive-compatible catalog. The same two approaches apply when the starting point is an Apache Hudi data lake, which comes in two flavors, Copy-on-Write (CoW) and Merge-on-Read (MoR).

In-place migration

This approach generates fresh Iceberg metadata on top of the existing data files of the source table, without rewriting the data itself. The Parquet files of a Hive, Hudi, or Delta Lake table stay in place, and a new or existing Iceberg table is pointed at them with its own metadata layer. The main advantage is cost and speed: no data rewrite, so the migration is fast and cheap on both compute and storage. The main limitation is that the Iceberg table inherits the source table’s schema, partitioning, and physical file shape (file sizes, row groups, sort order), and none of these can be changed during the migration itself.

Full table migration

In this approach, the data itself is rewritten into a new Iceberg table, typically using a writeTo() call or a CREATE TABLE AS SELECT (CTAS) statement. It works for any source an engine can read from (Hive, Hudi, Delta Lake, relational databases, and others), and because the data is being rewritten anyway, the migration step is also where you can reshape it: change the schema, apply Iceberg hidden partitioning, resort the data for pruning, and target larger file sizes than the source has. The trade-offs are cost, time, and storage: higher compute spend, longer migration, and the dataset is effectively stored twice (source and target) until the migration completes, and the source is retired. For large historical tables, a single CTAS is usually impractical, so the common pattern is to seed the table with a small CTAS and then run INSERT INTO ... SELECT partition by partition, parallelizing and checkpointing across batches.

In this post we work through both approaches end-to-end. We first create a sample Hudi event table in each flavor, CoW and MoR, then migrate them in place to Iceberg using two techniques, the Spark Iceberg add_files procedure and the Apache XTable sync tool, covering the considerations and prerequisites of each. Finally, we walk through the full table migration path, where the source data is rewritten into a new Iceberg table from scratch.

Solution overview

The following diagram illustrates the architecture that you implement through this post.

Architecture diagram of the Hudi-to-Iceberg migration workflow on AWS

Figure 1: Migration architecture showing the in-place paths (add_files and Apache XTable) and the full-table paths (CTAS and INSERT) to Amazon S3 and Amazon S3 Tables, all registered in the AWS Glue Data Catalog and queried with Amazon Athena

The workflow consists of the following steps:

  1. An AWS Glue notebook writes the source data as Apache Hudi tables to an Amazon S3 bucket and registers them in the AWS Glue Data Catalog. This creates the existing Hudi data lake that the migration starts from.
  2. The first in-place migration approach uses an AWS Glue notebook to run the Apache Iceberg add_files procedure. The procedure creates Iceberg metadata on top of the Parquet data files already in the Hudi table. The new Iceberg metadata points to the same Parquet files, so no data is copied or rewritten. This makes it a fast, low-cost migration path.
  3. The second in-place migration approach runs Apache XTable on an Amazon Elastic Compute Cloud (Amazon EC2) instance to convert the Hudi table metadata into Iceberg metadata. XTable reads the Hudi commit timeline and creates matching Iceberg metadata that points to the same Parquet files. Both table formats can then share a single copy of the data.
  4. For a full migration, an AWS Glue notebook uses CREATE TABLE AS SELECT (CTAS) or INSERT INTO statements to read the Hudi data and rewrite it as new Iceberg tables. The tables can go in a general purpose S3 bucket or in Amazon S3 Tables. This approach fully separates the new tables from the Hudi source. S3 Tables also handle table maintenance for you, such as compaction and snapshot management.
  5. The AWS Glue Data Catalog registers the Iceberg tables from all three approaches. Users can then use Amazon Athena, a serverless query service, to run SQL queries on these tables and validate the migrated data. Athena enables interactive SQL-based exploration of data directly in Amazon S3 without the need for complex infrastructure management.

Prerequisites

Before getting started, make sure you have the following:

Launch an AWS Glue Studio notebook for processing

For this post, we use an AWS Glue Studio notebook. Follow the steps in Getting started with notebooks in AWS Glue Studio to set up the notebook environment.

  1. Sign in to the AWS Management Console and open the AWS Glue console.
  2. In the Region selector (top right), choose your preferred working Region.
  3. Choose ETL Jobs in the left pane.
  4. Choose Notebook under Author using an interactive code notebook, select Start fresh, choose your IAM role, and choose Create notebook.
  5. After a minute, the Jupyter notebook editor appears. Clear all the default cells.

Create Hudi Copy-on-Write (CoW) and Merge-on-Read (MoR) sample event tables

This notebook creates Hudi tables using both Copy-on-Write (CoW) and Merge-on-Read (MoR) table types with sample events. We perform inserts, updates, and deletes, then inspect the underlying file structures to understand the key differences:

  • CoW: an update or delete fully rewrites every base Parquet file that contains an impacted row, producing a new file slice in the file group. Reads are cheap, and writes amplify with the fraction of files touched.
  • MoR: an update or delete is appended to an Avro log file alongside the base file instead of rewriting the base, and base + logs are merged at read time (or compacted into a new base file later). Cheaper writes. Costlier reads until compaction.
  1. Execute the first cell with the following configuration to set up the Spark session with Hudi and Iceberg support:

Code:

{
"glue_version": "5.1",
"worker_type": "G.1X",
"number_of_workers": 5,
"idle_timeout": 30,
"--datalake-formats" : "hudi,iceberg",
"--conf" : "spark.serializer=org.apache.spark.serializer.KryoSerializer --conf spark.sql.extensions=org.apache.spark.sql.hudi.HoodieSparkSessionExtension,org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions --conf spark.sql.catalog.glue_iceberg=org.apache.iceberg.spark.SparkCatalog --conf spark.sql.catalog.glue_iceberg.warehouse=s3://YOUR_BUCKET/warehouse/ --conf spark.sql.catalog.glue_iceberg.type=glue --conf spark.sql.catalog.spark_catalog=org.apache.spark.sql.hudi.catalog.HoodieCatalog --conf spark.kryo.registrator=org.apache.spark.HoodieSparkKryoRegistrar"
}
  1. Initialize the session and configuration. Update the bucket_name, db_name and region variables with your configurations. Reusable helper – list_table_files(table_name, label="", verbose=False) renders a table’s S3 layout as a directory tree so you can SEE how CLEAN, COMPACT and add_files change the files underneath. It is reused before/after each of those steps instead of re-coding the listing.

Code:

# ──────────────────────────────────────────────
# Source Hudi tables
# ──────────────────────────────────────────────
hudi_events_cow_table = "events_hudi_cow" # Copy-on-Write source
hudi_events_mor_table = "events_hudi_mor" # Merge-on-Read source
# ──────────────────────────────────────────────
# In-place migration targets (add_files/xtable)
# ──────────────────────────────────────────────
iceberg_cow_inplace = "events_iceberg_cow_inplace"
iceberg_mor_inplace = "events_iceberg_mor_inplace"
iceberg_cow_xtable = "events_hudi_cow_iceberg_xtable"
iceberg_mor_xtable = "events_hudi_mor_iceberg_xtable"
# ──────────────────────────────────────────────
# Full table (shadow) migration targets
# ──────────────────────────────────────────────
iceberg_cow_full_ctas = "events_iceberg_cow_full_ctas"
iceberg_cow_full_create_insert = "events_iceberg_cow_full_create_insert"
iceberg_mor_full_ctas = "events_iceberg_mor_full_ctas"
iceberg_mor_full_create_insert = "events_iceberg_mor_full_create_insert"
# ──────────────────────────────────────────────
# Infrastructure
# ──────────────────────────────────────────────
bucket_name = "demoblogiceberg-bdb5001" # S3 bucket for data
db_name = "hudi_to_iceberg_blog" # Glue Data Catalog database
region = "us-east-1"
# Create the Glue Data Catalog database
spark.sql(f"""
CREATE DATABASE IF NOT EXISTS {db_name}
LOCATION 's3://{bucket_name}/{db_name}'
""")
# Reusable helper —list_table_files()(S3 layout tree)
import boto3
s3 = boto3.client('s3', region_name=region)
# File/folder annotations keyed by classifier result
_NOTES = {
"hoodie_dir": "<-- Hudi metadata (timeline, schema, indexes)",
"hoodie_mdt": "<-- Hudi metadata table (internal index & stats, MoR)",
"hoodie_files": "<-- file listing index",
"hoodie_cstats":"<-- column-level min/max/null stats",
"hoodie_ridx": "<-- record-key -> file-group mapping",
"ice_meta_dir": "<-- Iceberg metadata layer (metadata.json, manifest lists, manifests)",
"ice_data_dir": "<-- Iceberg data layer (base Parquet files)",
"base": "<-- base Parquet file",
"log": "<-- Hudi delta log file (MoR update, uncompacted)",
"part_meta": "<-- Hudi partition marker",
"metadata_json":"<-- Iceberg table metadata (schema, snapshots)",
"manifest_list":"<-- Iceberg manifest list (snapshot -> manifests)",
"manifest": "<-- Iceberg manifest (lists data files)",
"props": "<-- table configuration & schema",
}
# Fixed-path annotations for metadata directories
_DIR_KIND = {
".hoodie": "hoodie_dir", ".hoodie/metadata": "hoodie_mdt",
".hoodie/metadata/files": "hoodie_files",
".hoodie/metadata/column_stats": "hoodie_cstats",
".hoodie/metadata/record_index": "hoodie_ridx",
"metadata": "ice_meta_dir", "data": "ice_data_dir",
}
def _fmt_size(n):
"""Human-readable byte size."""
for u in ("B", "KB", "MB", "GB", "TB"):
if n < 1024 or u == "TB":
return f"{n:,.0f} {u}" if u == "B" else f"{n:,.1f} {u}"
n /= 1024.0
def _leaf_kind(name):
"""Classify a leaf file by name -> annotation key / count bucket."""
if ".log." in name: return "log"
if name.startswith(".hoodie_partition_metadata"): return "part_meta"
if name == "hoodie.properties": return "props"
if name.endswith(".metadata.json"): return "metadata_json"
if name.startswith("snap-") and name.endswith(".avro"): return "manifest_list"
if name.endswith(".avro"): return "manifest"
if name.endswith(".parquet"): return "base"
return ""
def list_table_files(table_name, label="", verbose=False, max_depth=2, max_children=2):
"""Render a Hudi/Iceberg table's S3 layout as an annotated directory tree.
Teaching view for CLEAN/COMPACT/add_files: multiple base files in a partition
= stale file slices; .log.* = uncompacted MoR updates. The large Hudi .hoodie/
is summarized (depth/width capped); Iceberg metadata/ and data partitions show
in full. verbose=True expands everything.
"""
prefix = f"{db_name}/{table_name}/"
header = f"s3://{bucket_name}/{prefix}"
if label:
header += f" [{label}]"
print(header)
in_meta = lambda p: (p.split("/", 1)[0] if p else "") in (".hoodie", "metadata")
capped_meta = lambda p: (p.split("/", 1)[0] if p else "") == ".hoodie"
# ---- gather objects into a nested tree + tally honest counts -----------
root = {"d": {}, "f": []}
n_base = n_log = n_meta = n_other = 0
s_base = s_log = s_meta = 0
has_hudi = has_ice = False
for page in s3.get_paginator("list_objects_v2").paginate(Bucket=bucket_name, Prefix=prefix):
for obj in page.get("Contents", []):
key = obj["Key"].replace(prefix, "")
size = obj["Size"]
if key == "" or key.endswith("/"):
continue # S3 directory marker
parts = key.split("/")
fname, top = parts[-1], parts[0]
if top == ".hoodie": has_hudi = True
if top == "metadata": has_ice = True
# files inside a metadata folder count ONLY as metadata
if top in (".hoodie", "metadata"):
n_meta += 1; s_meta += size
elif ".log." in fname:
n_log += 1; s_log += size
elif fname.endswith(".parquet"):
n_base += 1; s_base += size
elif fname.startswith(".hoodie"):
n_meta += 1; s_meta += size; has_hudi = True
else:
n_other += 1
node = root
for part in parts[:-1]:
node = node["d"].setdefault(part, {"d": {}, "f": []})
node["f"].append((fname, size))
# ---- helpers -----------------------------------------------------------
def count_all(node):
return len(node["f"]) + sum(count_all(c) for c in node["d"].values())
def collapse(node, name, rel):
"""Merge single-child, file-less dir chains (year=/month=/day=)."""
while (len(node["d"]) == 1 and not node["f"] and not in_meta(rel)):
cname, child = next(iter(node["d"].items()))
crel = f"{rel}/{cname}"
if in_meta(crel): break
name, rel, node = f"{name}/{cname}", crel, child
return name, rel, node
def line(indent, branch, text, note, width):
s = f"{indent}{branch}{text}"
return f"{s:<{width}} {note}" if note else s
def render(node, rel, indent, depth):
entries = ([("d", n, c) for n, c in sorted(node["d"].items())]
+ [("f", n, sz) for n, sz in sorted(node["f"], key=lambda f: (".log." in f[0], f[0]))])
cap = (not verbose) and capped_meta(rel) and len(entries) > max_children
shown = entries[:max_children] if cap else entries
hidden = len(entries) - len(shown)
for i, item in enumerate(shown):
last = (i == len(shown) - 1) and hidden == 0
branch = "└── " if last else "├── "
sub = indent + (" " if last else "│ ")
if item[0] == "d":
_, name, child = item
disp, erel, enode = collapse(child, name, f"{rel}/{name}" if rel else name)
note = _NOTES.get(_DIR_KIND.get(erel, ""), "")
cnt = f" ({count_all(enode)} obj)" if (in_meta(erel) or erel in _DIR_KIND) else ""
print(line(indent, branch, f"{disp}/{cnt}", note, 60))
if (not verbose) and capped_meta(erel) and depth + 1 > max_depth:
inner = count_all(enode)
if inner:
print(f"{sub}└── … ({inner} objects, use verbose=True)")
else:
render(enode, erel, sub, depth + 1)
else:
_, name, size = item
note = _NOTES.get(_leaf_kind(name), "")
print(line(indent, branch, f"{name} ({_fmt_size(size)})", note, 72))
if hidden:
print(f"{indent}└── … (+{hidden} more)")
render(root, "", "", 0)
# ---- per-partition slice note (Hudi concept; skip metadata & Iceberg data/) ----
def slices(node, rel):
top = rel.split("/", 1)[0] if rel else ""
if top in (".hoodie", "metadata", "data"):
return
nb = sum(1 for f, _ in node["f"] if f.endswith(".parquet"))
nl = sum(1 for f, _ in node["f"] if ".log." in f)
if nb > 1:
print(f" note: {rel}/ has {nb} base files -> multiple file slices (stale versions)")
elif nb == 1 and nl:
print(f" note: {rel}/ has 1 base + {nl} log file(s) -> uncompacted MoR updates")
for n, c in node["d"].items():
slices(c, f"{rel}/{n}" if rel else n)
slices(root, "")
# ---- in-place migration note -------------------------------------------
if has_ice and "data" not in root["d"] and n_base == 0:
print(" note: Iceberg metadata/ present but no local data/ folder")
print(" -> in-place migration: data files remain registered in place at the source (Hudi) location; no data copied")
# ---- summary -----------------------------------------------------------
total = n_base + n_log + n_meta + n_other
print(
f"SUMMARY: {n_base} base · {n_log} log · {n_meta} meta"
+ (f" · {n_other} other" if n_other else "")
+ f" · {total} files · {_fmt_size(s_base + s_log + s_meta)}"
)
print(f" .hoodie/: {'present' if has_hudi else 'none'} metadata/ (Iceberg): {'present' if has_ice else 'none'}")
print()

Sample event data

We use a website clickstream events dataset, partitioned by year/month/day – a realistic pattern for event-driven architectures.

Note: In this example, we create the table with a preCombineField, which flips the default write operation of INSERT INTO from insert to upsert. You can override it explicitly with hoodie.spark.sql.insert.into.operation when you need a different behavior.

CoW table: create, upsert, and delete

We create a Hudi CoW table, insert records, apply an upsert, and delete a record, then inspect how the files change.

Create the Hudi CoW events table

Code:

spark.sql(f"""
CREATE TABLE {db_name}.{hudi_events_cow_table} (
event_id STRING,
user_id STRING,
event_type STRING,
event_timestamp TIMESTAMP,
page_url STRING,
year INT,
month INT,
day INT
)
USING HUDI
OPTIONS (
type = 'cow',
primaryKey = 'event_id',
preCombineField = 'event_timestamp'
)
PARTITIONED BY (year, month, day)
LOCATION 's3://{bucket_name}/{db_name}/{hudi_events_cow_table}/'
""")

Insert event records

Code:

spark.sql(f"""
INSERT INTO {db_name}.{hudi_events_cow_table}
VALUES
('EVT_001', 'USER_101', 'page_view', timestamp('2024-04-01 08:15:00'), '/home', 2024, 4, 1),
('EVT_002', 'USER_102', 'click', timestamp('2024-04-01 09:30:00'), '/products', 2024, 4, 1),
('EVT_003', 'USER_103', 'purchase', timestamp('2024-04-02 10:45:00'), '/checkout', 2024, 4, 2),
('EVT_004', 'USER_101', 'page_view', timestamp('2024-04-02 14:20:00'), '/blog', 2024, 4, 2),
('EVT_005', 'USER_104', 'signup', timestamp('2024-04-03 11:00:00'), '/register', 2024, 4, 3),
('EVT_006', 'USER_102', 'click', timestamp('2024-04-03 16:45:00'), '/deals', 2024, 4, 3)
""")

Upsert: simulate late-arriving corrections

Code:

spark.sql(f"""
INSERT INTO {db_name}.{hudi_events_cow_table}
VALUES
('EVT_002', 'USER_102', 'add_to_cart', timestamp('2024-04-01 09:31:00'), '/products/item-42', 2024, 4, 1),
('EVT_005', 'USER_104', 'signup', timestamp('2024-04-03 11:01:00'), '/welcome', 2024, 4, 3)
""")

Delete: remove a record

Code:

spark.sql(f"""
DELETE FROM {db_name}.{hudi_events_cow_table}
WHERE event_id = 'EVT_006'
""")

Inspect the CoW file structure

CoW tables rewrite the entire Parquet file on every upsert/delete. You will see one base Parquet file per file group (no log files).

Code:

list_table_files(hudi_events_cow_table, "COW --- initial file structure")

Output:

s3://demoblogiceberg-bdb5001/hudi_to_iceberg_blog/events_hudi_cow/ [COW — initial file structure]
├── .hoodie/ (50 obj) <-- Hudi metadata (timeline, schema, indexes)
│ ├── .......trimmed
└── year=2024/month=4/
├── day=1/
│ ├── .hoodie_partition_metadata (96 B) <-- Hudi partition marker
│ ├── 7d187e9a.....20261011152509633.parquet (426.3 KB) <-- base Parquet file
│ └── 7d187e9a.....20261011152403779.parquet (426.4 KB) <-- base Parquet file
├── day=2/
│ ├── .hoodie_partition_metadata (96 B) <-- Hudi partition marker
│ └── e583fe17.....20261011152403779.parquet (426.4 KB) <-- base Parquet file
└── day=3/
├── .hoodie_partition_metadata (96 B) <-- Hudi partition marker
├── eedc1b38.....20261011152509633.parquet (426.3 KB) <-- base Parquet file
├── eedc1b38.....20261011152539102.parquet (426.2 KB) <-- base Parquet file
└── eedc1b38.....20261011152403779.parquet (426.4 KB) <-- base Parquet file
note: year=2024/month=4/day=1/ has 2 base files -> multiple file slices (stale versions)
note: year=2024/month=4/day=3/ has 3 base files -> multiple file slices (stale versions)
SUMMARY: 6 base · 0 log · 53 meta · 59 files · 2.8 MB
.hoodie/: present metadata/ (Iceberg): none

MoR table: create, upsert, and delete

We run the same create, upsert, and delete sequence on a Hudi MoR table.

Create the Hudi MoR events table

Code:

spark.sql(f"""
CREATE TABLE {db_name}.{hudi_events_mor_table} (
event_id STRING,
user_id STRING,
event_type STRING,
event_timestamp TIMESTAMP,
page_url STRING,
year INT,
month INT,
day INT
)
USING HUDI
OPTIONS (
type = 'mor',
primaryKey = 'event_id',
preCombineField = 'event_timestamp'
)
PARTITIONED BY (year, month, day)
LOCATION 's3://{bucket_name}/{db_name}/{hudi_events_mor_table}/'
""")

Insert initial event records

Code:

spark.sql(f"""
INSERT INTO {db_name}.{hudi_events_mor_table}
VALUES
('EVT_001', 'USER_201', 'page_view', timestamp('2024-05-10 07:00:00'), '/home', 2024, 5, 10),
('EVT_002', 'USER_202', 'click', timestamp('2024-05-10 08:15:00'), '/products', 2024, 5, 10),
('EVT_003', 'USER_203', 'purchase', timestamp('2024-05-11 09:30:00'), '/checkout', 2024, 5, 11),
('EVT_004', 'USER_201', 'page_view', timestamp('2024-05-11 12:00:00'), '/account', 2024, 5, 11),
('EVT_005', 'USER_204', 'signup', timestamp('2024-05-12 10:30:00'), '/register', 2024, 5, 12),
('EVT_006', 'USER_202', 'click', timestamp('2024-05-12 15:45:00'), '/deals', 2024, 5, 12)
""")

Upsert: simulate late-arriving corrections (creates delta log files)

Code:

spark.sql(f"""
INSERT INTO {db_name}.{hudi_events_mor_table}
VALUES
('EVT_002', 'USER_202', 'add_to_cart', timestamp('2024-05-10 08:16:00'), '/products/item-99', 2024, 5, 10),
('EVT_005', 'USER_204', 'signup', timestamp('2024-05-12 10:31:00'), '/welcome', 2024, 5, 12)
""")

Delete: remove a record

Code:

spark.sql(f"""
DELETE FROM {db_name}.{hudi_events_mor_table}
WHERE event_id = 'EVT_006'
""")

Inspect MoR: base Parquet and log files

MoR tables write updates as delta log files (.log.*) alongside the base Parquet files. This avoids full file rewrites for faster writes.

Code:

list_table_files(hudi_events_mor_table, "MOR --- base parquet + log files")

Output:

s3://demoblogiceberg-bdb5001/hudi_to_iceberg_blog/events_hudi_mor/ [MOR — base parquet + log files]
├── .hoodie/ (50 obj) <-- Hudi metadata (timeline, schema, indexes)
│ ├── .......trimmed
└── year=2024/month=5/
├── day=10/
│ ├── .hoodie_partition_metadata (96 B) <-- Hudi partition marker
│ ├── 7d5ce247.....20261011153110535.parquet (426.4 KB) <-- base Parquet file
│ └── .7d5ce247.....20261011153145862.log.1_1-164-788 (1.3 KB) <-- Hudi delta log file (MoR update, uncompacted)
├── day=11/
│ ├── .hoodie_partition_metadata (96 B) <-- Hudi partition marker
│ └── f9b8147e.....20261011153110535.parquet (426.4 KB) <-- base Parquet file
└── day=12/
├── .hoodie_partition_metadata (96 B) <-- Hudi partition marker
├── 3f0b5ad4.....20261011153110535.parquet (426.4 KB) <-- base Parquet file
├── .3f0b5ad4.....20261011153145862.log.1_0-164-787 (1.3 KB) <-- Hudi delta log file (MoR update, uncompacted)
└── .3f0b5ad4.....20261011153215018.log.1_0-192-901 (1.1 KB) <-- Hudi delta log file (MoR update, uncompacted)
note: year=2024/month=5/day=10/ has 1 base + 1 log file(s) -> uncompacted MoR updates
note: year=2024/month=5/day=12/ has 1 base + 2 log file(s) -> uncompacted MoR updates
SUMMARY: 3 base · 3 log · 53 meta · 59 files · 1.5 MB
.hoodie/: present metadata/ (Iceberg): none

Query both Hudi tables

Code:

print("=== COW Table (events_hudi_cow) ===")
spark.sql(f"SELECT event_id, user_id, event_type, event_timestamp, page_url, year, month, day FROM {db_name}.{hudi_events_cow_table} ORDER BY event_id").show(truncate=False)
print("\n=== MOR Table (events_hudi_mor) ===")
spark.sql(f"SELECT event_id, user_id, event_type, event_timestamp, page_url, year, month, day FROM {db_name}.{hudi_events_mor_table} ORDER BY event_id").show(truncate=False)

Output:

=== COW Table (events_hudi_cow) ===
+--------+--------+-----------+-------------------+-----------------+----+-----+---+
|event_id|user_id |event_type |event_timestamp |page_url |year|month|day|
+--------+--------+-----------+-------------------+-----------------+----+-----+---+
|EVT_001 |USER_101|page_view |2024-04-01 08:15:00|/home |2024|4 |1 |
|EVT_002 |USER_102|add_to_cart|2024-04-01 09:31:00|/products/item-42|2024|4 |1 |
|EVT_003 |USER_103|purchase |2024-04-02 10:45:00|/checkout |2024|4 |2 |
|EVT_004 |USER_101|page_view |2024-04-02 14:20:00|/blog |2024|4 |2 |
|EVT_005 |USER_104|signup |2024-04-03 11:01:00|/welcome |2024|4 |3 |
+--------+--------+-----------+-------------------+-----------------+----+-----+---+
=== MOR Table (events_hudi_mor) ===
+--------+--------+-----------+-------------------+-----------------+----+-----+---+
|event_id|user_id |event_type |event_timestamp |page_url |year|month|day|
+--------+--------+-----------+-------------------+-----------------+----+-----+---+
|EVT_001 |USER_201|page_view |2024-05-10 07:00:00|/home |2024|5 |10 |
|EVT_002 |USER_202|add_to_cart|2024-05-10 08:16:00|/products/item-99|2024|5 |10 |
|EVT_003 |USER_203|purchase |2024-05-11 09:30:00|/checkout |2024|5 |11 |
|EVT_004 |USER_201|page_view |2024-05-11 12:00:00|/account |2024|5 |11 |
|EVT_005 |USER_204|signup |2024-05-12 10:31:00|/welcome |2024|5 |12 |
+--------+--------+-----------+-------------------+-----------------+----+-----+---+

Migrate Hudi tables to Iceberg with in-place migration

In-place migration keeps the original Parquet data files where they are and only builds Iceberg metadata on top of them. There is no rewrite of the underlying data, which makes the migration fast and inexpensive even on large tables. Two tools cover the common cases on AWS:

  • add_files (Iceberg built-in procedure). A Spark procedure shipped with Apache Iceberg that registers existing Parquet files into an Iceberg table by writing the corresponding manifests, without rewriting the data. It runs as a Spark job in which the source table’s partitions are distributed across Spark tasks, so file listing and column-statistics gathering happen in parallel on the cluster.
  • Apache XTable (incubating). An open-source cross-format translation tool that can read the metadata of one lakehouse format (Hudi, Delta, or Iceberg) and write out the equivalent metadata for another, pointing at the same underlying Parquet files. XTable can run once to produce the initial Iceberg metadata, or run on a schedule to keep the Iceberg view continuously in sync with ongoing writes to the Hudi table.

Choosing between add_files and Apache XTable for in-place migration

When planning an in-place migration, it is important to understand the strengths of each approach:

  • add_files is best suited for a one-time migration. It registers existing Hudi Parquet files into an Iceberg table in a single operation. After the migration is complete, the source Hudi table and target Iceberg table are independent, and any subsequent changes to the Hudi table are not reflected in Iceberg.
  • Apache XTable supports both an initial one-time conversion and ongoing incremental synchronization. This makes it ideal for transition periods where you need to keep both the source Hudi tables and the target Iceberg tables in sync while downstream consumers gradually migrate to Iceberg. After all workloads have been cut over, you can stop the sync process and decommission the Hudi tables.

Important notes

add_files/XTable register existing Parquet files as-is, so they rely on the column names baked into each file. Added and dropped columns are safe, but if the source table was renamed any column during its lifecycle, files written before the rename still hold the old name and reads against the new name return NULL for them. For tables with a history of column renames, prefer a full migration instead.

Iceberg version and column statistics (in-place add_files / snapshot): In Iceberg 1.9.0 through 1.10.0, the add_files and snapshot procedures don’t generate column stats in the Iceberg metadata. The cause is a NameMapping loss in ParquetUtil.footerMetrics. Without those column-level lower/upper bounds and null counts, the migrated Iceberg table loses most of its file-skipping ability at query planning time, which translates into more Parquet files being inspected, higher scan volume, and slower queries, especially for selective filters on non-partition columns. The issue is fixed in the Iceberg 1.10.1 release (#14617). Affected runtimes are AWS Glue 5.1 and Amazon EMR 7.11–7.13. We recommend AWS Glue 6.0+ or Amazon EMR 7.14+ for production migrations.

Shared data files during in-place migration: With both approaches, the in-place migration doesn’t copy data. The resulting Iceberg table points to the same underlying Parquet files as the source Hudi table. This means that until you perform a full cutover to Iceberg, you must avoid destructive operations on the Iceberg table that could delete or modify the shared data files. Specifically:

  • Don’t drop the Iceberg table with the PURGE option.
  • Don’t run Iceberg maintenance tasks such as expire_snapshots or remove_orphan_files.

Running any of these before cutover can remove files that the source Hudi table still depends on, leading to data loss. Iceberg exposes a built-in guardrail against this: the gc.enabled table property. When set to false, Iceberg blocks the preceding destructive operations. How you apply this depends on which migration path you choose.

With add_files. Disable garbage collection immediately after the procedure finishes and keep it disabled until you have fully cut over to Iceberg.

Right after add_files:

spark.sql(f"""
ALTER TABLE {db_name}.{table_name}
SET TBLPROPERTIES ('gc.enabled' = 'false');
""")

After Hudi source is retired and the Iceberg table owns its own data, re-enable GC so maintenance can run normally:

spark.sql(f"""
ALTER TABLE {db_name}.{table_name}
SET TBLPROPERTIES ('gc.enabled' = 'true');
""")

With Apache XTable (incremental sync). The gc.enabled = false guardrail is only partially usable here, because XTable’s incremental sync needs GC to be enabled on the Iceberg table to operate normally. A practical pattern is:

  1. Run the initial full XTable sync.
  2. Temporarily set gc.enabled = false to run post-migration validation and consistency checks on the Iceberg table in a safe state.
  3. Set gc.enabled = true again before starting incremental sync and leave it on for the duration of the sync period.

Because the automatic guardrail is off during incremental sync, the burden shifts to operational discipline: as long as XTable is syncing and data files are shared with the Hudi table, don’t run any Iceberg operation that can delete source data files (no DROP TABLE ... PURGE, no expire_snapshots, no remove_orphan_files, no manual object deletion against the shared S3 prefix). Treat the Iceberg table as read-only in terms of file lifecycle until cutover is complete, and Hudi is decommissioned, at which point normal Iceberg maintenance can resume.

Don’t enable the AWS Glue Data Catalog table optimizer before cutover.

Glue-managed Iceberg maintenance (compaction, snapshot retention, orphan file cleanup) will rewrite or delete the Parquet files that the source Hudi table still depends on. Verify that no catalog-level optimizer applies to the migrated table and leave table-level optimization off until cutover is complete.

Prerequisites for in-place migration with add_files. The add_files procedure registers every Parquet file it finds under the source location into the target Iceberg table, with no awareness of Hudi’s file-group versioning. If more than one file version of the same record is present at migration time, each version is registered as a separate row, and the Iceberg table will contain duplicates. The source Hudi table must therefore expose exactly one file version per record before add_files runs:

  • CoW tables: Run CLEAN to remove old file versions, keeping only the latest Parquet files.
  • MoR tables: Run COMPACTION (merge delta logs into base Parquet) + CLEAN before calling add_files, since add_files can only register base Parquet files and cannot process Hudi delta log files.

Option 1: Migrate Hudi tables to Iceberg with the add_files Spark procedure

This option uses the Iceberg add_files procedure to register the existing Hudi Parquet files into new Iceberg tables. Run it once per table, after preparing the Hudi table so that only the current file versions remain.

Migrate CoW to Iceberg

We create the target Iceberg table, prepare the Hudi source so that only the current file versions remain, register those files, and validate the result.

Create the target Iceberg table with the same schema

Code:

spark.sql(f"""
CREATE TABLE glue_iceberg.{db_name}.{iceberg_cow_inplace} (
event_id STRING,
user_id STRING,
event_type STRING,
event_timestamp TIMESTAMP,
page_url STRING,
year INT,
month INT,
day INT
)
USING iceberg
PARTITIONED BY (year, month, day)
LOCATION 's3://{bucket_name}/{db_name}/{iceberg_cow_inplace}/'
""")

Run Hudi CLEAN to keep only the latest file versions

Check files listing for the Hudi table before the CLEAN operation:

Code:

list_table_files(hudi_events_cow_table, "COW --- BEFORE CLEAN")

Output:

s3://demoblogiceberg-bdb5001/hudi_to_iceberg_blog/events_hudi_cow/ [COW — BEFORE CLEAN]
├── .hoodie/ (50 obj) <-- Hudi metadata (timeline, schema, indexes)
│ ├── .......trimmed
└── year=2024/month=4/
├── day=1/
│ ├── .hoodie_partition_metadata (96 B) <-- Hudi partition marker
│ ├── 7d187e9a.....20261011152509633.parquet (426.3 KB) <-- base Parquet file
│ └── 7d187e9a.....20261011152403779.parquet (426.4 KB) <-- base Parquet file
├── day=2/
│ ├── .hoodie_partition_metadata (96 B) <-- Hudi partition marker
│ └── e583fe17.....20261011152403779.parquet (426.4 KB) <-- base Parquet file
└── day=3/
├── .hoodie_partition_metadata (96 B) <-- Hudi partition marker
├── eedc1b38.....20261011152509633.parquet (426.3 KB) <-- base Parquet file
├── eedc1b38.....20261011152539102.parquet (426.2 KB) <-- base Parquet file
└── eedc1b38.....20261011152403779.parquet (426.4 KB) <-- base Parquet file
note: year=2024/month=4/day=1/ has 2 base files -> multiple file slices (stale versions)
note: year=2024/month=4/day=3/ has 3 base files -> multiple file slices (stale versions)
SUMMARY: 6 base · 0 log · 53 meta · 59 files · 2.8 MB
.hoodie/: present metadata/ (Iceberg): none

Run the CLEAN operation specifying to keep only the latest file slices:

Code:

spark.sql(f"""
CALL spark_catalog.system.run_clean(
table => '{db_name}.{hudi_events_cow_table}',
clean_policy => 'KEEP_LATEST_FILE_VERSIONS',
file_versions_retained => 1
)
""").show(truncate=False)

Output:

+-----------------+--------------------+-------------------+-------------------------+-----------------------+-------+
|start_clean_time |time_taken_in_millis|total_files_deleted|earliest_commit_to_retain|bootstrap_part_metadata|version|
+-----------------+--------------------+-------------------+-------------------------+-----------------------+-------+
|20261011154407413|382 |3 | |{} |2 |
+-----------------+--------------------+-------------------+-------------------------+-----------------------+-------+

Check files listing for the Hudi table after the CLEAN operation:

Code:

list_table_files(hudi_events_cow_table, "COW --- AFTER CLEAN")

Output:

s3://demoblogiceberg-bdb5001/hudi_to_iceberg_blog/events_hudi_cow/ [COW — AFTER CLEAN]
├── .hoodie/ (59 obj) <-- Hudi metadata (timeline, schema, indexes)
│ ├── .......trimmed
└── year=2024/month=4/
├── day=1/
│ ├── .hoodie_partition_metadata (96 B) <-- Hudi partition marker
│ └── 7d187e9a.....20261011152509633.parquet (426.3 KB) <-- base Parquet file
├── day=2/
│ ├── .hoodie_partition_metadata (96 B) <-- Hudi partition marker
│ └── e583fe17.....20261011152403779.parquet (426.4 KB) <-- base Parquet file
└── day=3/
├── .hoodie_partition_metadata (96 B) <-- Hudi partition marker
└── eedc1b38.....20261011152539102.parquet (426.2 KB) <-- base Parquet file
SUMMARY: 3 base · 0 log · 62 meta · 65 files · 1.6 MB
.hoodie/: present metadata/ (Iceberg): none

Register Hudi Parquet files into Iceberg with add_files

Code:

spark.sql(f"""
CALL glue_iceberg.system.add_files(
source_table => 'parquet.`s3://{bucket_name}/{db_name}/{hudi_events_cow_table}/`',
table => 'glue_iceberg.{db_name}.{iceberg_cow_inplace}'
)
""").show(truncate=False)

Output:

+-----------------+-----------------------+
|added_files_count|changed_partition_count|
+-----------------+-----------------------+
|3 |NULL |
+-----------------+-----------------------+

Validate: compare Hudi CoW and Iceberg (in-place)

We can see the Hudi and Iceberg tables reflect the same content:

Code:

print("Source: Hudi COW")
spark.sql(f"SELECT event_id, user_id, event_type, event_timestamp, page_url FROM {db_name}.{hudi_events_cow_table} ORDER BY event_id").show(truncate=False)
print("Target: Iceberg (in-place)")
spark.sql(f"SELECT event_id, user_id, event_type, event_timestamp, page_url FROM glue_iceberg.{db_name}.{iceberg_cow_inplace} ORDER BY event_id").show(truncate=False)

Output:

Source: Hudi COW
+--------+--------+-----------+-------------------+-----------------+
|event_id|user_id |event_type |event_timestamp |page_url |
+--------+--------+-----------+-------------------+-----------------+
|EVT_001 |USER_101|page_view |2024-04-01 08:15:00|/home |
|EVT_002 |USER_102|add_to_cart|2024-04-01 09:31:00|/products/item-42|
|EVT_003 |USER_103|purchase |2024-04-02 10:45:00|/checkout |
|EVT_004 |USER_101|page_view |2024-04-02 14:20:00|/blog |
|EVT_005 |USER_104|signup |2024-04-03 11:01:00|/welcome |
+--------+--------+-----------+-------------------+-----------------+
Target: Iceberg (in-place)
+--------+--------+-----------+-------------------+-----------------+
|event_id|user_id |event_type |event_timestamp |page_url |
+--------+--------+-----------+-------------------+-----------------+
|EVT_001 |USER_101|page_view |2024-04-01 08:15:00|/home |
|EVT_002 |USER_102|add_to_cart|2024-04-01 09:31:00|/products/item-42|
|EVT_003 |USER_103|purchase |2024-04-02 10:45:00|/checkout |
|EVT_004 |USER_101|page_view |2024-04-02 14:20:00|/blog |
|EVT_005 |USER_104|signup |2024-04-03 11:01:00|/welcome |
+--------+--------+-----------+-------------------+-----------------+

We can see under the Iceberg table location only Iceberg metadata has been generated. These point to the source Hudi table data files.

Code:

list_table_files(iceberg_cow_inplace, "COW Iceberg --- AFTER add_files (note metadata/ folder)", verbose=True)

Output:

s3://demoblogiceberg-bdb5001/hudi_to_iceberg_blog/events_iceberg_cow_inplace/ [COW Iceberg — AFTER add_files (note metadata/ folder)]
└── metadata/ (5 obj) <-- Iceberg metadata layer (metadata.json, manifest lists, manifests)
├── 00000.....metadata.json (1.3 KB) <-- Iceberg table metadata (schema, snapshots)
├── 00001.....metadata.json (2.0 KB) <-- Iceberg table metadata (schema, snapshots)
├── 00002.....metadata.json (3.0 KB) <-- Iceberg table metadata (schema, snapshots)
├── snap-7577.....avro (4.4 KB) <-- Iceberg manifest list (snapshot -> manifests)
└── stage-223...-manifest.....avro (6.7 KB) <-- Iceberg manifest (lists data files)
note: Iceberg metadata/ present but no local data/ folder
-> in-place migration: data files remain registered in place at the source (Hudi) location; no data copied
SUMMARY: 0 base · 0 log · 5 meta · 5 files · 17.4 KB
.hoodie/: none metadata/ (Iceberg): present

Migrate MoR to Iceberg

For the MoR table, we compact and clean the Hudi source first, then register the compacted files and validate the result.

Create the target Iceberg table

Code:

spark.sql(f"""
CREATE TABLE glue_iceberg.{db_name}.{iceberg_mor_inplace} (
event_id STRING,
user_id STRING,
event_type STRING,
event_timestamp TIMESTAMP,
page_url STRING,
year INT,
month INT,
day INT
)
USING iceberg
PARTITIONED BY (year, month, day)
LOCATION 's3://{bucket_name}/{db_name}/{iceberg_mor_inplace}/'
""")

Compact the MoR table: merge delta logs into base Parquet files

Check files listing for the Hudi table before the CLEAN operation:

Code:

list_table_files(hudi_events_mor_table, "MOR --- BEFORE COMPACT+CLEAN")

Output:

s3://demoblogiceberg-bdb5001/hudi_to_iceberg_blog/events_hudi_mor/ [MOR — BEFORE COMPACT+CLEAN]
├── .hoodie/ (50 obj) <-- Hudi metadata (timeline, schema, indexes)
│ ├── .......trimmed
└── year=2024/month=5/
├── day=10/
│ ├── .hoodie_partition_metadata (96 B) <-- Hudi partition marker
│ ├── 7d5ce247.....20261011153110535.parquet (426.4 KB) <-- base Parquet file
│ └── .7d5ce247.....20261011153145862.log.1_1-164-788 (1.3 KB) <-- Hudi delta log file (MoR update, uncompacted)
├── day=11/
│ ├── .hoodie_partition_metadata (96 B) <-- Hudi partition marker
│ └── f9b8147e.....20261011153110535.parquet (426.4 KB) <-- base Parquet file
└── day=12/
├── .hoodie_partition_metadata (96 B) <-- Hudi partition marker
├── 3f0b5ad4.....20261011153110535.parquet (426.4 KB) <-- base Parquet file
├── .3f0b5ad4.....20261011153145862.log.1_0-164-787 (1.3 KB)
└── .3f0b5ad4.....20261011153215018.log.1_0-192-901 (1.1 KB) <-- Hudi delta log file (MoR update, uncompacted)
note: year=2024/month=5/day=10/ has 1 base + 1 log file(s) -> uncompacted MoR updates
note: year=2024/month=5/day=12/ has 1 base + 2 log file(s) -> uncompacted MoR updates
SUMMARY: 3 base · 3 log · 53 meta · 59 files · 1.5 MB
.hoodie/: present metadata/ (Iceberg): none

Trigger COMPACTION scheduling on the MoR table with the delta-commit and age thresholds set to their minimum, so any file slice with pending log files is included in the plan and merged back into its base Parquet file.

Code:

# Schedule compaction
spark.sql(f"""
CALL spark_catalog.system.run_compaction(
table => '{db_name}.{hudi_events_mor_table}',
op => 'schedule',
options =>
'hoodie.compact.inline.max.delta.commits=1,
hoodie.compact.inline.max.delta.seconds=0'
)
""").show(truncate=False)

Output:

+-----------------+--------------+---------+
|timestamp |operation_size|state |
+-----------------+--------------+---------+
|20261011154522819|2 |REQUESTED|
+-----------------+--------------+---------+

Execute the previously scheduled compaction plan to merge the pending log files into their base Parquet files. The REQUESTED instant produced by the schedule step transitions to COMPLETED, and the table is left with base Parquet files only.

Code:

# Execute compaction
spark.sql(f"""
CALL spark_catalog.system.run_compaction(
table => '{db_name}.{hudi_events_mor_table}',
op => 'run'
)
""").show(truncate=False)

Output:

+-----------------+--------------+---------+
|timestamp |operation_size|state |
+-----------------+--------------+---------+
|20261011154522819|2 |COMPLETED|
+-----------------+--------------+---------+

Run Hudi CLEAN to remove old file versions and log files

Code:

spark.sql(f"""
CALL spark_catalog.system.run_clean(
table => '{db_name}.{hudi_events_mor_table}',
clean_policy => 'KEEP_LATEST_FILE_VERSIONS',
file_versions_retained => 1
)
""").show(truncate=False)

Output:

+-----------------+--------------------+-------------------+-------------------------+-----------------------+-------+
|start_clean_time |time_taken_in_millis|total_files_deleted|earliest_commit_to_retain|bootstrap_part_metadata|version|
+-----------------+--------------------+-------------------+-------------------------+-----------------------+-------+
|20261011154552026|345 |5 | |{} |2 |
+-----------------+--------------------+-------------------+-------------------------+-----------------------+-------+

Code:

list_table_files(hudi_events_mor_table, "MOR --- AFTER COMPACT+CLEAN")

Output:

s3://demoblogiceberg-bdb5001/hudi_to_iceberg_blog/events_hudi_mor/ [MOR — AFTER COMPACT+CLEAN]
├── .hoodie/ (69 obj) <-- Hudi metadata (timeline, schema, indexes)
│ ├── .......trimmed
└── year=2024/month=5/
├── day=10/
│ ├── .hoodie_partition_metadata (96 B) <-- Hudi partition marker
│ └── 7d5ce247.....20261011154522819.parquet (426.3 KB) <-- base Parquet file
├── day=11/
│ ├── .hoodie_partition_metadata (96 B) <-- Hudi partition marker
│ └── f9b8147e.....20261011153110535.parquet (426.4 KB) <-- base Parquet file
└── day=12/
├── .hoodie_partition_metadata (96 B) <-- Hudi partition marker
└── 3f0b5ad4.....20261011154522819.parquet (426.1 KB) <-- base Parquet file
SUMMARY: 3 base · 0 log · 72 meta · 75 files · 1.7 MB
.hoodie/: present metadata/ (Iceberg): none

Register compacted Parquet files into Iceberg with add_files

Code:

spark.sql(f"""
CALL glue_iceberg.system.add_files(
source_table => 'parquet.`s3://{bucket_name}/{db_name}/{hudi_events_mor_table}/`',
table => 'glue_iceberg.{db_name}.{iceberg_mor_inplace}'
)
""").show(truncate=False)

Output:

+-----------------+-----------------------+
|added_files_count|changed_partition_count|
+-----------------+-----------------------+
|3 |NULL |
+-----------------+-----------------------+

Refresh the Hudi table to invalidate Spark’s cached metadata and file listings, so subsequent queries re-read the post-compaction state from the catalog and storage instead of returning stale pre-compaction results.

Code:

spark.sql(f"REFRESH TABLE {db_name}.{hudi_events_mor_table}")

Validate: compare Hudi MoR and Iceberg (in-place)

Code:

print("Source: Hudi MOR")
spark.sql(f"SELECT event_id, user_id, event_type, event_timestamp, page_url FROM {db_name}.{hudi_events_mor_table} ORDER BY event_id").show(truncate=False)
print("Target: Iceberg (in-place)")
spark.sql(f"SELECT event_id, user_id, event_type, event_timestamp, page_url FROM glue_iceberg.{db_name}.{iceberg_mor_inplace} ORDER BY event_id").show(truncate=False)

Output:

Source: Hudi MOR
+--------+--------+-----------+-------------------+-----------------+
|event_id|user_id |event_type |event_timestamp |page_url |
+--------+--------+-----------+-------------------+-----------------+
|EVT_001 |USER_201|page_view |2024-05-10 07:00:00|/home |
|EVT_002 |USER_202|add_to_cart|2024-05-10 08:16:00|/products/item-99|
|EVT_003 |USER_203|purchase |2024-05-11 09:30:00|/checkout |
|EVT_004 |USER_201|page_view |2024-05-11 12:00:00|/account |
|EVT_005 |USER_204|signup |2024-05-12 10:31:00|/welcome |
+--------+--------+-----------+-------------------+-----------------+
Target: Iceberg (in-place)
+--------+--------+-----------+-------------------+-----------------+
|event_id|user_id |event_type |event_timestamp |page_url |
+--------+--------+-----------+-------------------+-----------------+
|EVT_001 |USER_201|page_view |2024-05-10 07:00:00|/home |
|EVT_002 |USER_202|add_to_cart|2024-05-10 08:16:00|/products/item-99|
|EVT_003 |USER_203|purchase |2024-05-11 09:30:00|/checkout |
|EVT_004 |USER_201|page_view |2024-05-11 12:00:00|/account |
|EVT_005 |USER_204|signup |2024-05-12 10:31:00|/welcome |
+--------+--------+-----------+-------------------+-----------------+

Code:

list_table_files(iceberg_mor_inplace, "MOR Iceberg --- AFTER add_files (note metadata/ folder)", verbose=True)

Output:

s3://demoblogiceberg-bdb5001/hudi_to_iceberg_blog/events_iceberg_mor_inplace/ [MOR Iceberg — AFTER add_files (note metadata/ folder)]
└── metadata/ (5 obj) <-- Iceberg metadata layer (metadata.json, manifest lists, manifests)
├── 00000.....metadata.json (1.3 KB) <-- Iceberg table metadata (schema, snapshots)
├── 00001.....metadata.json (2.0 KB) <-- Iceberg table metadata (schema, snapshots)
├── 00002.....metadata.json (3.0 KB) <-- Iceberg table metadata (schema, snapshots)
├── snap-5097.....avro (4.4 KB) <-- Iceberg manifest list (snapshot -> manifests)
└── stage-254...-manifest.....avro (6.7 KB) <-- Iceberg manifest (lists data files)
note: Iceberg metadata/ present but no local data/ folder
-> in-place migration: data files remain registered in place at the source (Hudi) location; no data copied
SUMMARY: 0 base · 0 log · 5 meta · 5 files · 17.4 KB
.hoodie/: none metadata/ (Iceberg): present

Option 2: Migrate Hudi tables to Iceberg with the Apache XTable sync tool

Apache XTable (Incubating) is an open-source interoperability layer that translates metadata between Apache Hudi, Apache Iceberg, and Delta Lake without copying data. Its sync utility supports both one-time conversion and ongoing incremental synchronization, enabling parallel access to source and target formats during migration. Because it ships as a self-contained Java process with no managed-service dependency, you can run it anywhere a JVM is available: a developer laptop for one-off conversions, an Amazon Elastic Container Service (Amazon ECS) or Amazon Elastic Kubernetes Service (Amazon EKS) container, or an AWS Lambda function, triggered on a schedule through Amazon EventBridge or on an event such as a new Hudi commit.

XTable’s sync utility does two things:

  1. First run – performs the initial in-place migration of a Hudi table to Iceberg.
  2. Subsequent runs – keep the Iceberg metadata in sync with the source table as it continues to receive writes.

Compile xtable-utilities following the instructions in the Apache XTable GitHub repository and copy xtable-utilities/target/xtable-utilities_2.12-0.5.0-SNAPSHOT-bundled.jar into the current working directory.

Migrate MoR to Iceberg

Note: When running the XTable sync tool on a MoR table, the utility only reads the base Parquet files and doesn’t process the delta log files. As a result, the generated Iceberg metadata reflects only the Hudi read-optimized view, meaning any recent updates or deletes stored in delta logs will be missing. To avoid data loss, always run compaction on the MoR table before executing the sync tool (for example, similar run_compaction commands as for the add_files example). Unlike add_files, however, there is no need to run CLEAN beforehand: XTable doesn’t scan the table location file by file, but builds the Iceberg manifests from Hudi’s own metadata, so it already knows which Parquet files belong to the current file slices and ignores superseded versions automatically.

Configure Apache XTables Configuration files.

Create the datasetConfig.yaml file containing indications about the dataset(s) to convert with the following content:

sourceFormat: HUDI
targetFormats:
  - ICEBERG
datasets:
  - tableBasePath: s3://YOUR_BUCKET/hudi_to_iceberg_blog/events_hudi_mor/
    tableName: events_hudi_mor_iceberg_xtable
    namespace: hudi_to_iceberg_blog
    partitionSpec: year:VALUE,month:VALUE,day:VALUE

Create the glueDataCatalog.yaml file containing Iceberg catalog (AWS Glue Data Catalog) settings with the following content:

catalogImpl: org.apache.iceberg.aws.glue.GlueCatalog
catalogName: glue
catalogOptions:
  warehouse: s3://YOUR_BUCKET/warehouse/
  catalog-impl: org.apache.iceberg.aws.glue.GlueCatalog
  io-impl: org.apache.iceberg.aws.s3.S3FileIO

Run the conversion

export AWS_DEFAULT_REGION=us-east-1

java -jar incubator-xtable/xtable-utilities/target/xtable-utilities_2.12-0.5.0-SNAPSHOT-bundled.jar \
-d datasetConfig.yaml \
-i glueDataCatalog.yaml

CLI options (from --help)

Flag Long form Description
-d --datasetConfig Path to the dataset configuration YAML (required)
-i --icebergCatalogConfig Path to the Iceberg catalog config YAML
-c --convertersConfig Override converter configs
-p --hadoopConfig Extra Hadoop config XML
-m --continuousMode Run on a scheduled loop
-t --continuousModeInterval Loop interval in seconds (with -m)

Verify the result

% aws glue get-table --database-name hudi_to_iceberg_blog \
--name events_hudi_mor_iceberg_xtable \
--query 'Table.{Name:Name,Type:Parameters.table_type,MetaLoc:Parameters.metadata_location}'

{
  "Name": "events_hudi_mor_iceberg_xtable",
  "Type": "ICEBERG",
  "MetaLoc": "s3://YOUR_BUCKET/hudi_to_iceberg_blog/events_hudi_mor/metadata/00002-a88318ba-ad13-4a0c-85a8-d595b53e9a89.metadata.json"
}

% aws s3 ls s3://YOUR_BUCKET/hudi_to_iceberg_blog/events_hudi_mor/metadata/
2026-09-22 16:26:18        648 00000-c71bcac6-3eee-4b98-875f-7562770db80b.metadata.json
2026-09-22 16:26:19       1940 00001-941c5622-95e3-41d7-942a-dabd69e561d1.metadata.json
2026-09-22 16:26:20       4293 00002-a88318ba-ad13-4a0c-85a8-d595b53e9a89.metadata.json
2026-09-22 16:26:20       8845 11adf6a4-58b9-4cc2-8cf0-317a7b43a8f7-m0.avro
2026-09-22 16:26:20       4493 snap-8409429281635613515-1-11adf6a4-58b9-4cc2-8cf0-317a7b43a8f7.avro
Amazon Athena console query returning five rows from the migrated Iceberg table

Figure 2: Validating the Apache XTable conversion by querying the migrated Iceberg table in Amazon Athena

Note: If you keep ingesting into the source Hudi table and want to keep the Iceberg table in sync, re-run the same conversion command. XTable automatically detects the previous execution and runs in incremental mode.

Migrate CoW to Iceberg

For the CoW table, update the datasetConfig.yaml with the CoW table path and name.

sourceFormat: HUDI
targetFormats:
  - ICEBERG
datasets:
  - tableBasePath: s3://YOUR_BUCKET/hudi_to_iceberg_blog/events_hudi_cow/
    tableName: events_hudi_mor_iceberg_xtable
    namespace: hudi_to_iceberg_blog
    partitionSpec: year:VALUE,month:VALUE,day:VALUE

The glueDataCatalog.yaml, conversion command, and verification steps remain the same as described in the MOR example.

Migrate Hudi tables to Iceberg with full table migration

Full table migration (also called shadow migration) reads all data from Hudi and writes it into a brand-new Iceberg table. This approach:

  • Allows schema and partition evolution (for example, switching to Iceberg hidden partitioning).
  • Produces a clean Iceberg table with no Hudi metadata dependencies.
  • Requires additional storage (data is copied)

Two options are demonstrated:

  • Option A: CTAS – a single-statement CREATE TABLE ... AS SELECT.
  • Option B: CREATE + INSERT – explicit table creation followed by data insertion.

Note: When performing a full table migration, the process is the same regardless of whether your source is a Hudi CoW or MoR table. This is because Spark reads from the Hudi real-time view by default, which reflects the latest table state. For CoW tables, this means reading the current base Parquet files. For MoR tables, the real-time view automatically merges the base Parquet files with any pending delta log files, ensuring all recent inserts, updates, and deletes are captured. As a result, the migrated Iceberg table will contain a complete and up-to-date snapshot of your data, with no additional compaction or cleanup steps required before migration.

We have taken a Hudi CoW table example to demonstrate the migration from Hudi CoW table to Iceberg table.

Prepare the column list for migration

Filter out Hudi internal metadata columns (_hoodie_*) and explicit partition columns to use Iceberg hidden partitioning.

Code:

# Build column list excluding Hudi metadata and explicit partition columns
all_columns_cow = spark.sql(f"SELECT * FROM {db_name}.{hudi_events_cow_table} LIMIT 1").columns
non_hoodie_columns_cow = [col for col in all_columns_cow if not col.startswith("_hoodie")]
partition_cols = ['year', 'month', 'day']
data_columns_cow = [col for col in non_hoodie_columns_cow if col not in partition_cols]
columns_to_select_cow = ", ".join(data_columns_cow)
print(f"Columns for COW migration: {columns_to_select_cow}")

Output:

Columns for COW migration: event_id, user_id, event_type, event_timestamp, page_url

Migrate CoW to Iceberg (full table / shadow migration)

We show two full-migration options: a single-statement CTAS and an explicit CREATE followed by INSERT.

Option A: CTAS (CREATE TABLE AS SELECT)

Single statement that creates the Iceberg table and populates it in one step. Here we also adopt Iceberg hidden partitioning by days(event_timestamp) – no need for explicit year/month/day columns.

Code:

spark.sql(f"""
CREATE TABLE glue_iceberg.{db_name}.{iceberg_cow_full_ctas}
USING ICEBERG
PARTITIONED BY (days(event_timestamp))
LOCATION 's3://{bucket_name}/{db_name}/{iceberg_cow_full_ctas}/'
AS (SELECT {columns_to_select_cow} FROM {db_name}.{hudi_events_cow_table})
""")

Code:

# Verify CTAS migration
print("Iceberg COW (CTAS) - Full Migration")
spark.sql(f"SELECT * FROM glue_iceberg.{db_name}.{iceberg_cow_full_ctas} ORDER BY event_id").show(truncate=False)

Output:

Iceberg COW (CTAS) - Full Migration
+--------+--------+-----------+-------------------+-----------------+
|event_id|user_id |event_type |event_timestamp |page_url |
+--------+--------+-----------+-------------------+-----------------+
|EVT_001 |USER_101|page_view |2024-04-01 08:15:00|/home |
|EVT_002 |USER_102|add_to_cart|2024-04-01 09:31:00|/products/item-42|
|EVT_003 |USER_103|purchase |2024-04-02 10:45:00|/checkout |
|EVT_004 |USER_101|page_view |2024-04-02 14:20:00|/blog |
|EVT_005 |USER_104|signup |2024-04-03 11:01:00|/welcome |
+--------+--------+-----------+-------------------+-----------------+

Option B: CREATE + INSERT

Useful when you need more control over the target table schema or want to add table properties before loading data, such as sort order. It is also a good fit for very large source tables, because the load phase is a plain INSERT INTO that you can run partition by partition, giving you control over parallelism, resource usage, and resumability during the migration.

Code:

spark.sql(f"""
CREATE TABLE glue_iceberg.{db_name}.{iceberg_cow_full_create_insert} (
event_id STRING,
user_id STRING,
event_type STRING,
event_timestamp TIMESTAMP,
page_url STRING
)
USING iceberg
PARTITIONED BY (days(event_timestamp))
LOCATION 's3://{bucket_name}/{db_name}/{iceberg_cow_full_create_insert}/'
""")

Code:

spark.sql(f"""
INSERT INTO glue_iceberg.{db_name}.{iceberg_cow_full_create_insert}
SELECT {columns_to_select_cow}
FROM {db_name}.{hudi_events_cow_table}
""")

Code:

# Verify CREATE + INSERT migration
print("Iceberg COW (CREATE+INSERT) - Full Migration")
spark.sql(f"SELECT * FROM glue_iceberg.{db_name}.{iceberg_cow_full_create_insert} ORDER BY event_id").show(truncate=False)

Output:

Iceberg COW (CREATE+INSERT) - Full Migration
+--------+--------+-----------+-------------------+-----------------+
|event_id|user_id |event_type |event_timestamp |page_url |
+--------+--------+-----------+-------------------+-----------------+
|EVT_001 |USER_101|page_view |2024-04-01 08:15:00|/home |
|EVT_002 |USER_102|add_to_cart|2024-04-01 09:31:00|/products/item-42|
|EVT_003 |USER_103|purchase |2024-04-02 10:45:00|/checkout |
|EVT_004 |USER_101|page_view |2024-04-02 14:20:00|/blog |
|EVT_005 |USER_104|signup |2024-04-03 11:01:00|/welcome |
+--------+--------+-----------+-------------------+-----------------+

Full table migration of Hudi to Amazon S3 Tables

Create a new notebook following the same procedure described earlier, updating the configuration as shown in the following steps.

Configure the Spark session

Change <ACCOUNT_ID>, <REGION>, and <TABLE_BUCKET_NAME> to your S3 Tables bucket details.

Code:

%%configure
{
"glue_version": "5.1",
"worker_type": "G.1X",
"number_of_workers": 5,
"idle_timeout": 30,
"--datalake-formats": "hudi,iceberg",
"--conf": "spark.serializer=org.apache.spark.serializer.KryoSerializer --conf spark.kryo.registrator=org.apache.spark.HoodieSparkKryoRegistrar --conf spark.sql.extensions=org.apache.spark.sql.hudi.HoodieSparkSessionExtension,org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions --conf spark.sql.catalog.s3tablesbucket=org.apache.iceberg.spark.SparkCatalog --conf spark.sql.catalog.s3tablesbucket.catalog-impl=org.apache.iceberg.aws.glue.GlueCatalog --conf spark.sql.catalog.s3tablesbucket.glue.id=<ACCOUNT_ID>:s3tablescatalog/<TABLE_BUCKET_NAME> --conf spark.sql.catalog.s3tablesbucket.warehouse=arn:aws:s3tables:<REGION>:<ACCOUNT_ID>:bucket/<TABLE_BUCKET_NAME>"
}

Configuration variables

Code:

# ──────────────────────────────────────────────
# Source Hudi tables - created in previous notebook
# ──────────────────────────────────────────────
hudi_events_cow_table = "events_hudi_cow" # Copy-on-Write source
# ──────────────────────────────────────────────
# s3tables targets - Full table migration
# ──────────────────────────────────────────────
s3tables_cow_full = "events_s3tables_cow_full"
# ──────────────────────────────────────────────
# Infrastructure
# ──────────────────────────────────────────────
db_name = "hudi_to_iceberg_blog" # Glue Data Catalog database
namespace_name = "hudi_to_s3tables" # S3tables Catalog database

Create the S3 Tables namespace

Code:

spark.sql(f"""
CREATE NAMESPACE IF NOT EXISTS s3tablesbucket.{namespace_name}
""")

Full table migration with CREATE + INSERT

Let’s perform full migration to S3tables. We also implement Iceberg hidden partitioning during the migration.

Hudi CoW table example

Code:

spark.sql(f"""
CREATE TABLE s3tablesbucket.{namespace_name}.{s3tables_cow_full} (
event_id STRING,
user_id STRING,
event_type STRING,
event_timestamp TIMESTAMP,
page_url STRING
)
USING iceberg
PARTITIONED BY (days(event_timestamp))
""")

Code:

spark.sql(f"""
INSERT INTO s3tablesbucket.{namespace_name}.{s3tables_cow_full}
SELECT
event_id,
user_id,
event_type,
event_timestamp,
page_url
FROM {db_name}.{hudi_events_cow_table}
""")

Query the S3 Tables Iceberg table

Code:

spark.sql(f"""
SELECT * FROM s3tablesbucket.{namespace_name}.{s3tables_cow_full} ORDER BY event_id
""").show(truncate=False)

Output:

+--------+--------+-----------+-------------------+-----------------+
|event_id|user_id |event_type |event_timestamp |page_url |
+--------+--------+-----------+-------------------+-----------------+
|EVT_001 |USER_101|page_view |2024-04-01 08:15:00|/home |
|EVT_002 |USER_102|add_to_cart|2024-04-01 09:31:00|/products/item-42|
|EVT_003 |USER_103|purchase |2024-04-02 10:45:00|/checkout |
|EVT_004 |USER_101|page_view |2024-04-02 14:20:00|/blog |
|EVT_005 |USER_104|signup |2024-04-03 11:01:00|/welcome |
+--------+--------+-----------+-------------------+-----------------+

Clean up

To avoid incurring future charges and to clean up unused roles and policies, delete the resources you created.

  1. Clean up the S3 Tables tables and namespace (same Spark session configuration as for the S3 Tables section):
    spark.sql(f"DROP TABLE IF EXISTS s3tablesbucket.{namespace_name}.{s3tables_cow_full} PURGE")
    spark.sql(f"DROP NAMESPACE IF EXISTS s3tablesbucket.{namespace_name}")

  2. Clean up the tables and namespace created in the general S3 bucket (same Spark session configuration as for the S3 General buckets section):
    in_place_iceberg = [
        iceberg_cow_inplace,
        iceberg_mor_inplace,
        iceberg_cow_xtable,
        iceberg_mor_xtable,
    ]
    for t in in_place_iceberg:
        spark.sql(f"DROP TABLE IF EXISTS glue_iceberg.{db_name}.{t}")
    
    owned_iceberg = [
        iceberg_cow_full_ctas,
        iceberg_cow_full_create_insert,
        iceberg_mor_full_ctas,
        iceberg_mor_full_create_insert,
    ]
    for t in owned_iceberg:
        spark.sql(f"DROP TABLE IF EXISTS glue_iceberg.{db_name}.{t}")
    
    # --- Hudi tables ---
    hudi_tables = [
        hudi_events_cow_table,
        hudi_events_mor_table,
    ]
    for t in hudi_tables:
        spark.sql(f"DROP TABLE IF EXISTS {db_name}.{t}")
    
    spark.sql(f"DROP DATABASE IF EXISTS {db_name} CASCADE")

  3. On the Amazon S3 console, navigate to the database folder and delete it.
  4. In the AWS Glue console, under ETL jobs, select the created notebook and choose Actions, Delete job(s).
  5. In the IAM console, delete the role you created for the notebook.

Conclusion

This post outlined strategies for migrating Apache Hudi tables to Apache Iceberg on Amazon S3 and Amazon S3 Tables, enabling organizations to build a modern transactional data lake. Most of the migrations were performed from AWS Glue 5.1 notebooks with interactive sessions, with the exception of the Apache XTable path, which was executed as a standalone Java process from a local workstation to show that cross-format conversion doesn’t require a managed Spark environment and can run anywhere a JVM is available.

The migration process, whether through an in-place migration, a full table migration, or a combination of both, should be chosen based on a thorough analysis of the data architecture and the integration pipelines that read from and write to the table. Factors to weigh include performance requirements, cost, data freshness needs, and the acceptable downtime window during the cutover. The migration should follow well-defined phases that identify the data integration patterns and use cases in play, so the selected strategy aligns with the specific requirements of each table.

To get started, open the AWS Glue console and try the migration path that fits your tables. For more information about the procedures used in this post, see the Apache Iceberg Spark procedures documentation and the AWS Glue Developer Guide.

Note: Always run the migration end to end in a non-production environment first and validate the migrated Iceberg table against the source Hudi table before cutting production workloads over. We recommend preparing a validation runbook with queries that compare row counts per partition, aggregate values on key metrics, latest-record checks against the preCombine field, and sample point lookups on primary keys, and running it both immediately after the migration and again after each downstream pipeline is repointed at the Iceberg table. Keep the source Hudi table available until the validation runbook has passed on production traffic.


About the authors

Nitin Kumar

Nitin Kumar

Nitin is a Solutions Architect at AWS Industries. He partners with customers to transform their cloud journey through innovative, scalable solutions. In his free time, he likes to watch movies and spend time with his family.

Shubham Purwar

Shubham Purwar

Shubham is an AWS Analytics Specialist Solution Architect. He helps organizations unlock the full potential of their data by designing and implementing scalable, secure, and high-performance analytics solutions on the AWS platform. In his free time, Shubham loves to spend time with his family and travel around the world.

Anirudh Chawla

Anirudh Chawla

Anirudh is an AWS Analytics Specialist Solution Architect. He helps organizations empower businesses to harness their data effectively through AWS’s analytics platform. His interest lies in building highly available distributed systems.

Stefano Sandonà

Stefano Sandonà

Stefano is a Senior Big Data Specialist Solution Architect at AWS. Passionate about data, distributed systems, and security, he helps customers worldwide architect scalable and secure data platforms, with a particular focus on open table formats to build performant and optimized transactional data lakes.

Build a data foundation for agentic AI on AWS: From lakehouse to MCP

Post Syndicated from Adrien Lebret original https://aws.amazon.com/blogs/big-data/build-a-data-foundation-for-agentic-ai-on-aws-from-lakehouse-to-mcp/

Building a data foundation ready for agentic AI is becoming a priority for organizations deploying AWS. This foundation relies on a unified lakehouse and interoperability protocols like Model Context Protocol (MCP). You can move from prototype to production. Yet many teams struggle to know where to start.

According to Gartner, more than 40 percent of agentic AI projects will be canceled by 2027 for failing to deliver the expected value. While Gartner points to several contributing factors, we believe the root cause comes down to two things: a lack of governance and inconsistent data.

If you’re building a data platform for AI agents, you probably recognize four barriers. Your data is fragmented across silos. Your unstructured data is available but hard to use. Your agents and your systems lack a common way to communicate. Gaps in quality and governance weaken trust and create hallucinations.

Each barrier holds back agentic AI. Closing them requires rethinking your data foundation as a whole, rather than fixing pipelines one at a time.

In this post, we walk you through four pillars for building a data foundation on AWS that is ready for agentic AI.

Pillar 1: Building a unified lakehouse with zero-ETL

The foundation starts with where your data lives and how you query it.

Beyond the data lake and the data warehouse: The lakehouse as your foundation

Every data platform sits between two approaches. Data lakes offer flexible storage, open formats, and raw data preserved on Amazon Simple Storage Service (Amazon S3) at low cost, which suits data science and AI workloads. However, this flexibility often comes with weak governance. Data warehouses provide native ACID transactions, high-performance SQL, and strong governance, but they become rigid when handling growing volumes or unstructured data.

Amazon SageMaker Lakehouse combines both approaches without requiring a full migration. Your operational, analytical, and AI data live in one place. Amazon S3 Tables, a capability of Amazon S3, provides native, open-source Apache Iceberg support. You can read and write from Spark, Amazon Athena, Amazon EMR, or Amazon Redshift.

Three essential lakehouse capabilities for agentic AI

A lakehouse built for agents needs three capabilities. Zero-ETL ingestion removes the need to manage pipelines. A federated catalog gives you a unified view of tables across S3, Amazon Redshift, Snowflake, or Databricks. With query federation, you can interrogate multiple sources without duplicating data.

SELECT customer_id, sentiment_score FROM s3tables.sales_db.orders WHERE order_date > '2024-01-01';

Native zero-ETL integrations to feed the lakehouse

AWS Glue connectors bring in operational sources like Amazon Aurora, Amazon DynamoDB, and Amazon Relational Database Service (Amazon RDS). They also support SaaS sources including Salesforce, ServiceNow, and SAP. Streaming sources include Amazon Managed Streaming for Apache Kafka (Amazon MSK) and Amazon Kinesis. Raw data and vector embeddings land in the same governed foundation, ready for the next pillar: context engineering.

Amazon SageMaker Lakehouse architecture connecting operational, analytical, and AI data stores

Figure 1: Amazon SageMaker Lakehouse unifying data through zero-ETL ingestion and a federated catalog

Pillar 2: Context engineering for high-performing AI agents

A lakehouse makes data accessible, but agents also need curated, relevant context to act on it effectively. Large language models (LLMs) remain stateless, with a finite context window. Feeding an agent excessive data often backfires. Research on long-context models identifies a lost in the middle effect, where information placed away from the prompt’s start or end gets effectively ignored (Liu et al., 2023). Context engineering addresses this challenge through a context manager built on three components: knowledge bases, session state and history, and data tools.

Context manager coordinating knowledge bases, session state and history, and data tools

Figure 2: The context manager built on knowledge bases, session state and history, and data tools

For knowledge bases, AWS offers several vector store options, including Amazon OpenSearch, Amazon Aurora PostgreSQL, and Amazon Neptune. Amazon S3 Vectors, a capability of Amazon S3, stands out because raw data and indexed embeddings reside in the same governed lakehouse foundation. This means agents and business intelligence tools consume the same source of truth without duplicating data or managing a separate system.

The following snippet is illustrative pseudocode that shows the flow. Check the Amazon Bedrock Knowledge Bases API reference for the exact parameter names and model identifiers.

# Illustrative pseudocode: parameter names are simplified
bedrock_agent.create_knowledge_base(
    name="customer-context-kb",
    vector_store_configuration={
        "s3VectorsConfiguration": {
            "vectorBucketArn": "arn:aws:s3vectors:::my-vector-bucket"
        }
    },
    embedding_model_arn="arn:aws:bedrock:::foundation-model/amazon.titan-embed-text-v2"
)

Static knowledge covers only half the problem. Agentic memory preserves dynamic context across sessions through two tiers. Short-term memory holds raw session history. Long-term memory stores vectorized records.

Amazon Bedrock AgentCore memory, a capability of Amazon Bedrock AgentCore, automates this process with an extraction module. This module identifies key terms, such as a client name or project, in raw events. It writes them into long-term storage for reuse. The result includes personalization, conversation continuity, and fewer hallucinations.

Data tools complete the context manager. Rather than receiving everything in the prompt, an agent calls a tool to fetch only the curated data it needs, such as the result of a SQL query. These capabilities prepare agents before they start communicating with each other and with your systems. MCP, the topic of our next pillar, standardizes that tool access.

Amazon Bedrock AgentCore memory with short-term and long-term memory and an automatic extraction module

Figure 3: Amazon Bedrock AgentCore memory extracting key terms from raw events into short-term and long-term memory

Pillar 3: Multi-agent interoperability with MCP and open protocols

After agents can retrieve the right context, the next challenge is collaboration, both between agents and with existing systems. Multi-agent debate techniques, where models review and correct each other’s outputs, can help improve reliability compared to a single model (Du et al., 2023). Two open protocols address this need. Agent2Agent (A2A) handles agent-to-agent communication. Model Context Protocol (MCP) connects agents to your systems.

Agent-to-agent communication with open protocols

With A2A, agents collaborate over standard HTTP and JSON, without sharing memory or a direct connection. It supports long-running tasks. An agent handling a lengthy video processing job can report progress while an orchestrator decides whether to wait or reassign the task. Each agent publishes an agent card describing its capabilities, inputs, and outputs. Popular open-source agent orchestration frameworks can query this card before delegating work.

Connecting the agentic world to your systems with MCP

MCP standardizes how agents access your data and tools through three components. Resources expose read-only data. Tools run actions like SQL queries. Prompts provide reusable instructions.

Amazon Bedrock AgentCore Gateway, a capability of Amazon Bedrock AgentCore, centralizes this access. It connects to an AWS Lambda function, an API, or a SaaS integration like Salesforce. It also enforces authentication and audit logging in one place.

Semantic search and tool discovery

As your gateway grows, agents risk being overwhelmed by available tools. AgentCore Gateway addresses this with semantic search: agents query in natural language, and the gateway returns only the relevant, permission-scoped tools based on AWS Identity and Access Management (IAM) policies.

Pillar 4: Data and AI governance for trust and compliance

Agents now communicate and act through MCP, so the data they rely on must be trustworthy. Governance has become your true differentiator. Foundation models (FMs) are widely accessible, so your data and how you manage it are what set your agents apart. Amazon SageMaker Data Catalog addresses this need through three capabilities: discovery, governance, and collaboration.

Most enterprise data remains unstructured, with incomplete metadata. The catalog automatically generates summaries, glossaries, data lineage, and quality indicators for each dataset. This gives users confidence in the data before they connect an agent to it.

Governance follows a publish-and-subscribe model. Producers publish datasets, and consumers subscribe with access scoped to their needs, through full access, row-level filtering, or column-level filtering.

These workflows run through IAM and expose APIs, so teams can automate approval flows instead of managing access requests manually.

Amazon SageMaker Unified Studio brings producers, analysts, and data scientists into a shared environment. A built-in generative AI assistant translates natural language requests into SQL, Python, or visualization cells that teammates can run immediately. This turns data exploration into a shared, auditable notebook instead of disconnected scripts.

Together, these four pillars (lakehouse, context engineering, interoperability, and governance) form a foundation you can build at enterprise scale. You can find a full technical walkthrough in the recorded session video from AWS Summit Paris.

The four pillars of an agentic AI data foundation

Figure 4: Lakehouse, context engineering, interoperability, and governance as the four pillars of an agentic AI data foundation

Conclusion

In this post, we outlined a four-pillar framework for an AI-ready data foundation on AWS, designed around connected capabilities rather than patched individual pipelines. Amazon SageMaker Lakehouse addresses the fragmentation and silo barrier. It brings operational, analytical, and AI data into one governed foundation with S3 Tables and native Apache Iceberg support. Context engineering with Amazon S3 Vectors and Amazon Bedrock AgentCore memory tackles the second barrier: unstructured data that is technically accessible but not usable. It turns your unified data into knowledge and persistent memory that agents can act on, instead of overloading a context window.

After your agents have the right context, MCP and Amazon Bedrock AgentCore Gateway address the interoperability barrier. They give agents a secure, centralized way to reach your tools and systems. Semantic search keeps tool discovery manageable as your gateway grows. Finally, Amazon SageMaker Data Catalog closes the governance gap that erodes trust and can introduce hallucinations. Its discovery, publish-and-subscribe access, and lineage capabilities give you the traceability that agentic AI needs to run in production.

If you’re starting this journey, sequence matters. Get your lakehouse and zero-ETL ingestion right first, because every downstream pillar depends on having a single, governed source of truth. Then invest in context engineering before you scale to multi-agent orchestration. Agents that hallucinate or lose session context will only compound errors after they start communicating with each other through A2A or MCP.

Treat governance as a parallel track from day one, not a final checkpoint. Column- and row-level access controls are far easier to build in early than to retrofit later.

These pillars also apply to workloads such as media personalization, customer service automation, and fraud detection pipelines. In each, multiple agents need to share a consistent, trustworthy view of enterprise data.

To go deeper, watch the recorded session video from AWS Summit Paris for the full technical walkthrough. You can also explore the Amazon SageMaker Lakehouse documentation and the Amazon Bedrock AgentCore documentation for implementation details.


About the authors

Adrien Lebret

Adrien Lebret

Adrien is a Solutions Architect at Amazon Web Services since 2022, having started through the Tech U program. Specializing in the Media, Entertainment and Sports sectors, he works daily with French companies on their AI and cloud architecture projects.

Guillaume Marchand

Guillaume Marchand

Guillaume is a Principal Solutions Architect based in Paris, France. He joined Amazon in 2016 after working for a television broadcaster, where he managed the architecture of their OTT platform. In his current role, Guillaume supports major French media groups in their cloud initiatives.

Build a multi-team AI and analytics environment on Amazon SageMaker Unified Studio with Terraform

Post Syndicated from Harshi Surampalli original https://aws.amazon.com/blogs/big-data/build-a-multi-team-ai-and-analytics-environment-on-amazon-sagemaker-unified-studio-with-terraform/

Platform engineers who support data and AI teams face a recurring challenge: analytics, machine learning (ML), and AI developer teams each need different tools. When each team operates its own tools and infrastructure, governance becomes fragmented. Organizations face duplicated effort and limited collaboration. Data engineers, data scientists, and AI developers might all work with the same underlying data. Yet they navigate separate consoles, manage distinct AWS Identity and Access Management (IAM) configurations, and lack a shared view of each other’s work.

Amazon SageMaker Unified Studio brings these capabilities together in one governed workspace. Every practitioner gets access to the tools they need: SQL editors, JupyterLab notebooks, and the Amazon Bedrock IDE. At the same time, they share a common business data catalog, security model, and project structure, all governed centrally within Amazon SageMaker Unified Studio. Teams collaborate within projects, while access to data, compute, and development artifacts is managed centrally.

Setting up this kind of multi-team environment means coordinating IAM roles, blueprints, project profiles, and user onboarding on top of the initial domain configuration. New user roles and use cases might require enabling new blueprints and combining them into new project profiles to extend the functionality supported by the domain. To keep this repeatable and consistent, we use the Amazon SageMaker Unified Studio Terraform module to codify the entire setup. The module creates three purpose-built project profiles, one for each team, on a shared domain, plus an initial project to get you started. Creating the remaining per-team projects is a single additional sub-module block.

Consider a mid-size technology company with three teams that need cloud-based data and AI capabilities:

Team What they need Key AWS services
Data Analytics Query and transform data across Amazon Simple Storage Service (Amazon S3), Apache Spark jobs, and Amazon Redshift, build and orchestrate data pipelines, manage a data catalog Amazon SageMaker Lakehouse, Amazon Redshift Serverless, AWS Glue, Amazon Managed Workflows for Apache Airflow (MWAA)
Machine Learning Run experiments, train models, deploy endpoints Amazon SageMaker AI, MLflow, Amazon EMR Serverless
Generative AI Build chat agents, knowledge bases, prompt flows, and guardrails Amazon Bedrock

A common issue today is that customers don’t have a unified strategy to deploy and manage their infrastructure. The analytics team has a standalone Amazon Redshift cluster, the ML team provisions SageMaker notebooks ad hoc, and the generative AI team experiments with Bedrock through the console. Each team runs its own infrastructure. Because these environments are separate, there’s no shared data catalog, no consistent access control, and no central visibility into what’s running or what it costs.

The goal: a single unified environment where each team gets exactly the capabilities they need, with shared data access, consistent security, and infrastructure you define entirely as code.

Solution overview

We use the Amazon SageMaker Unified Studio Terraform module to create a single domain with three project profiles, one per team. A project profile is a collection of blueprints which are configurations used to create projects, while the domain provides shared governance, IAM roles, and networking.

Key module capabilities:

  • Dual provider: Uses both the AWS provider and AWS Cloud Control (AWSCC) provider for full Amazon SageMaker Unified Studio resource coverage.
  • Service role flexibility: All IAM roles are auto-created with least-privilege policies, or you can supply existing roles to be used by Amazon SageMaker Unified Studio.
  • Domain and project level access using AWS Identity and Access Management (IAM), single sign-on (SSO) with AWS IAM Identity Center or both.
  • KMS encryption: Optionally encrypt domain metadata with a customer-managed AWS Key Management Service (AWS KMS) key using kms_key_identifier.
  • Model governance: The domain module automatically provisions a model governance project for Generative AI administrators to be added to. Members of the project can enable or disable specific models accessible in the domain.
Single SageMaker Unified Studio domain with three project profiles sharing common IAM roles, VPC, and S3 storage

Figure 1: Multi-team Amazon SageMaker Unified Studio architecture

The Terraform module follows a layered architecture with four composable modules:

Layer 1: Domain module. Creates the domain, Tooling blueprint, IAM roles, and S3 bucket:

module "domain" {
  source     = "aws-ia/sagemaker-unified-studio/aws"
  domain_name = var.domain_name
  vpc_id      = vpc-xxx
  subnet_ids  =  ["subnet-xxx", "subnet-yyy", "subnet-zzz"]
  enable_sso  = var.enable_sso
}

Layer 2: Blueprint module. Enables individual blueprints on the domain using for_each:

module "blueprints" {
  source   = "aws-ia/sagemaker-unified-studio/aws//modules/blueprint"
  for_each = local.blueprint_configs

  domain_id      = module.domain.domain_id
  blueprint_name = each.value.blueprint_name
  regional_parameters = local.regional_parameters
  manage_access_role_arn = module.domain.manage_access_role_arn
  provisioning_role_arn  = module.domain.provisioning_role_arn
}

Layer 3: Project profile module. Composes blueprints into team-specific profiles:

module "sql_analytics_project_profile" {
  source    = "aws-ia/sagemaker-unified-studio/aws//modules/project-profile"
  domain_id = module.domain.domain_id
  name      = "SQL analytics"
  blueprints = local.sql_analytics_blueprint_config
  blueprint_dependencies = [for k, bp in module.blueprints : bp.entity_id]
  depends_on = [module.blueprints]
}

Layer 4: Project and Project membership module. Creates a project and assigns members:

module "project" {
  source             = "aws-ia/sagemaker-unified-studio/aws//modules/project"
  domain_id          = module.domain.domain_id
  project_name       = local.project_name
  project_profile_id =  concat(module.all_capabilities_project_profile, module.sql_analytics_project_profile, module.generative_ai_project_profile)[0].project_profile_id 
  depends_on = [module.create_project_from_project_profile_grant]
}
module "project_membership" {
  source = " aws-ia/sagemaker-unified-studio/aws//modules/project-membership"

  domain_id            = module.domain.domain_id
  project_id           = module.project[0].project_id
  project_owners       = var.project_owners
  project_contributors = var.project_contributors

  depends_on = [
    aws_datazone_user_profile.sso_users,
    aws_datazone_user_profile.iam_users,
    awscc_datazone_group_profile.sso_groups,
  ]
}

At a high level, the deployment mentioned in this post performs the following:

  1. Terraform creates the Amazon SageMaker Unified Studio domain with shared IAM roles and networking.
  2. Terraform enables all required blueprints on the domain (DataLake, RedshiftServerless, Bedrock services, EMR, and so on).
  3. Terraform composes three project profiles (one per team), selecting the appropriate blueprints and parameters.
  4. Terraform creates a project from the first available profile (All Capabilities profile).
  5. Project members (SSO users, SSO groups, IAM users, or IAM roles) are assigned as owners or contributors to the created project.

What each team gets

After deployment and teams are assigned to their respective projects, each team can:

  • Data Analytics team (SQL Analytics profile):
    • Query data across Amazon S3 and Amazon Redshift using SageMaker Lakehouse.
    • Manage a shared data catalog with AWS Glue.
    • Create and share SQL notebooks and dashboards.
  • Machine Learning team (All Capabilities profile):
    • Run ML experiments with MLflow integration.
    • Process data at scale with Amazon EMR Serverless.
    • Access all SQL analytics and generative AI capabilities.
    • Build end-to-end ML pipelines with Workflows.
  • Generative AI team (Generative AI profile):
    • Build chat agents and knowledge bases with Amazon Bedrock.
    • Create and test prompt flows and guardrails.
    • Evaluate model performance with Bedrock Evaluation.
    • Deploy serverless AI functions.

All three teams share the same governed domain, data catalog, IAM policies, and networking. This eliminates the silos that existed before. Team isolation is achieved by assigning users or groups to projects created from the appropriate project profile.

Prerequisites

Before you begin, verify the following:

  • An AWS account with permissions to create and manage Amazon DataZone, AWS Identity and Access Management (IAM), Amazon Simple Storage Service (Amazon S3), Amazon Elastic Compute Cloud (Amazon EC2), and Amazon Virtual Private Cloud (Amazon VPC) resources. See Changing permissions for an IAM user for guidance.
  • Terraform version >= 1.7.
  • AWS Command Line Interface (AWS CLI) configured with credentials that have access to the target account and AWS Region.
  • Amazon SageMaker Unified Studio available in your target Region.
  • AWS IAM Identity Center configured (required only if using SSO-based project membership). If using IAM-only membership, Identity Center isn’t required.

Solution walkthrough

We complete the setup in four steps:

  1. Clone the module repository.
  2. Configure the Terraform variables for each team.
  3. Apply the Terraform configuration.
  4. Verify the platform and onboard teams.

Step 1: Clone the repository

Clone the Amazon SageMaker Unified Studio Terraform module and navigate to the quick-setup example:

git clone https://github.com/aws-ia/terraform-aws-sagemaker-unified-studio.git
cd terraform-aws-sagemaker-unified-studio

The module directory structure:

Directory tree of the terraform-aws-sagemaker-unified-studio module repository

Figure 2: Directory structure of the Amazon SageMaker Unified Studio Terraform module

Change into the quick-setup example directory:

cd examples/quick-setup

Step 2: Configure the Terraform variables

Copy the example variables file and edit it:

cp terraform.tfvars.example terraform.tfvars

For our multi-team scenario, we enable all three project profiles:

# Domain configuration
domain_name        = "acme-ai-platform"
domain_description = "Multi-team AI and analytics domain"
aws_region         = "us-east-1"
environment        = "prod"

# Project configuration
project_name        = "analytics-pilot"
project_description = "Initial pilot project for the analytics team"

# Enable all three team profiles
enable_sql_analytics    = true   # Data Analytics team
enable_generative_ai    = true   # Generative AI team
enable_all_capabilities = true   # ML team (includes SQL + AI + ML + EMR)

# SSO user access
enable_sso = true
sso_users  = [
  "[email protected]"
]

# Project membership
project_owners = {
  sso_users = ["a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"]
}

project_contributors = {
  sso_groups = ["a1b2c3d4-5678-90ab-cdef-EXAMPLE22222"]
  iam_roles  = ["arn:aws:iam::123456789012:role/CI-CD-DeployRole"]
}

# Note: If your organization doesn't use Identity Center, set enable_sso = false and use iam_users and iam_roles instead. See "Adding IAM principals to projects" below. This is a one way door decision. If you change this later on the domain and all dependent resources need to be destroyed and recreated

# Optional: Use a specific VPC instead of the default
# vpc_id     = "vpc-0abc123def456"
# subnet_ids = ["subnet-0abc123", "subnet-0def456"]

Here’s what each profile creates:

Variable Team Blueprints enabled
enable_sql_analytics Data Analytics DataLake, LakehouseCatalog, RedshiftServerless
enable_generative_ai Generative AI BedrockChatAgent, BedrockEvaluation, BedrockFlow, BedrockFunction, BedrockGuardrail, BedrockKnowledgeBase, BedrockPrompt
enable_all_capabilities ML (full access) All of the preceding + EMR Serverless, EMR on EC2, MLExperiments, Workflows

Internally, the toggles build a dynamic map of blueprints that gets passed to the blueprint module’s for_each:

locals {
  blueprint_configs = merge(
    var.enable_generative_ai  ? { /* Bedrock blueprints */ } : {},
    var.enable_sql_analytics  ? { /* DataLake, Redshift, Lakehouse */ } : {},
    var.enable_all_capabilities ? { /* EMR, ML, Workflows + all above */ } : {},
  )
}

Network auto-discovery: If you don’t specify vpc_id and subnet_ids, the module automatically discovers and uses your default VPC and its subnets.

Customizing blueprint parameters: The quick-setup example uses recommended defaults. For production, you can customize Amazon Redshift capacity, Glue database names, or deployment modes in the sql_analytics_blueprint_config and generative_ai_blueprint_config locals in main.tf. For example, to increase Redshift Serverless max capacity:

"RedshiftServerless" = {
  deployment_mode = "ON_CREATE"
  parameter_overrides = {
    "redshiftMaxCapacity" = {
      value       = "1024"    # Increased from default 512
      is_editable = false
    }
  }
}

Step 3: Apply the Terraform configuration

Configure your AWS CLI credentials for the target account and Region, then:

  1. Run terraform init to download the modules and providers.
  2. Run terraform plan and review the output to verify:
    • An Amazon SageMaker Unified Studio domain will be created.
    • Three IAM roles will be created (domain execution, manage access, provisioning).
    • An S3 bucket for tooling storage will be created.
    • All selected blueprints will be enabled on the domain.
    • Three project profiles will be created (SQL Analytics, Generative AI, All Capabilities).
    • A project will be created from the first available profile.
    • Project memberships will be configured for SSO identities, IAM principals or both.
  3. Run terraform apply and allow the apply to complete.

Figure 3: Successful terraform apply output showing the domain URL, project ID, and project profile IDs

View the key outputs:

# Domain portal URL — share this with your teams
terraform output domain_url

# Project URL — direct link to the created project
terraform output project_url

# All enabled blueprints
terraform output blueprint_ids

# Project profile IDs (one per team)
terraform output project_profile_ids

# IAM role ARNs for auditing
terraform output domain_execution_role_arn
terraform output manage_access_role_arn
terraform output provisioning_role_arn

Step 4: Verify the platform and onboard teams

Verify the deployment. Confirm the environment is healthy before onboarding teams:

  1. Open the domain_url from the Terraform output and confirm the Amazon SageMaker Unified Studio portal loads, and you can sign in using a principal that was added to the project.
  2. In the portal, confirm the three project profiles (SQL Analytics, Generative AI, All Capabilities) appear under the domain.
  3. Confirm the initial project created by terraform apply is listed and project members can access the project interface.
  4. Cross-check the Terraform outputs (terraform output blueprint_ids, terraform output project_profile_ids) against the blueprints and profiles you expected.

Access the portal: Open the domain_url from the Terraform output. Any user added as an owner or member of the project can sign in immediately and access their project.

Create team-specific projects: The initial terraform apply creates one project. To create additional projects for each team, add more "project" sub-moduleblocks referencing different profiles:

module "genai_project" {
  source             = "aws-ia/sagemaker-unified-studio/aws//modules/project"
  domain_id          = module.domain.domain_id
  project_name       = "genai-team"
  project_profile_id = module.generative_ai_project_profile.project_profile_id
}

You can also create projects from the Amazon SageMaker Unified Studio portal using the available profiles.

Onboard additional users: To isolate teams, create separate projects using the appropriate project profiles as shown earlier, then add members (SSO users, SSO groups, IAM users, or IAM roles) to each project using the project_membership module. Each principal type can be used independently or in combination. This restricts each team to the capabilities defined by their project profile. For details on adding IAM principals, see the next section.

Adding IAM principals to projects

Amazon SageMaker Unified Studio uses project membership to control who can access a project’s resources (data, environments, and development artifacts). The Terraform module supports four principal types for project membership:

  • SSO users: Individual IAM Identity Center users.
  • SSO groups: IAM Identity Center groups (all members inherit access).
  • IAM users: Native IAM user ARNs.
  • IAM roles: IAM role ARNs (assumed by humans, services, or automation).

Project membership defines which principals are authorized to access a project. It also sets what actions they are allowed to perform as either project owners or contributors. When a principal is added to a project through project membership, they are automatically added to the domain membership list and are authorized to access the interface.

Why add IAM principals to projects?

While Identity Center users and groups cover most human access patterns, IAM principals unlock additional use cases:

Use Case Principal Type Example
Continuous integration and continuous delivery (CI/CD) pipeline deploys environments in a project IAM Role arn:aws:iam::123456789012:role/GitHubActionsDeployRole
Service account runs automated data pipelines IAM Role arn:aws:iam::123456789012:user/etl-service-account
Organization without Identity Center needs project access IAM User/Role Any IAM principal in the account

Configuration

The project_owners and project_contributors variables accept any combination of principal types:

project_owners = {
  sso_users  = ["[email protected]"]
  sso_groups = []
  iam_users  = ["arn:aws:iam::123456789012:user/platform-admin"]
  iam_roles  = ["arn:aws:iam::123456789012:role/DataPlatformLead"]
}

project_contributors = {
  sso_users  = []
  sso_groups = ["a1b2c3d4-5678-90ab-cdef-EXAMPLE22222"]
  iam_users  = ["arn:aws:iam::123456789012:user/data-engineer-1"]
  iam_roles  = ["arn:aws:iam::123456789012:role/CI-CD-DeploymentRole"]
}

Project members can be defined as owners or contributors. The AWS caller identity that runs this Terraform code is added as a project owner so that it has permission to manage project resources and update team membership. To know what permissions each of these roles have please refer to the full documentation here.

How the module registers principals

The module automatically creates the required domain-level profile for each principal before assigning membership. No manual pre-registration is needed. The module handles the full lifecycle.

IAM identity prerequisite: IAM roles and users must have the AWS managed SageMakerStudioUserIAMConsolePolicy (or equivalent) attached to access the Amazon SageMaker Unified Studio interface. This policy provides permissions for domain listing, project creation, and other portal operations. The module doesn’t automatically attach this policy to IAM roles.

Example: Granting a CI/CD pipeline access to a project

project_contributors = {
  iam_roles = ["arn:aws:iam::123456789012:role/GitHubActionsDeployRole"]
}

The pipeline role can now create and manage environments within the project scope, without domain-wide access.

Example: IAM-only project membership

Organizations that don’t use Identity Center can manage project membership entirely through IAM principals by setting enable_sso = false in the domain module.

enable_sso = false

project_owners = {
  iam_roles = ["arn:aws:iam::123456789012:role/PlatformAdmin"]
}

project_contributors = {
  iam_users = [
    "arn:aws:iam::123456789012:user/analyst-1",
    "arn:aws:iam::123456789012:user/analyst-2"
  ]
  iam_roles = [
    "arn:aws:iam::123456789012:role/DataScientistRole"
  ]
}

Note: Currently, only IAM principals within the same AWS account as the domain can access the Amazon SageMaker Unified Studio portal. Cross-account IAM role access might be limited. Verify cross-account support in your Region before relying on it for production access patterns.

Additional considerations

As you move this setup toward production, consider the following areas.

Scaling to multiple environments

For production readiness, deploy separate domains for development, staging, and production using Terraform workspaces or separate state files:

# Development
terraform workspace new dev
terraform apply -var="domain_name=acme-ai-dev" -var="environment=dev"

# Production
terraform workspace new prod
terraform apply -var="domain_name=acme-ai-prod" -var="environment=prod"

Cost management

The base infrastructure (domain, IAM roles, S3 bucket) has minimal ongoing costs. Primary charges occur when teams create and use environments:

  • Redshift Serverless: Pay per RPU-hour when queries are running.
  • EMR Serverless: Pay per vCPU and memory per second.
  • Bedrock: Pay per input and output token.
  • S3: Standard storage pricing.

Use the parameter_overrides in blueprint configurations to set capacity limits (for example, redshiftMaxCapacity) and control costs.

Security and governance

The module creates least-privilege service roles by default. For additional permissions, attach custom policies to the user role:

user_role_policy_arns = [
  "arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess",
  "arn:aws:iam::123456789012:policy/CustomBedrockPolicy"
]

You can also configure VPC endpoints for private connectivity and enable AWS CloudTrail for audit logging of all Amazon DataZone API calls.

DevOps best practices

  1. Version control: Store configurations in a code repository with automated CI/CD pipelines.
  2. Module registry: Publish organization-specific module compositions to a private Terraform registry.

Cleanup

To destroy all resources:

# Empty the S3 bucket first
terraform output s3_bucket_name
aws s3 rm s3://BUCKET_NAME --recursive

# Destroy all resources
terraform destroy

Warning: This deletes all resources including the domain, projects, and any data stored in the S3 bucket. Additionally, extra resources created manually within the console won’t be affected by this terraform destroy.

Conclusion

In this post, we walked through a real-world scenario: building a multi-team AI and analytics unified environment where data analysts, ML engineers, and generative AI developers each get tailored capabilities on a shared, governed domain. Terraform provisions and manages the full set of Amazon SageMaker Unified Studio resources, including the domain, blueprints, project profiles, and an initial project. As your needs grow, you can extend the configuration by adding projects per team through the project sub-module.

Key benefits of this approach:

  • Team-specific profiles: Each team gets exactly the blueprints they need, nothing more.
  • Shared governance: One domain, one set of IAM roles, one data catalog, consistent policies.
  • Infrastructure as Code: Repeatable, auditable, version-controlled deployments.
  • Auto-discovery: Minimal configuration required; VPC, subnets, and instance details are discovered automatically.
  • Scalable: Add teams, environments, or accounts by extending the same Terraform configuration.
  • Flexible membership: Add SSO users, IAM users, IAM roles, or any combination as project members.

The Terraform module and examples are available in the Amazon SageMaker Unified Studio Terraform module repository.

Have questions or feedback? Leave us a comment or open an issue in the GitHub repository.

Additional resources


About the authors

Harshi Surampalli

Harshi Surampalli

Harshi is a Senior Technical Account Manager at AWS supporting Financial Services customers, with deep expertise in hybrid cloud architectures and infrastructure modernization. She helps enterprises optimize their AWS environments, strengthen operational resilience, and navigate complex migrations. Outside work, she enjoys reading, gardening, and spending time with family.

Samuel Ouvrard

Samuel Ouvrard

Samuel is a Solutions Architect at AWS Canada who works with enterprise and ISV customers across the financial services and adtech sectors. He has built deep expertise in Terraform by creating and maintaining open-source Terraform modules that help customers deploy AWS services through Infrastructure as Code, simplifying what were previously complex, manual setups into repeatable, version-controlled deployments.

Nathan Yee

Nathan Yee

Nathan is a Specialist Solutions Architect at Amazon Web Services (AWS) with a focus on Agentic Data & Analytics services. He helps customers architect scalable data platforms and optimize their data processing workloads.

How Samsung Ads federated Snowflake Iceberg tables using Amazon Cognito

Post Syndicated from Balaji Selva Rajan original https://aws.amazon.com/blogs/big-data/how-samsung-ads-federated-snowflake-iceberg-tables-using-amazon-cognito/

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.

Query path from Amazon Athena through AWS Lake Formation and an 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:

  1. A user or application submits a SQL query in Amazon Athena that references a federated table in the Snowflake catalog.
  2. Athena delegates catalog resolution and permission checks to Lake Formation, which evaluates fine-grained access controls on the federated catalog entry.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. The connection returns the metadata to Lake Formation, which generates temporary, scoped Amazon S3 credentials and passes them to Athena.
  8. 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.

  1. Choose Launch Stack.

Launch Stack

  1. In the Region selector, confirm the Region matches your Snowflake account Region, then choose Next.
  2. For Stack name, keep snowflake-federation-oauth. Leave all parameters at their default values, then choose Next.
  3. On Configure stack options, keep the defaults and choose Next.
  4. On Review and create, select I acknowledge that AWS CloudFormation might create IAM resources with custom names, then choose Submit.
  5. 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
CloudFormation Outputs tab listing the six stack outputs used in later steps

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.

  1. On the Outputs tab, copy the value of VerifyAudClaimCommand.
  2. Choose the AWS CloudShell icon on the console navigation bar, as shown in the following screenshot.
  3. 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.
Decoded access token payload showing the injected aud claim and the snowflake/catalog.read scope

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.

  1. 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.

  1. 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;
  1. 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.

  1. 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.

{
  "Sid": "AllowSnowflakeVolumeSession",
  "Effect": "Allow",
  "Principal": {
    "AWS": "arn:aws:sts::<account-id>:assumed-role/<external-volume-role>/snowflake"
  },
  "Action": [
    "kms:Decrypt",
    "kms:DescribeKey",
    "kms:GenerateDataKey"
  ],
  "Resource": "*"
}

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.

  1. Using an IAM user with long-term access keys, generate a federation token:
aws sts get-federation-token --name snowflake-privatelink --duration-seconds 900 --profile <iam-user-profile>

The token appears in the SQL statement, so Snowflake keeps it in query history. The 15-minute duration limits how long it stays valid.

  1. In your Snowflake worksheet, pass your AWS account ID and the full JSON output from the previous command:
USE ROLE ACCOUNTADMIN;
SELECT SYSTEM$AUTHORIZE_PRIVATELINK('<aws-account-id>', '<full-federation-token-json>');

The output confirms that Snowflake authorized PrivateLink for your account.

Snowflake worksheet output confirming PrivateLink authorization for the AWS account

Figure 4: Snowflake output confirming PrivateLink authorization

  1. 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.

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:

  1. Choose Launch Stack.

Launch Stack

  1. Confirm the Region selector matches your Snowflake account Region, then choose Next.
  2. 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.

  1. Choose Next, keep the defaults on Configure stack options, and choose Next.
  2. On Review and create, select I acknowledge that AWS CloudFormation might create IAM resources with custom names, then choose Submit.
  3. 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.

  1. 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>'
  1. 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.
aws lakeformation register-resource \
  --resource-arn "$S3_LOCATION" \
  --role-arn "$LFROLE" --with-federation
  1. Create the AWS Glue connection. This writes the definition to a file, then creates it.
cat > conn.json <<JSON
{
  "Name": "$CONN",
  "Description": "Snowflake Iceberg REST catalog through AWS Cognito.",
  "ConnectionType": "ICEBERGRESTCATALOG",
  "ConnectionProperties": {
    "INSTANCE_URL": "$WORKSPACE_URL",
    "ROLE_ARN": "$LFROLE",
    "CATALOG_CASING_FILTER": "UPPERCASE_ONLY"
  },
  "AuthenticationConfiguration": {
    "AuthenticationType": "OAUTH2",
    "SecretArn": "$SECRET_ARN",
    "OAuth2Properties": {
      "OAuth2GrantType": "CLIENT_CREDENTIALS",
      "TokenUrl": "$TOKEN_URL",
      "OAuth2ClientApplication": { "UserManagedClientApplicationClientId": "$CLIENT_ID" },
      "TokenUrlParametersMap": { "scope": "$SCOPE" }
    }
  },
  "PhysicalConnectionRequirements": {
    "SubnetId": "$SUBNET",
    "SecurityGroupIdList": ["$SG"]
  }
}
JSON

aws glue create-connection --connection-input file://conn.json
  1. 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.

aws glue delete-connection --connection-name $CONN
  1. Register the connection with Lake Formation using privileged access. A federated catalog can only use a connection registered this way.
aws lakeformation register-resource \
  --resource-arn arn:aws:glue:$REGION:$ACCT:connection/$CONN \
  --role-arn "$LFROLE" --with-federation --with-privileged-access
  1. Create the federated catalog, then confirm the tables surface through it.
aws glue create-catalog --name $CATALOG --catalog-input '{
  "FederatedCatalog": {"Identifier": "'"$REMOTE_DB"'", "ConnectionName": "'"$CONN"'"},
  "CreateDatabaseDefaultPermissions": [],
  "CreateTableDefaultPermissions": []
}'

aws glue get-tables --catalog-id $ACCT:$CATALOG --database-name $SCHEMA --query 'TableList[].Name'
  1. 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.
aws lakeformation grant-permissions \
  --principal DataLakePrincipalIdentifier="$QUERY_PRINCIPAL" \
  --resource '{"Database":{"CatalogId":"'"$ACCT:$CATALOG"'","Name":"'"$SCHEMA"'"}}' \
  --permissions DESCRIBE

aws lakeformation grant-permissions \
  --principal DataLakePrincipalIdentifier="$QUERY_PRINCIPAL" \
  --resource '{"Table":{"CatalogId":"'"$ACCT:$CATALOG"'","DatabaseName":"'"$SCHEMA"'","TableWildcard":{}}}' \
  --permissions SELECT DESCRIBE

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

  1. 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.
  2. 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
  1. 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.

Amazon Athena query results returning 10 rows from a Snowflake-managed Iceberg table

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

  1. On the AWS Lake Formation console, choose Catalogs, select your federated catalog, then choose Actions and Delete catalog.
  2. 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.
SG='<GlueConnectionSecurityGroupId from Step 5>'
aws ec2 describe-network-interfaces \
  --filters "Name=group-id,Values=$SG" "Name=description,Values=*ICEBERGRESTCATALOG" \
  --query 'NetworkInterfaces[].NetworkInterfaceId' --output text | tr '\t' '\n' > glue-enis.txt

cat glue-enis.txt
  1. 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.
aws lakeformation deregister-resource --resource-arn arn:aws:glue:<region>:<account-id>:connection/<glue-connection-name>
aws glue delete-connection --connection-name <glue-connection-name>
  1. 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
  1. On the Lake Formation console, under Administration, choose Data lake locations, select the registered Amazon S3 location, then choose Actions and Remove.
  1. 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

  1. 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;
  1. 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:
aws sts get-federation-token --name snowflake-privatelink --duration-seconds 900 --profile <iam-user-profile>
USE ROLE ACCOUNTADMIN;
SELECT SYSTEM$REVOKE_PRIVATELINK('<aws-account-id>', '<full-federation-token-json>');
  1. Confirm the account is no longer authorized:
SELECT SYSTEM$GET_PRIVATELINK_AUTHORIZED_ENDPOINTS();

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.

To get started, see Catalog federation to remote Iceberg catalogs and Federate to Snowflake Iceberg Catalog in the AWS Lake Formation Developer Guide, and External OAuth overview in the Snowflake documentation. If you have feedback about this post, submit comments in the Comments section.

 


About the authors

Ajay Gunasekaran

Ajay Gunasekaran

Ajay is an ML Platform Engineer at Samsung Ads. He has been instrumental in building the ML platform across the Snowflake and AWS ecosystems and is passionate about making complex infrastructure simple, reliable, and easy to use. Curious by nature, he enjoys learning, sharing ideas, and solving challenging problems.

Balaji Selva Rajan

Balaji Selva Rajan

Balaji is a Technical Account Manager at AWS, specializing in Cloud Operations, Storage, and Data Analytics. He helps customers to run their workloads efficiently on AWS and is particularly interested in turning recurring customer problems into repeatable, reusable patterns.

David Zhang

David Zhang

David is a Senior Specialist Solutions Architect specializing in Data & AI at AWS, where he focuses on designing and implementing open lakehouse architectures and agentic AI solutions. He is an active speaker at AWS events and contributes to technical publications and open-source initiatives. He is also the co-author of Apache Iceberg on AWS book. Outside of work, David enjoys staying active through volleyball, tennis, and basketball.

Steven Alyekhin

Steven Alyekhin

Steven is a Senior Solutions Architect on the AWS Canada ISV team, where he helps software companies build generative AI, machine learning, and data solutions on AWS.

Allocate shared Amazon MSK costs to Kafka topics for cost visibility

Post Syndicated from Durai Krishnan original https://aws.amazon.com/blogs/big-data/allocate-shared-amazon-msk-costs-to-kafka-topics-for-cost-visibility/

Your AWS bill shows Amazon Managed Streaming for Apache Kafka (Amazon MSK) charges at the cluster level, with one cost line item for each cluster. If your organization runs one cluster for several teams, and each team owns its own Kafka topics, you need a way to show each team its share of the spend. This post shows how you can produce that per-topic cost view by combining cluster-level billing data with per-topic usage metrics. The result gives each team a usage-based picture of what it consumes.

Bringing cost and usage together

You can use Amazon MSK to run Apache Kafka at scale while AWS manages the underlying infrastructure, so you can focus on configuring and operating your applications. Many organizations consolidate multiple workloads onto a single cluster, where each team or application owns a set of Kafka topics. Consolidation can help you improve operational efficiency. When you implement per-topic cost visibility, you can show each team its share of the cluster spend.

Producing that view draws on two sources of data, and the solution brings them together.

Cost: cluster-level billing in the CUR

You can locate MSK charges in your AWS Cost and Usage Report (CUR) by cluster ARN and see operations such as RunBroker, RunVolume, and Bandwidth. You use this cluster-level cost as the starting point when you allocate costs to your topics.

Usage: per-topic metrics without cost context

Amazon MSK surfaces per-topic throughput metrics, which provide the usage signal you use to distribute cluster cost across topics. You can use the cluster name that Amazon MSK provides with these metrics. Map that name to the cluster ARN to join usage with billing and produce per-topic cost.

Solution overview

Option A – Enhanced Monitoring: Uses per-topic Amazon CloudWatch metrics published by Amazon MSK.

Option B – Open Monitoring with Amazon Managed Service for Prometheus: A cost-optimized alternative. This option uses the MSK Open Monitoring endpoint at no additional charge and keeps metric cost growth low as topic count grows.

Both options use the same allocation logic and output. Switch between them with one configuration value.

The pipeline runs in five steps:

  1. Read cluster cost from CUR – A daily AWS Lambda function reads MSK line items by cluster ARN and day.
  2. Bridge identifiers – The function calls ListClustersV2 to map cluster name to ARN.
  3. Read per-topic usage – The function retrieves each topic’s daily throughput. This step differs between Option A and Option B.
  4. Allocate proportionally – For each day, the function distributes that day’s cluster cost across topics based on each topic’s share of throughput.
  5. Publish results – The function writes allocation data as Apache Parquet to Amazon Simple Storage Service (Amazon S3) and refreshes an Amazon Athena table. You visualize the results in AWS Quick Sight.

The following diagram shows the pipeline.

Serverless pipeline allocating MSK cluster cost to Kafka topics from CUR and per-topic metrics, output to Amazon S3 and Quick Sight

Figure 1: Solution architecture. A single serverless pipeline supports both per-topic metric sources, selected with the METRIC_SOURCE environment variable

How the allocation works

For each cluster and day, the function computes each topic’s share of ingress bytes and applies that share to the cost:

topic_run_cost = day_broker_cost × (topic_bytes / total_cluster_bytes)
topic_storage_cost = day_storage_cost × (topic_bytes / total_cluster_bytes)
topic_total_cost = topic_run_cost + topic_storage_cost

The function assigns 30 percent of the cost to a topic that carries 30 percent of ingress. Allocations always sum to the day’s total. During a partial outage, the function distributes costs only among topics for which you have configured metrics.

Two behaviors to know:

  • Idle topics get no row. If only 3 of 20 report traffic, those 3 absorb the full cost. The allocation_method column catches this.
  • If no topic reports traffic for a cluster-day, the function falls back to an even split across all topics you have configured.

Why bytes-in as the allocation weight

Bytes-in is available from both metric sources and correlates well with broker compute and network cost.

However, bytes-in is a proxy. Its limitations:

  • It can’t see retention. Two topics with identical throughput but different retention periods use different storage.
  • It can’t see replication factor or compression, which change actual bytes on disk.
  • It can’t see consumer fan-out. A topic read by ten consumer groups looks the same as one read by one.

Other factors can drive your costs, such as egress (consumer read volume), partition count, or storage retention. In that case, you can adapt the same pipeline to use a different allocation weight or a blended model.

Report unallocated charges (data transfer, tiered storage, MSK Connect) explicitly so finance has a more complete picture.

Prerequisites

Before you begin, make sure you have:

  • An active Amazon MSK Provisioned cluster with topics carrying traffic. (Amazon MSK Serverless is out of scope. It bills differently and does not expose per-topic BytesInPerSec.)
  • AWS CUR (or AWS Data Exports for CUR 2.0) delivering Parquet to Amazon S3 with resource IDs enabled. Uses CUR 2.0 snake_case column names.
  • An AWS Glue catalog table over the CUR data with correct partition configuration.
  • Permissions to create AWS Lambda functions, IAM roles, Athena tables, and Quick Sight resources.
  • Quick Sight Enterprise edition (for SPICE datasets and row-level security in the reporting layer).
  • For Option B only: a private subnet in the MSK virtual private cloud (VPC) for the scraper, and an Amazon Managed Service for Prometheus workspace.

Timing: CUR lags up to 24 hours. Per-topic metrics exist only from the moment you enable them.

Sourcing per-topic usage: Two options

How you collect per-topic usage is the main design decision in this solution, because it determines your monitoring cost and setup effort. The pipeline supports both options, and you select one with the METRIC_SOURCE environment variable.

When you set Enhanced Monitoring to PER_TOPIC_PER_BROKER, MSK publishes per-topic throughput metrics to CloudWatch. The Lambda function aggregates each topic’s daily usage with GetMetricStatistics calls.

Option A path: Amazon MSK publishes per-topic metrics to CloudWatch, which the allocation Lambda function reads directly

Figure 2: Option A collection path. Amazon MSK publishes per-topic metrics to CloudWatch, and the allocation function reads them directly

Code sample — reading per-topic metrics from CloudWatch:

result = cloudwatch.get_metric_statistics(
    Namespace='AWS/Kafka', MetricName='BytesInPerSec',
    Dimensions=[
        {'Name': 'Cluster Name', 'Value': cluster_name},
        {'Name': 'Broker ID', 'Value': str(broker_id)},
        {'Name': 'Topic', 'Value': topic},
    ],
    StartTime=day_start, EndTime=day_end,
    Period=86400, Statistics=['Sum'],
)

Note: BytesInPerSec is a rate. Period=86400 with Statistics=[Sum] returns a valid relative weight for proportional allocation, not total bytes.

Why start here: Nothing to deploy. Change one cluster setting and metrics appear in CloudWatch.

The trade-off: CloudWatch bills per metric. PER_TOPIC_PER_BROKER publishes a metric set for every topic-broker pair, so cost grows with both.

Scaling tip: At scale (over 50 clusters, over 200 topics), switch to GetMetricData (up to 500 metrics per call) instead of iterating GetMetricStatistics.

Option B (cost-optimized): Open Monitoring with Amazon Managed Service for Prometheus

Kafka brokers expose operational metrics through Java Management Extensions (JMX). Amazon MSK Open Monitoring makes these infrastructure metrics available in Prometheus format on port 11001 at no cost.

You run a scraper (AWS Fargate with an AWS Distro for OpenTelemetry (ADOT) Collector) that forwards metrics to a Prometheus workspace through SigV4 remote write. The task role needs the aps:RemoteWrite permission.

Option B path: a VPC scraper collects JMX metrics and remote-writes them to Amazon Managed Service for Prometheus

Figure 3: Option B collection path. A VPC scraper collects JMX metrics at no additional charge and forwards them to Prometheus

Scraper configuration (Prometheus agent):

global:
  scrape_interval: 60s
  external_labels:
    cluster_name: "<your-cluster-name>"  # allocation query filters on this

scrape_configs:
  - job_name: msk-jmx
    metrics_path: /metrics
    static_configs:
      - targets:
          - "b-1.<cluster>.<id>.kafka.<region>.amazonaws.com:11001"
          - "b-2.<cluster>.<id>.kafka.<region>.amazonaws.com:11001"

remote_write:
  - url: https://aps-workspaces.<region>.amazonaws.com/workspaces/<workspace-id>/api/v1/remote_write
    sigv4:
      region: <region>
      role_arn: arn:aws:iam::<central-account-id>:role/MskPromRemoteWriteRole
    queue_config:
      capacity: 2500
      max_samples_per_send: 1000

Get broker hostnames from GetBootstrapBrokers. For dynamic lists, use Prometheus file_sd_configs.

PromQL query for per-topic usage:

sum by (topic) (
  avg_over_time(
    kafka_server_BrokerTopicMetrics_OneMinuteRate_BytesInPerSec{cluster_name="<cluster>"}[1d]
  )
) * 86400

This averages broker rates over 24 hours into one value per topic, producing a comparable weight.

Open Monitoring is available at no additional charge and the Prometheus workspace bills on samples ingested, so metric cost grows slowly. This suits large fleets.

How the function discovers topics

The function resolves topic lists through a tiered lookup:

  1. Static topic map – An environment variable holding JSON keyed by cluster name. No API calls needed. Works well when you already track topic ownership in config or infrastructure code.
  2. Amazon MSK ListTopics API – Control-plane call, no VPC connectivity needed.
  3. CloudWatch ListMetrics – Reads topics from metric dimensions (Enhanced Monitoring only).
  4. Previous allocation output – Falls back to yesterday’s topic list from S3.

The tiered lookup keeps the function working whether or not Enhanced Monitoring is enabled:

def discover_topics(cluster_name, kafka_client=None, cluster_arn=None):
    """Resolve the topic list without requiring Enhanced Monitoring.
    Tiers are tried in order; the first that returns topics wins."""
    # Tier 1: static map from an env var (no API calls). Set TOPIC_LIST_JSON
    # to a JSON object keyed by cluster name, e.g. {"<cluster>": ["<topic>", ...]}
    if TOPIC_LIST_JSON:
        mapping = json.loads(TOPIC_LIST_JSON)
        if cluster_name in mapping:
            return set(mapping[cluster_name])
    # Tier 2: MSK ListTopics API - works at DEFAULT monitoring, no extra cost
    if kafka_client and cluster_arn:
        topics = _discover_topics_via_msk_api(kafka_client, cluster_arn)
        if topics:
            return topics
    # Tier 3: CloudWatch ListMetrics - only returns topics when Enhanced
    # Monitoring (PER_TOPIC_PER_BROKER) is enabled
    topics = _discover_topics_via_cloudwatch(cluster_name)
    if topics:
        return topics
    # Tier 4: fall back to the topic list from yesterday's allocation output in S3
    return _topics_from_previous_allocations()

Choosing between the options

For steady topics, both options typically produce comparable results. The choice is cost and operating model:

Option A: Enhanced Monitoring Option B: Open Monitoring + Prometheus
Per-topic metric cost ~$90/cluster/month None (Open Monitoring is at no additional charge)
Additional infra cost None ~$11/cluster/month (scraper + workspace)
Setup effort Change one cluster setting Deploy scraper, workspace, and VPC networking
Ongoing operations None Maintain one scraper per VPC
Scaling behavior Grows with topics × brokers Grows slowly from a much lower base
Time to first allocation Next day Next day (after a few days of setup)

Note: Figures are illustrative, not AWS list prices. Recalculate using the CloudWatch, Prometheus, and Fargate pricing pages.

Guideline: if monitoring cost is below 5 percent of MSK spend, take Option A. Above 10 percent, Option B repays the setup quickly.

You can enable Enhanced Monitoring only on clusters where chargeback accuracy matters, and switch to Option B later with one environment variable change.

Deploying the allocation pipeline

Deploy with AWS Cloud Development Kit (AWS CDK). The core Lambda function (Python 3.11, 1 GB, 10-min timeout) uses the AWS SDK for pandas layer for Parquet processing. Two triggers invoke the function, for resilience:

  • An Amazon S3 event notification fires when a new CUR Parquet file arrives, so allocation runs as soon as fresh cost data lands.
  • An Amazon EventBridge rule runs daily at 06:00 UTC as a fallback, in case the S3 event doesn’t arrive or CUR delivery lags.

Set METRIC_SOURCE to cloudwatch for Option A or prometheus for Option B. For Option B, you also supply the workspace query endpoint and label names.

The handler at a glance

The following handler function orchestrates the five-step pipeline. Each step delegates to a dedicated function, described in the sections that follow.

def handler(event, context):
    """Lambda entry point --- runs the five-step pipeline once per invocation."""
    # Step 1: read cluster cost from CUR (MSK rows only)
    daily_cur = read_cur_costs_via_athena()
    if not daily_cur:
        return _resp(200, 'No MSK costs found in CUR data')
    # Step 2: bridge identifiers - group cluster ARNs by account
    clusters_by_account = _group_clusters_by_account(daily_cur)
    # Steps 3-4: read per-topic usage and allocate cost proportionally, per cluster
    all_rows, errors = [], []
    for account_id, cluster_arns in clusters_by_account.items():
        try:
            all_rows.extend(process_account(account_id, cluster_arns, daily_cur))
        except Exception as e:
            errors.append({'account': account_id, 'error': str(e)})
    # Step 5: publish results - write Parquet to S3, refresh the Athena table
    write_allocations(all_rows)
    refresh_allocation_table()
    return _resp(200, {'rows_written': len(all_rows), 'errors': len(errors)})

CDK stack – Lambda function definition:

allocation_fn = lambda_.Function(
    self, "AllocationProcessor",
    runtime=lambda_.Runtime.PYTHON_3_11,
    handler="handler.handler",
    code=lambda_.Code.from_asset("src/lambda/allocation_processor"),
    timeout=Duration.minutes(10),
    memory_size=1024,
    dead_letter_queue=dlq,
    environment={
        "OUTPUT_BUCKET": allocation_bucket.bucket_name,
        "ATHENA_DATABASE": cur_database_name,
        "CUR_TABLE_NAME": cur_table_name,
        "ATHENA_OUTPUT": f"s3://{allocation_bucket.bucket_name}/athena-results/",
        # Option A. Switch to "prometheus" for Option B.
        "METRIC_SOURCE": "cloudwatch",
        # Option B only:
        # "AMP_QUERY_URL": "https://aps-workspaces.<region>.amazonaws.com/"
        # "workspaces/<workspace-id>/api/v1",
        # "AMP_CLUSTER_LABEL": "cluster_name",
        # "AMP_TOPIC_LABEL": "topic",
    },
    layers=[pandas_layer],
)

Triggers:

# Trigger 1: process when new CUR data arrives
cur_bucket.add_event_notification(
    s3.EventType.OBJECT_CREATED,
    s3n.LambdaDestination(allocation_fn),
    s3.NotificationKeyFilter(prefix="cur-clean/", suffix=".parquet"),
)

# Trigger 2: daily schedule as fallback
daily_rule = events.Rule(
    self, "DailyAllocationRule",
    schedule=events.Schedule.cron(hour="6", minute="0"),
)
daily_rule.add_target(targets.LambdaFunction(allocation_fn))

The stack provisions an Amazon Simple Queue Service (Amazon SQS) dead-letter queue with 14-day retention for failed invocations, Amazon Simple Notification Service (Amazon SNS) alerts, and CloudWatch alarms. To subscribe your team, add sns.Topic.add_subscription(subscriptions.EmailSubscription("[email protected]")) in CDK, or subscribe manually through the Amazon SNS console.

The stack creates the AWS Glue table over the allocation output, so you don’t need to write DDL by hand. Deploy it with:

cdk bootstrap  # once per account and Region
cdk deploy

Invoke the function once manually to produce a first allocation.

Reading CUR efficiently at scale

The function queries CUR through Amazon Athena to get only MSK rows. Filter on partition columns so Athena prunes whole partitions:

SELECT line_item_resource_id, line_item_usage_start_date,
       line_item_unblended_cost, line_item_operation
FROM "<cur_database>"."<cur_table>"
WHERE billing_period IN ('<current_month>', '<previous_month>')
  AND line_item_product_code = 'AmazonMSK'
  AND line_item_resource_id LIKE 'arn:aws:kafka:%'
  AND line_item_usage_start_date >= TIMESTAMP '<start_of_prev_month>'
  AND line_item_unblended_cost != 0

The query reads two months because AWS can update CUR line items after the first delivery. Adjust arn:aws:kafka: for GovCloud or the China Regions.

Publishing and querying the results

The function writes allocation results to Amazon S3 as Snappy-compressed Parquet, partitioned by billing period. Each row covers one topic on one day with cluster identity, usage weight, and allocated cost.

Each run overwrites the file for its billing period. This helps prevent double-counting on CUR redeliveries.

Output schema:

Field Description
account_id AWS account that owns the cluster
cluster_name, cluster_arn MSK cluster identity and join key back to the CUR
topic_name Kafka topic
client_id Owning team or client (from a configurable mapping)
allocation_date, year, month The day this row covers, plus year and month for convenient filtering
bytes_in Topic ingress used as the allocation weight
run_cost, storage_cost, total_cost Allocated cost components
**cluster_*_cost_day** Cluster totals for that day (for reconciliation against the bill)
allocation_method “proportional” or “equal_split” – explains anomalies without re-running
generated_at Timestamp of the run that produced this row

Verifying the numbers

Run this reconciliation query before publishing a dashboard. Schedule it as a Lambda post-step with an AllocationVariance CloudWatch alarm:

SELECT allocation_date,
       cluster_name,
       SUM(total_cost) AS allocated,
       MAX(cluster_run_cost_day + cluster_storage_cost_day) AS billed,
       SUM(total_cost) - MAX(cluster_run_cost_day + cluster_storage_cost_day) AS variance,
       MAX(allocation_method) AS method,
       COUNT(*) AS topics_charged
FROM topic_cost_allocation
WHERE billing_period = '<YYYY-MM>'
GROUP BY allocation_date, cluster_name
HAVING ABS(SUM(total_cost)
    - MAX(cluster_run_cost_day + cluster_storage_cost_day)) > 0.01
ORDER BY allocation_date;

An empty result means allocations reconcile. Rows indicate days where topic discovery and cost data disagreed.

Mapping topics to teams

The function derives owners from topic naming conventions. Pass an explicit topic-to-team map where conventions fail. Unmapped topics appear as unfamiliar owners.

Visualizing cost by topic in Quick Sight

Create an Athena data source in Quick Sight, import into SPICE, and schedule daily refreshes.

A useful dashboard typically includes:

  • A detail table of cost by team, topic, and month.
  • A bar chart of total cost by topic.
  • Filter controls for cluster, topic, and time period.

Apply Quick Sight row-level security against client_id so teams see only their own numbers. Row-level security requires Enterprise edition.

Extending to multiple accounts

The pipeline extends to multi-account setups:

  • The central account reads the consolidated CUR.
  • The Lambda function assumes a read-only role in each member account (by using AWS Security Token Service (AWS STS)) to list clusters and read usage, writing one consolidated dataset.
  • For Option B, a single central Prometheus workspace receives remote-writes from every member account’s scraper, each stamping its own cluster_name label.

One dataset and one dashboard across all accounts.

Multi-account setup: a central tooling account runs the pipeline and assumes read-only roles in member accounts

Figure 4: Multi-account extension. The central tooling account owns the pipeline and reaches into member accounts through a scoped, read-only role

Security considerations

This pipeline reads billing data and crosses account boundaries.

Grant the central execution role only the permissions it needs to: read the CUR and Glue catalog, run Athena queries, write to the allocation S3 bucket, and assume member-account roles.

Member-account role is read-only. Require a shared external ID on every AssumeRole call to help mitigate the confused-deputy problem.

For Option B, restrict port 11001 to the scraper’s security group. Consider AWS PrivateLink for remote write.

Encrypt CUR, allocation output, and Athena results at rest using SSE-KMS (recommended for financial data). Use TLS to encrypt data in transit, including the scraper’s remote write and Athena connections.

The output reveals what every team spends. Treat the output bucket and Quick Sight dataset as financial reports.

Cost of running the solution

The pipeline itself is inexpensive (Lambda, Athena, S3, Amazon EventBridge are negligible). Two items dominate:

  • The metric source: ~$90 (Option A) compared to ~$11 (Option B) per month on the example cluster.
  • Quick Sight user licenses: frequently the largest cost, scaling with how many people get access.

Clean up

To avoid ongoing charges, remove the resources you created. Delete Athena query result files and the CUR delivery configuration if created solely for this solution.

cdk destroy

If you enabled Enhanced Monitoring solely for this solution, return to the previous level. For Option B, remove the scraper and Prometheus workspace.

Conclusion

This pipeline bridges cluster-level CUR cost to topic-level usage, giving each team visibility into its share of the spend. Switch between monitoring options with one environment variable. Pick a cluster and run the allocation to get started.

Learn more:


About the authors

Durai Krishnan

Durai Krishnan

Durai is a Senior Customer Solution Manager at Amazon Web Services (AWS) with rich background in consulting and leadership. Durai specializes in guiding customers through their cloud journey, focusing on migration, modernization, and cost optimization strategies.

Ganesh Thiyagarajan

Ganesh Thiyagarajan

Ganesh is a Senior Solutions Architect at Amazon Web Services (AWS) with over 20 years of experience in software architecture, IT consulting, and solution delivery. He helps ISVs transform and modernize their applications on AWS. He is also part of the AI/ML Technical field community, helping customers build and scale Gen AI solutions.

Governance compliance beyond the catalog in Amazon SageMaker Unified Studio

Post Syndicated from Amom Luiz original https://aws.amazon.com/blogs/big-data/governance-compliance-beyond-the-catalog-in-amazon-sagemaker-unified-studio/

As your data catalog grows, how do you know which assets meet your organization’s governance standards? Amazon SageMaker Unified Studio provides the building blocks for governance such as metadata form definitions, data quality scores, glossary associations, subscription data, and a daily catalog export queryable through SQL.

A data catalog typically answers what exists as asset names, schemas, and ownership. SageMaker Unified Studio goes further, surfacing governance signals like metadata completeness, data quality scores, and glossary associations for each asset. This pattern brings them together into a single view you can query across all your assets, projects, and data products.

This post walks through how to build that enrichment pipeline and provide an asset scorecard example with an extensible set of dimensions and weights. However, the key takeaway is the pattern itself: after the signals are in one place, your team can define what “compliant” means for your context and manage assets and data products at scale. The pipeline is the foundation, and the business/compliance logic is yours to adapt and evolve.

The governance questions this pattern can answer include:

  • Data Owner: Which of my assets are missing a required metadata form?
  • Data Steward: Which assets have no glossary terms associated?
  • Data Platform team/Managers: Is compliance improving since the team published the new governance rules, within and between projects?
  • Chief Data Officer: Which departments need to work to provide more reliable data products to the organization?

This solution extends Analyzing your data catalog: Query SageMaker Catalog metadata with SQL, which introduced the asset metadata export feature. This post focuses on enriching the metadata export to support an enhanced and data-driven governance compliance strategy.

Solution overview

Architecture diagram showing the daily enrichment pipeline within an AWS account. Five enrichment data sources on the left (Amazon SageMaker Asset Export, Custom Policy Config, Search and GetListings API, GetAssetType API, and ListSubscriptions API) feed an Enrichment Lambda function triggered by an Amazon EventBridge Scheduler. The Lambda writes daily snapshot partitions to the governance_metadata.asset_compliance S3 Table, governed by AWS Lake Formation. Downstream consumers on the right include Amazon Athena for SQL queries, Amazon Quick Sight for the compliance dashboard used by data stewards, data owners, and CDOs, and Amazon EventBridge with SNS and SES for threshold alerts.

Figure 1: Daily governance enrichment pipeline, from the five data sources through the enrichment Lambda function to the Amazon Athena, AWS Quick Sight, and Amazon EventBridge consumers

The enriched compliance table is itself an Amazon Simple Storage Service (Amazon S3) Table asset in the SageMaker catalog queryable inside SageMaker Unified Studio alongside all domain assets.

The enrichment pipeline runs daily and consists of five data sources joined by an enrichment Lambda function:

  1. Amazon SageMaker Asset Metadata Export: the base inventory of all published assets, stored as an S3 Table.
  2. Form Policy Config: an S3 JSON file that defines custom organization-level required forms per project and asset type.
  3. Search / GetListing API: returns glossary terms, attached metadata forms, and a data quality summary per asset.
  4. GetAssetType API: returns the complete data quality rules count per asset.
  5. ListSubscriptions API: returns the number of active consumer subscriptions per published asset.

The pipeline reads from all five sources, computes a weighted compliance score per asset, and writes the result as a new daily snapshot partition to the governance_metadata.asset_compliance S3 Table. Downstream consumers such as Amazon Athena, AWS Quick Sight compliance dashboard, and Amazon EventBridge compliance alerts, read from that enriched table.

The following figure shows the end data product you will build: a compliance dashboard scoring every asset across your projects.

Amazon Quick Sight compliance dashboard showing four KPI cards at the top: Avg Compliance Score (36.59), Assets Without Glossary (27), Assets Without Business Description (28), and Assets Without Resource Description (13). Below, a donut chart titled Assets by Compliance Band shows 28 total assets distributed across Critical (majority), At Risk, and Compliant bands. To the right, a horizontal bar chart titled Assets by Compliance Score ranks assets from lowest to highest, with daily_revenue_report at the top.

Figure 2: Compliance dashboard scoring every asset across your projects, the end product you build

Prerequisites

Before you begin, verify that you have the following in place:

  • Python 3.12 and AWS Cloud Development Kit (AWS CDK) for deployment of the enrichment pipeline from the sample GitHub repository.
  • An Amazon SageMaker Unified Studio domain. This post demonstrates the solution using an AWS IAM Identity Center (IDC)-based domain. You need permission to enable the asset metadata export on the domain (activating the export is covered in Part 1).
  • Published assets in the SageMaker Unified Studio domain: the solution enriches information based on assets already published in the domain.
  • An AWS account with permissions to work with the services used in this solution: AWS Lambda, Amazon Athena, Amazon S3 including Amazon S3 Tables, AWS Glue Data Catalog, AWS Lake Formation, AWS Quick Sight, and Amazon EventBridge.
  • AWS Lake Formation access: The asset metadata export and the enriched table are governed by AWS Lake Formation, so you need to grant the Lambda execution role and the Amazon service role the appropriate DESCRIBE/SELECT permissions (detailed in the aws-samples repository).
  • The AWS Command Line Interface (AWS CLI): configured for your account and target AWS Region.
  • An AWS Quick Sight account in the same Region, required for the dashboard in Part 6.

Estimated time to complete is approximately 2 hours. Estimated cost is less than $5 per month for a small test domain (AWS Lambda invocations, Athena queries, and S3 storage). Costs scale with the number of assets and query volume.

Deploy the solution

The complete source code for this solution is available in the sample-smus-asset-scorecard repository on GitHub. The AWS Cloud Development Kit (AWS CDK) stack provisions all required infrastructure, including the enrichment Lambda function, Amazon S3 policy configuration bucket, Amazon EventBridge Scheduler rule, AWS Identity and Access Management (IAM) roles, and the S3 Table namespace. Follow the walkthrough available in the repository to deploy the solution.

Part 1: The asset metadata export

The asset metadata export serves as the primary data source for the enriched scorecard dataset. To activate the export once per domain, use the following AWS CLI command:

aws datazone put-data-export-configuration \
  --domain-identifier <domain-id> \
  --region <region> \
  --enable-export

Within 24 hours you can read the asset metadata export as an S3 Table in SageMaker Unified Studio query editor (table asset_metadata.asset). You can check the Exporting Asset Metadata official documentation to get more details about the Asset Metadata export. Three fields from the export are used by the enrichment pipeline:

  • asset_id: the identity of each asset in the catalog, and the join key the enrichment uses to map each row to its published listing (Part 3).
  • extended_metadata[‘owningEntityId’]: this single key from the metadata map identifies which project owns the asset, driving the per-project compliance policy lookup in Part 2.
  • business_description and resource_description: the documentation signals that contribute to the description dimension of the compliance score.

The following figure shows an example of the Asset Metadata Export:

Amazon SageMaker query editor showing a SELECT query result for the asset_metadata.asset table with 47 rows. Columns displayed are snapshot_time, asset_id, asset_name, extended_metadata, resource_type_enum, resource_id, and account_id. Sample rows include asset names such as churn, user_sessions_silver, ad_hoc_export_2025, raw_clickstream_events, daily_revenue_report, and monthly_active_users, all of type GlueTable. The account_id column is masked.

Figure 3: Example of the asset metadata export queried in the SageMaker query editor

Part 2: The policy layer: Defining mandatory metadata forms

The export tells you what metadata form fields are filled. But required is a two-level concept in this solution:

Level 1: Amazon SageMaker Unified Studio metadata enforcement rules. You can configure mandatory metadata forms for publishing and subscription flows. These enforcement rules are defined at the asset-type level. You can call the GetAssetType API and inspect the required boolean in formsOutput.

Level 2: Custom organization-defined requirements. This solution also accounts for required metadata forms that lack enforcement rules, but your organization still considers mandatory. For example, a project might require a DataClassificationForm on every Glue table, even though SageMaker Unified Studio itself doesn’t enforce it at the asset-type level. These project-specific rules don’t exist as a native API endpoint, they can be stored externally in an S3 configuration file.

The enrichment pipeline reads both layers and takes their union. The SageMaker Unified Studio enforcement rules come from GetAssetType API per asset type and the custom organization-specific overrides come from a policy file stored in Amazon S3. Change the following sample file with the project IDs and required forms for your use case and put it in the S3 bucket created with CDK (see the Walkthrough section in the Readme of sample repository):

{
  "default": {
    "required_forms": ["DataClassification"]
  },
  "projects": {
    "<project-id-1>": {
      "required_forms": ["DataClassification", "CriticalityForm"]
    },
    "<project-id-2>": {
      "required_forms": ["DataClassification", "CriticalityForm", "OwnershipForm"]
    }
  }
}

The S3 configuration file is updated whenever your governance policy evolves. The GetAssetType call ensures the pipeline always respects whatever enforcement rules are defined in SageMaker Unified Studio, including any new rules created in future revisions.

Part 3: The enrichment pipeline

The enrichment pipeline reads the latest export snapshot and joins it with governance facets from the published catalog through GetListing. It then merges the compliance policy from both enforcement rules (GetAssetType) and the custom organization-defined policy file. The complete implementation with annotated code is available in the aws-samples repository.

The enrichment Lambda reads the latest asset metadata export, calls the APIs for the dimensions not present in the export (data quality scores and glossary associations), and writes one enriched compliance record per asset.

3.1 The compliance score

The compliance score combines five independent dimensions, each contributing a weighted percentage as the following table shows:

Dimension Weight Signal
Form coverage 50% % of required forms present compared to policy
Data quality score 20% Data quality pass/fail percentage
Data quality rule coverage 10% Actual rules compared to minimum expected
Glossary presence 10% Has at least 1 glossary term
Description 10% Has a business or resource description

Weights and the minimum data quality rules threshold are configurable. Adjust them to reflect your organization’s governance priorities.

3.2 Run the enrichment pipeline

To run the pipeline, invoke the Lambda function as shown in the following example:

aws lambda invoke \
  --function-name gov-obs-enrichment \
  --region <region> \
  --cli-binary-format raw-in-base64-out \
  --payload '{}' /tmp/response.json

Part 4: The governance answers

With the enriched table available, the governance questions listed at the beginning of the post can be answered using SQL queries against the enriched table.

4.1 Assets missing required forms

The following query returns the list of assets missing required forms:

SELECT
    asset_name,
    project_name,
    missing_required_forms,
    dq_score,
    dq_rules_count,
    overall_compliance_score
FROM "s3tablescatalog/gov-obs-data"."governance_metadata"."asset_compliance"
WHERE snapshot_date = CAST(CURRENT_DATE AS VARCHAR)
AND json_array_length(missing_required_forms) > 0
ORDER BY overall_compliance_score ASC;
Amazon SageMaker query editor showing the enriched asset_compliance table result with 27 rows. Columns are asset_name, project_name, missing_required_forms, dq_score, dq_rules_count, and overall_compliance_score. Sample rows show fact_orders in the data-engineering project with a score of 16.67, raw_email_events in marketing-analytics with 25.0, and raw_clickstream_events in admin-project with 25.0. The project name containing the account ID is masked.

Figure 4: Query result listing the assets that are missing required metadata forms

4.2 Compliance scorecard per project

To explore the scorecard grouped by project, run the following query:

SELECT
    project_name,
    COUNT(*) AS total_assets,
    ROUND(AVG(overall_compliance_score), 1) AS avg_compliance_score,
    COUNT(CASE WHEN json_array_length(missing_required_forms) > 0 THEN 1 END) AS assets_with_form_gaps,
    COUNT(CASE WHEN dq_score >= 80 THEN 1 END) AS assets_passing_dq
FROM "s3tablescatalog/gov-obs-data"."governance_metadata"."asset_compliance"
WHERE snapshot_date = CAST(CURRENT_DATE AS VARCHAR)
GROUP BY project_name
ORDER BY avg_compliance_score ASC;
Amazon SageMaker query editor showing a project-level aggregation result with 3 rows. Columns are project_name, total_assets, avg_compliance_score, assets_with_form_gaps, and assets_passing_dq. Results show admin-project (22 assets, avg score 16.0, 20 form gaps, 2 passing data quality), data-engineering (4 assets, score 31.1, 4 form gaps, 0 passing data quality), and marketing-analytics (3 assets, score 40.0, 3 form gaps, 0 passing data quality). The project name containing the account ID is masked.

Figure 5: Per-project compliance scorecard aggregation

4.3 Compliance trend since rule publication

To answer how your assets are evolving since you published new rules you can run the following query:

SELECT
    snapshot_date,
    ROUND(AVG(overall_compliance_score), 1) AS avg_compliance_score,
    COUNT(*) AS total_assets,
    COUNT(CASE WHEN json_array_length(missing_required_forms) = 0 THEN 1 END)
    AS fully_compliant_assets
FROM "s3tablescatalog/gov-obs-data"."governance_metadata"."asset_compliance"
WHERE snapshot_date >= '2026-05-01' -- replace with your governance policy publish date
GROUP BY snapshot_date
ORDER BY snapshot_date;
Amazon SageMaker query editor showing a time-series compliance trend result with 3 rows. Columns are snapshot_date, avg_compliance_score, total_assets, and fully_compliant_assets. Rows show 2026-06-27 (score 36.6, 28 assets, 2 compliant), 2026-06-28 (score 36.6, 28 assets, 2 compliant), and 2026-06-29 (score 36.2, 29 assets, 2 compliant).

Figure 6: Compliance trend across daily snapshots since the governance policy was published

Part 5: Alerting on non-compliant assets

You can go further and use Amazon EventBridge Scheduler combined with AWS Lambda to send weekly reports and alert your team when compliance drops below a defined threshold:

def handler(event, context):
    # Query compliance for today
    df = wr.athena.read_sql_query(
        sql="""
        SELECT project_name,
        COUNT(*) FILTER (WHERE json_array_length(missing_required_forms) > 0) AS non_compliant
        FROM "s3tablescatalog/gov-obs-data"."governance_metadata"."asset_compliance"
        WHERE snapshot_date = CAST(CURRENT_DATE AS VARCHAR)
        GROUP BY project_name
        HAVING COUNT(*) FILTER (WHERE json_array_length(missing_required_forms) > 0) > 0
        """,
        database="governance_metadata"
    )
    if not df.empty:
        # Send alert using Amazon SNS, a Slack webhook, Amazon SES, and so on.
        send_governance_alert(df)

You can configure the Amazon EventBridge Scheduler rule to fire on a weekly schedule or daily if your organization requires tighter compliance monitoring. The send_governance_alert function is illustrative and can be routed to any channel your team prefers: Amazon Simple Notification Service (Amazon SNS) topics, Amazon Simple Email Service (Amazon SES), or a Slack webhook through an HTTP call.

Part 6: Building a governance dashboard with AWS Quick Sight

With the enriched governance table producing daily compliance scores, the final step is making these insights visible to stakeholders through an actionable and interactive dashboard. AWS Quick Sight connects directly to Amazon Athena, so you can visualize the compliance table directly.

6.1 Connecting and configuring AWS Quick Sight with the enriched table

Grant the AWS Quick Sight service role (aws-quicksight-service-role-v0) Lake Formation DESCRIBE and SELECT permissions on governance_metadata.asset_compliance. You can see details of grants needed in the aws-samples repository. In the repository you also can see a Python script which creates AWS Quick Sight data source, datasets and a complete dashboard with the compliance data, as the following figure shows:

Amazon Quick Sight compliance dashboard showing four KPI cards at the top: Avg Compliance Score (36.59), Assets Without Glossary (27), Assets Without Business Description (28), and Assets Without Resource Description (13). Below, a donut chart titled Assets by Compliance Band shows 28 total assets distributed across Critical (majority), At Risk, and Compliant bands. To the right, a horizontal bar chart titled Assets by Compliance Score ranks assets from lowest to highest, with daily_revenue_report at the top.

Figure 7: Compliance dashboard connected to the enriched table in AWS Quick Sight

Amazon Quick Sight Governance Dashboard showing four horizontal bar charts comparing three projects (marketing-analytics, admin-project, and data-engineering). Top left: Avg Score by Project: marketing-analytics leads at 40, followed by admin-project around 37, and data-engineering at 31. Top right: Avg data quality Score by Project: data-engineering leads at approximately 26. Bottom left: Avg data quality Rules by Project: admin-project and marketing-analytics near 1.8, data-engineering at 1.2. Bottom right: Assets With Form Gaps by Project: admin-project has the most at approximately 19.

Figure 8: Per-project comparison charts in the governance dashboard

6.2 Create visualization using natural language

Use the natural language Build feature in AWS Quick Sight to create each visualization with a plain-language prompt:

Visualization Natural language prompt Purpose
Compliance scorecard “Show average overall_compliance_score by project_name as a bar chart” Per-project accountability
Compliance band distribution “Show count of asset_name by compliance_band as a pie chart” Executive summary
Score trend over time “Show average overall_compliance_score by snapshot_date as a line chart” Is governance improving?
Form gap breakdown “Show count of asset_name where missing_required_forms is not empty by project_name as a stacked bar” Which teams have metadata form gaps?
Glossary coverage “Show count of asset_name where glossary_terms_count equals 0 as a KPI” How many assets have no terms?
Data Quality coverage “Show average dq_rules_count by project_name as a bar chart” Which projects lack data quality rules?
Amazon Quick Sight analysis editor showing the AutoGraph builder. On the left, the Asset Compliance dataset field list includes asset_name, compliance_band, dq_rules_count, dq_score, glossary_terms_count, missing_required_forms, overall_compliance_score, project_name, and snapshot_date. On the right, the Build a visual panel shows a natural language query typed as: Show average overall_compliance_score by project name, with a BUILD button and example prompts visible.

Figure 9: Building a visualization with a natural language prompt in the AWS Quick Sight analysis editor

Amazon Quick Sight: Build a visual panel showing the query interpreted as: Average of Overall Compliance Score by Project Name. The resulting horizontal bar chart displays three projects: marketing-analytics (40), admin-project-29 (37.15), and data-engineering (31.09), with an ADD TO ANALYSIS button at the bottom.

Figure 10: Natural language prompt interpreted as average compliance score by project

This produces an AWS Quick Sight dashboard built on top of the enriched table that delivers actionable governance, not raw metadata counts. Stakeholders see compliance scores, form gaps, and improvement trends without needing to understand the underlying API model.

Amazon Quick Sight horizontal bar chart titled Average of Overall Compliance Score by Project Name, part of the SageMaker Unified Studio Scorecard dashboard. Three bars are shown: marketing-analytics at 40, admin-project at approximately 37, and data-engineering at 31.09, on a scale from 0 to 40.

Figure 11: Average overall compliance score by project rendered as a bar chart

For a deeper walkthrough of the natural language Build approach applied to the raw export table, see Build governance dashboards for Amazon SageMaker Catalog with AWS Quick Sight. The same technique applies to your enriched compliance table with the richer signals added by this pipeline.

Part 7: Seeing the pipeline in action

To illustrate how to apply these concepts, consider a domain with 20 published AWS Glue table assets across three projects, each at a different governance maturity level. After the daily enrichment runs, querying the compliance table immediately surfaces the differences.

7.1 Per-project scorecard

Briefly, you can see which teams are investing in governance and which ones need attention. The marketing-analytics leads because its assets have metadata forms, glossary terms, and data quality rules configured, while the other two projects have only basic data quality checks in place.

Amazon Quick Sight: Amazon SageMaker Scorecard dashboard showing three visuals. Top left KPI card displays 16 unique assets. Bottom left horizontal bar chart titled Average of Overall Compliance Score by Project Name shows marketing-analytics at 40, admin-project at 37.15, and data-engineering at 31.09. Right side pie chart titled Unique number of Asset Name by Compliance Band shows Critical at 75% (15 assets), At Risk at 20% (4 assets), and Compliant at 5% (1 asset).

Figure 12: Per-project scorecard with compliance score and compliance band distribution

7.2 Drilling into individual assets

Based on compliance score defined previously as example, you can see the governance maturity into clear bands:

Score Band Typical profile
80–100 Fully governed All required forms present, glossary terms linked, data quality passing, description provided
60–79 Mostly governed Required forms present, but missing either glossary terms or data quality coverage
40–59 Partially governed Some required forms missing, or forms present but no glossary or data quality
20–39 Data quality only Data quality rules configured and running, but no governance forms, glossary, or description
1–19 Minimally documented Only a description present, but no forms, no data quality rules, no glossary
0 Ungoverned No forms, no glossary, no data quality rules, no description

The pipeline produces this output automatically on every scheduled run without manual intervention required. The Amazon EventBridge Scheduler fires daily, enriches the latest snapshot, and writes the compliance scorecard to the Iceberg table. A single Athena query then produces the per-project, per-asset view shown here.

Scalability note: in our test scenario with a domain of 29 published Glue Table assets across three projects, the enrichment Lambda completed in approximately 30 seconds. For organizations with larger domains and production environment, consider parallelizing asset enrichment calls and increasing Lambda memory allocation. For very large catalogs, a fan-out pattern using AWS Step Functions can distribute the workload across multiple Lambda invocations.

7.3 Consumption-weighted risk: who is using ungoverned data?

Compliance scores tell you what is below the required threshold. But not all compliance findings carry equal urgency. An asset with a score of 10 that five projects depend on might require immediate attention. The enrichment pipeline adds a subscription count per asset which represents the number of projects that have an approved subscription to consume it. This comes from the ListSubscriptions API, filtered by subscribedListingId (every published asset has a listing). Combined with the compliance score, it produces a risk matrix, as the following example shows:

Quadrant Compliance Subscriptions Recommended Action
Gold standard >= 80 High No action: well governed and well adopted
Over-invested >= 80 Zero Review: strong governance on unused assets
Backlog < 50 Zero Plan: low risk, improve over time
Critical < 50 >= 2 Act now: many consumers depend on ungoverned data

The risk-view query joins both columns:

SELECT
    asset_name,
    project_name,
    subscription_count,
    overall_compliance_score,
    CASE
        WHEN subscription_count >= 2 AND overall_compliance_score < 50 THEN 'CRITICAL'
        WHEN subscription_count >= 1 AND overall_compliance_score < 50 THEN 'MEDIUM_RISK'
        ELSE 'OK'
    END AS risk_level
FROM "s3tablescatalog/gov-obs-data"."governance_metadata"."asset_compliance"
WHERE snapshot_date = CAST(CURRENT_DATE AS VARCHAR)
AND subscription_count > 0
ORDER BY subscription_count DESC, overall_compliance_score ASC;
Amazon SageMaker query editor showing a subscribed asset risk query result with 4 rows. Columns are asset_name, project_name, subscription_count, overall_compliance_score, and risk_level. Results show daily_revenue_report (2 subscriptions, score 99.6, OK), user_sessions_silver (1 subscription, score 35.0, MEDIUM_RISK), churn (1 subscription, score 52.0, OK), and monthly_active_users (1 subscription, score 60.0, OK). The project name containing the account ID is masked.

Figure 13: Risk query joining compliance score and subscription count to prioritize ungoverned assets

This turns your governance dashboard from a passive scorecard into a prioritization engine and asset teams know exactly where to focus based on both compliance gaps and downstream impact.

7.4 Extending to data products

With SageMaker Unified Studio, data producers can group related assets into data products, which are versioned, self-contained packages aligned to a business use case. Data consumers subscribe to a data product in a single request and receive access to all its member assets at once.

With this structure, you can aggregate compliance at the data product level. Build an asset_id -> data_product_name mapping by iterating over all projects. The data product scorecard query then rolls up compliance metrics across all assets in each product:

SELECT
    COALESCE(NULLIF(data_product_name, ''), '(unassigned)') AS data_product,
    project_name,
    COUNT(*) AS total_assets,
    ROUND(AVG(overall_compliance_score), 1) AS product_compliance_score,
    SUM(subscription_count) AS total_subscriptions,
    COUNT(CASE WHEN JSON_ARRAY_LENGTH(missing_required_forms) > 0 THEN 1 END) AS assets_with_form_gaps
FROM "s3tablescatalog/gov-obs-data"."governance_metadata"."asset_compliance"
WHERE snapshot_date = date_format(current_date, '%Y-%m-%d')
GROUP BY
    COALESCE(NULLIF(data_product_name, ''), '(unassigned)'),
    project_name
ORDER BY product_compliance_score ASC;
Amazon SageMaker query editor showing a data product compliance query result with 5 rows. Columns are data_product, project_name, total_assets, product_compliance_score, total_subscriptions, and assets_with_form_gaps. Rows include entries across data-engineering (score 31.1), admin-project (score 31.3), and marketing-analytics (score 40.0), plus User Behavior (score 43.5, 6 form gaps) and Finance Analytics (score 79.8, 9 subscriptions, 0 form gaps). The project name containing the account ID is masked.

Figure 14: Data product compliance rollup across projects

This produces a compliance view at the level data consumers need: the products they subscribe to. A data product with a compliance score of 15 out of 100 and three subscriber projects is a potential governance incident, not a backlog item.

Cleaning up

If you deployed this pipeline in a test environment, delete the following resources to avoid incurring ongoing charges:

  • The enrichment Lambda function and its associated IAM role.
  • The Amazon EventBridge Scheduler rule.
  • The governance_metadata AWS Glue database and the asset_compliance S3 Table.
  • The S3 policy configuration file and any associated S3 bucket.
  • The AWS Quick Sight dataset and analysis (if created).
  • The Lake Formation permissions granted to the AWS Quick Sight service role.

The aws-samples repository has the commands needed to run the cleanup.

Conclusion

This post showed how to build a governance observability pipeline using Amazon SageMaker Unified Studio metadata exports and APIs, computes weighted compliance scores, and surfaces actionable governance insights through SageMaker Unified Studio queries and an AWS Quick Sight dashboard.

Amazon SageMaker Unified Studio provides the building blocks for governance such as asset type definitions, metadata form fields, data quality scores, glossary associations, subscription data, and a daily catalog export. This post demonstrates how to join those signals within Amazon SageMaker Unified Studio into a single enriched dataset to enhance data governance at scale.

The specific scoring model implemented here considering the five dimensions, their weights, and the risk classification by consumption is not prescriptive, but a starting point. Your organization’s governance policy might weight data product coverage more heavily, treat regulated project assets differently, or define “compliant” with a different threshold. The pipeline itself is the reusable part: after the signals are together, the scoring logic is yours to define and evolve.

Have questions about implementing this governance pipeline in your environment? Share your thoughts in the comments below or visit the aws-samples repository to contribute.


About the authors

Amom Luiz

Amom Luiz

Amom is a Senior Specialist Solutions Architect, Data & AI, at AWS. He is focused on helping customers to define and implement their Data & AI strategy at scale.

Brenda Medeiros

Brenda Medeiros de Florenco

Brenda is a DevOps Delivery Consultant in AWS Professional Services. She helps customers automate and operate cloud infrastructure and is expanding her focus toward data platforms and governance.

Guilherme Monte

Guilherme Monte

Guilherme is a Data Architect (Delivery Consultant) in AWS Professional Services. He specializes in data platforms and helps organizations build scalable, well-governed data ecosystems.