Tag Archives: Technical How-to

Understanding span queries in Amazon OpenSearch Service

Post Syndicated from Jon Handler original https://aws.amazon.com/blogs/big-data/understanding-span-queries-in-amazon-opensearch-service/

Amazon OpenSearch Service is a fully managed service for deploying, scaling, and operating OpenSearch in the AWS Cloud. OpenSearch is an open source software suite for search, analytics, and observability, licensed under the Apache License V2.0. Among the OpenSearch query types, span queries give you precise control over where terms appear in a document and how they relate to one another. Most applications get good results from match and phrase queries, but certain workloads require exact term placement that simpler queries cannot express. These include legal search, regulatory compliance, scientific and patent search, and contract analysis. Span queries fill that gap.

In this post, you will learn how span queries work, when to use them instead of phrase queries, and how to compose them to express precise structural constraints on your text.

When phrase queries fall short

The phrase query matches a contiguous sequence of terms in order. The match_phrase query accepts a slop parameter that loosens this constraint by allowing some number of position swaps between terms. A user searching for “star wars iv” expects to find the movie “Star Wars: Episode IV — A New Hope.” However, the exact phrase doesn’t appear in the title because of the intervening word “Episode.” Setting slop to 1 allows OpenSearch to swap one term position and find the match.

To explore this, create an index with a single text field:

PUT term_order
{
  "mappings": {
    "properties": {
      "title": {"type": "text"}
    }
  }
}

Index two documents:

POST term_order/_doc/1
{"title": "Star Wars: Episode IV - A New Hope"}

POST term_order/_doc/2
{"title": "Hope for Star Wars: The Prequel Series"}

A match_phrase query for “star wars iv” with slop: 1 matches the first document. Change the query to “star wars hope” with slop: 4, and the query matches both documents:

GET term_order/_search
{
  "query": {
    "match_phrase": {
      "title": {
        "query": "star wars hope",
        "slop": 4
      }
    }
  }
}

The match against “Hope for Star Wars: The Prequel Series” is unexpected. The order of terms in that document is different from the query. Phrase slop performs an edit-distance match, swapping terms within the edit window regardless of order. When you need to enforce term order, position within a field, or structural relationships between terms, phrase queries lack the expressiveness.

What span queries provide

Span queries are compound queries that give you precise control over the position of terms relative to one another. Span queries only contain other span queries. You can’t mix them with non-span queries inside the same compound expression. OpenSearch supports several span query types:

  • span_term: Matches a single term. This is typically the leaf of a compound span query.
  • span_multi: Wraps a multi-term query (prefix, regex, wildcard) so it can be used inside a span query.
  • span_first: Matches spans at the start of a field, within a specified number of positions.
  • span_near: Matches a set of span clauses within a specified slop, similar to match_phrase but operating on spans.
  • span_not: Excludes specific terms from a span match.
  • span_or: Unions multiple span clauses.
  • span_field_masking: Uses a span_term from another field, masked to appear as the primary field.
  • span_containing: Matches spans that contain other spans.
  • span_within: Matches spans that are contained within other spans. span_within is the mirror of span_containing.

All span queries accept an in_order parameter that controls whether sub-spans must appear in the order of the query clauses.

Anchoring a term to a position

To find “A New Hope” in the index, you can require “star” at the beginning of the title and “hope” within 12 terms after it:

GET term_order/_search
{
  "query": {
    "span_near": {
      "clauses": [
        {
          "span_first": {
            "match": {"span_term": {"title": "star"}},
            "end": 2
          }
        },
        {"span_term": {"title": {"value": "hope"}}}
      ],
      "slop": 12,
      "in_order": true
    }
  }
}

This query matches only “Star Wars: Episode IV — A New Hope.” The span_first clause requires “star” within the first two positions of the title. The enclosing span_near then requires “hope” within 12 positions, in the specified order. The second document doesn’t match because “star” isn’t at the start of the title.

Spans within spans

With span_containing and span_within, you can express structural constraints by matching one span inside another. Both take a big and a little clause: the little span must be contained by the big span. The difference is which span the query returns. span_containing returns the big matches, and span_within returns the little matches.

For example, to find documents where the phrase “episode iv” appears within a span containing both “star” and “hope”:

GET term_order/_search
{
  "query": {
    "span_containing": {
      "little": {
        "span_near": {
          "clauses": [
            {"span_term": {"title": {"value": "episode"}}},
            {"span_term": {"title": {"value": "iv"}}}
          ],
          "slop": 0,
          "in_order": true
        }
      },
      "big": {
        "span_near": {
          "clauses": [
            {"span_term": {"title": {"value": "star"}}},
            {"span_term": {"title": {"value": "hope"}}}
          ],
          "slop": 12,
          "in_order": false
        }
      }
    }
  }
}

The little clause matches “episode iv” as an exact phrase (slop is 0, in_order is true). The big clause matches a span containing “star” and “hope” within 12 terms of one another, in either order. The span_containing query then requires the little phrase to fall within a big match. Only “Star Wars: Episode IV — A New Hope” satisfies both constraints.

When to use span queries

Span queries are useful any time you need to express constraints that phrase queries cannot. In legal and regulatory search, statutes and contracts often require specific phrases to appear in proximity. One example is finding documents where “force majeure” appears within five terms of “termination.” Span queries give you the precise control to express that requirement.

In patent and scientific search, claims and papers frequently require terms to appear in specific structural positions relative to one another. Compliance and audit workflows that must enforce exact term placement to satisfy regulatory definitions benefit from the same precision. More generally, when your text doesn’t have an explicit structured model but you need to express constraints about where terms appear within a field, span queries provide a query-time alternative to reshaping your data.

Conclusion

Span queries trade simplicity for precision. Span queries are more verbose than phrase queries and require careful composition. In return, you can use them to express constraints that phrase queries can’t: exact ordering, position within a field, and containment relationships. For applications where term placement carries meaning, span queries are the right tool.

For more information, see the OpenSearch span query documentation and the Amazon OpenSearch Service documentation.

 


About the author

Jon Handler

Jon Handler

Jon is a Senior Principal Solutions Architect for Search Services at Amazon Web Services. Jon works closely with OpenSearch and Amazon OpenSearch Service, providing help and guidance to a broad range of customers who have search and log analytics workloads. Prior to joining AWS, Jon’s career as a software developer included four years of coding a large-scale, eCommerce search engine.

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.

AWS Graviton support for Java in AWS Transform continuous modernization

Post Syndicated from Harvinder Nagpal original https://aws.amazon.com/blogs/devops/aws-graviton-support-for-java-in-aws-transform-continuous-modernization/

AWS Transform continuous modernization now supports Graviton readiness assessment and remediation for Java, generally available since October 29, 2026. Use it to move Java applications to AWS Graviton-based instances. A readiness assessment finds the Arm64 compatibility issues in a repository, and a remediation skill resolves them in code, which you then validate on Arm64 and deploy.

AWS Graviton-based instances deliver better price-performance than comparable x86 instances. Teams planning a migration therefore face two questions about their estate: which applications are ready to move, and what has to change in the ones that are not.

Answering that repository by repository does not scale. The Java code itself is rarely the obstacle. What decides readiness is an application’s dependencies, and whether each one supports Arm64. Establishing that manually across an estate is slow, repetitive, and prone to error.

In this post, you learn how to analyze a Java repository for AWS Graviton readiness, remediate the findings, validate the change on Arm64, and deploy and run the result on a Graviton-based instance.

Solution overview

AWS Transform continuous modernization connects to your source provider, discovers your repositories, analyzes them for technical debt, remediates what it finds, and opens a pull request with the result. Analysis can also run on a schedule, so once your applications are running on Graviton you can keep checking them as dependencies change.

Two skills cover the Graviton migration:

Skill What it does
AWS/graviton-readiness-assessment Scans a repository for native libraries, architecture-specific code, and Arm64-incompatible transitive dependencies. Read-only. It does not modify source or project files.
AWS/java-x86-to-graviton Resolves the findings the analysis returned: updates native libraries, upgrades blocking dependencies, adds aarch64 handling, updates Dockerfiles for multi-architecture builds, and applies Graviton JVM flags.

The readiness assessment does not change your code. It produces findings, one for each Arm64 compatibility issue it identifies. Each finding carries a severity, a category, file references, and the transformation that resolves it, so you can triage a portfolio and drive remediation directly from the findings.

Continuous modernization runs in two places. Remotely, it uses infrastructure in your AWS account or infrastructure that AWS Transform manages. Locally, it runs on your own machine. For a Graviton migration, that choice decides what can be validated:

AWS Transform-managed Customer-managed (Amazon Elastic Compute Cloud (Amazon EC2) or AWS Batch) Local
Analysis Supported, nothing to provision Supported Supported
Remediation Not supported Supported (x86 only) Supported

Note: Continuous modernization currently provisions remote infrastructure in your account on the x86 architecture. A remote remediation produces the Arm64 code changes, but it cannot build or test them on Arm64 — you do that in your own Arm64 pipeline before you merge. On an Arm64 host, a local run builds on the target architecture as part of the remediation and leaves the change on disk, which is why this post runs it locally.

Step 5 in the following diagram, deploying to a Graviton-based instance, is beyond the scope of AWS Transform, whose output is the validated change and the pull request. In your environment, Step 5 is your existing Arm64 pipeline or test environment.

Steps 1 to 4 run inside AWS Transform continuous modernization; step 5, deploying to a Graviton instance, runs in your own Arm64 environment

Figure 1: Where each step runs. Steps 1–4 are AWS Transform continuous modernization. Step 5 is your own Arm64 environment

The walkthrough covers these steps:

  1. Connect your source and discover repositories.
  2. Analyze the repository for Graviton readiness.
  3. Remediate the findings.
  4. Validate the build on Arm64.
  5. Deploy to a Graviton instance and verify.
  6. Scale across your portfolio.

For the full command surface, refer to Working with continuous modernization in the AWS Transform User Guide.

Prerequisites

To follow this walkthrough, you need:

  • An AWS account with AWS Transform enabled for your user identity, which gives you access to the AWS Transform web application. For instructions, refer to Setting up AWS Transform.
  • An AWS Region where AWS Transform is available. For the current list, refer to Supported Regions for AWS Transform.
  • AWS credentials with permission to use AWS Transform.
  • The AWS Transform CLI, installed with the setup script, and Node.js 20 or later. Install Node.js from the Node.js website, because some package managers ship an older version.
  • Git, used for version control during the transformation.
  • A source connection: a GitHub, GitLab, or Bitbucket personal access token with repository scope, or a local folder containing checkouts you already have. The readiness assessment is read-only, so it needs no write access to your code. Remediation needs write access only if you want it to open the pull request.
  • For remediation, an Arm64 host, such as a Graviton-based Amazon EC2 instance. A local remediation builds its changes on the machine it runs on, so running it on Arm64 validates them on the target architecture. On x86, the remediation skill produces the code changes but cannot build or test them on Arm64.
  • Java 8 or later. These capabilities do not change Java versions. If you also need a version upgrade, run the AWS/java-version-upgrade transformation first. For more information, refer to the AWS Transform User Guide.

This post uses Amazon Corretto 21, Gradle 8.13, and a c7g.2xlarge instance running Amazon Linux 2023.

The sample application

This walkthrough uses TASSEL, an open source genetics toolkit. It is a Gradle project on Java 21 of about 245,000 lines of code, and it is a useful example because its dependency on x86 is typical rather than exotic.

TASSEL’s inner loop is matrix algebra, and it delegates that work to a native BLAS library through a Java Native Interface (JNI) bridge. It also reads and writes scientific data formats through libraries that ship compiled binaries inside their JAR files. Those binaries are built per architecture, and several of them have no Arm64 build — which is exactly what the readiness assessment is looking for.

If you do not have a sample application of your own, clone this one into the folder you will register as a source:

git clone https://github.com/btmonier/tassel-renovate.git

Connect your source and discover repositories

In this step, you register where your code lives and list the repositories that AWS Transform can see.

To connect a source and discover repositories

  1. Open a terminal and set the Region for the session with export AWS_REGION=us-east-1.
  2. Enter atx ct status to confirm the CLI reaches the service. It prints a summary of the sources, repositories, analyses, and findings in your account.
  3. Register a hosted source with atx ct source add --name graviton-demo --provider github --org my-org --token "$PAT", or a local folder with atx ct source add --name graviton-demo --provider local --path ~/code.
  4. Enter atx ct discovery scan --source graviton-demo to discover the repositories.
  5. Enter atx ct repository list --source graviton-demo --language java to confirm what was found.

Analyze the repository for Graviton readiness

In this step, you run the readiness assessment and review what it found.

To run the analysis

  1. Enter the following command:
    atx ct analysis run --type graviton-readiness \
    --source graviton-demo --repo tassel-renovate

  2. Enter atx ct analysis get --id <analysis-id> to follow progress.
  3. Enter atx ct findings count --by severity --repo graviton-demo::tassel-renovate to see the severity breakdown. For this repository it returned seven findings: three high, three medium, and one low.

You can also run the analysis from the AWS Transform web application.

To run the analysis on the console

  1. On the Analyses tab, choose Run new analysis.
  2. For Analysis type, choose Graviton readiness.
  3. For Analysis name, enter a name for the run.
  4. For Connected source, select your source.
  5. Choose Next to select repositories and an infrastructure mode, then choose Run. To run it on a recurring cadence, choose Schedule.
The Analysis type list in the AWS Transform web application, with Graviton readiness selected

Figure 2: Graviton readiness in the Analysis type list

The Run new analysis page configured for a Graviton readiness analysis

Figure 3: Configuring a Graviton readiness analysis against a connected source

What the analysis found

The analysis returned seven findings for this repository. The following examples are two of the seven, chosen because the difference between them is why this analysis is worth running. It also reported build configuration and JVM flag issues not shown here.

The application’s own code – TASSEL loads a native BLAS bridge with System.loadLibrary("TasselBlas") and declares six native methods. The JNI glue is in the repository as C source, with no compiled binary for Arm64.

Inside the dependency JAR files – This group is visible neither in your source nor in your dependency declarations. The assessment resolved the dependency tree and inspected the binaries inside each archive:

$ unzip -l cisd-jhdf5-19.04.1.jar | grep native
native/jhdf5/amd64-Linux/libjhdf5.so
native/jhdf5/arm-Linux/libjhdf5.so

$ file native/jhdf5/*/libjhdf5.so
amd64-Linux: ELF 64-bit LSB shared object, x86-64
arm-Linux: ELF 32-bit LSB shared object, ARM, EABI5

Note the second directory: it is 32-bit ARM, not aarch64. In a listing it reads as ARM support, but on Graviton the architecture-keyed loader finds no match, and no published release contains an aarch64-Linux directory. Two further dependencies arrived the same way: cisd:base:18.09.0 through jhdf5, and gov.nih.nlm.ncbi:ngs-java:2.9.0 through com.github.samtools:htsjdk:2.24.1, whose loader publishes linux-x86_64 only.

Remediate the findings

In this step, you hand the findings to the remediation skill and review the change it produces.

To remediate the findings

  1. Collect the finding IDs as the comma-separated list that --ids expects:
    atx ct findings list --repo graviton-demo::tassel-renovate --json \
    | jq -r '[.[].id] | join(",")'

  2. Pass that list to the remediation:
    atx ct remediation create --ids <finding-ids> --local

  3. Enter atx ct remediation status --id <remediation-id> to follow it.
  4. Review the branch it produced with git log and git diff --stat.

Note what you do not pass: neither the transformation nor the repository. Each finding already records the transformation that resolves it, so the remediation reads that from the findings and derives the target repositories from them. Pass --transformation-name only to pin or override that choice.

The run produced three atomic commits (the analysis reports, the change itself, then the validation reports):

build.gradle.kts | 53 ++++-
.../matrixalgebra/Matrix/DoubleMatrixFactory.java | 7 +-
graviton-analysis/ (8 report files)
graviton-validation/ (6 report files)
15 files changed, 867 insertions(+), 3 deletions(-)

Of the 867 lines added, only two files are code that runs. The remainder documents what was found and what was done.

What the remediation changed

1. It removed the x86-only dependency from the resolved classpath. The ngs-java artifact downloads linux-x86_64 native libraries at runtime and has no aarch64 search path. There is no aarch64-capable ngs-java 2.x to upgrade htsjdk to, so the remediation excluded the unused code path and recorded why:

// gov.nih.nlm.ncbi:ngs-java (transitive via htsjdk) downloads the NCBI
// ngs-sdk/ncbi-vdb natives at runtime. Those are linux-x86_64 only.
// TASSEL only uses htsjdk's pure-Java SAM/BAM/CRAM/VCF readers, so the
// unused SRA path is excluded rather than bumping htsjdk (no
// aarch64-capable ngs-java 2.x exists).
configurations.all {
    exclude(group = "openchart", module = "openchart")
    exclude(group = "gov.nih.nlm.ncbi", module = "ngs-java")
}

It then verified the exclusion took effect:

$ ./gradlew dependencies --configuration runtimeClasspath | grep -c ngs-java
0

2. It added an aarch64 native library path, ahead of the x86 payloads bundled in the JAR files. No aarch64 build of jhdf5 or cisd:base is published, and their C sources are not in the repository, so they cannot be recompiled there. The remediation added a resolution order for externally built binaries:

val tasselNativeLibDir: String =
    (project.findProperty("tasselNativeLibDir") as String?)
        ?: System.getenv("TASSEL_NATIVE_LIB_DIR")
        ?: file("src/main/native/aarch64").absolutePath

val isAarch64: Boolean = System.getProperty("os.arch").lowercase().let {
    it == "aarch64" || it == "arm64"
}

3. It applied Graviton JVM flags and wired the native path into the runtime. The test block previously set only -Xmx10g:

test {
    // -Xmx10g is architecture-neutral. The code-cache sizing flags below are the
    // Graviton (ARM64) tuning recommended for JDK 21; both are valid on x86-64 too.
    jvmArgs = listOf<String>(
        "-Xmx10g",
        "-XX:ReservedCodeCacheSize=64M",
        "-XX:InitialCodeCacheSize=64M"
    )
    if (isAarch64 && file(tasselNativeLibDir).isDirectory) {
        systemProperty("java.library.path", tasselNativeLibDir)
        systemProperty("native.libpath", tasselNativeLibDir)
    }

4. It made the state of the native libraries visible at build and run time. The build now warns on an Arm64 host when the aarch64 directory is missing, naming the libraries to supply. At the native load site, which previously logged the same message on every platform, the architecture is now included:

-	myLogger.info("TasselBlas library for system-specific BLAS/LAPACK not found. "
-			+ "Using system-independent EJML for DoubleMatrix operations.");
+	myLogger.info("TasselBlas library for system-specific BLAS/LAPACK not found for os.arch="
+			+ osArch + ". Using system-independent EJML for DoubleMatrix operations. To use"
+			+ " native BLAS on this architecture, place a matching libTasselBlas.so on"
+			+ " java.library.path.");

Together, these changes give the project a defined place for aarch64 binaries ahead of the bundled x86 ones, apply the Graviton JVM tuning, and report the state of those libraries at build and run time.

Validate the build on Arm64

In this step, you confirm the change compiles on the target architecture, which the remediation does for you on an Arm64 host.

To validate the build

  1. Check out the branch the remediation created.
  2. Enter ./gradlew clean build -x test --no-daemon.
  3. Confirm the output reports a successful build and produces the JAR file.
    BUILD SUCCESSFUL in 14s
    5 actionable tasks: 5 executed
    
    $ ls -la build/libs/sTASSEL.jar
    -rw-r--r-- 3681163 build/libs/sTASSEL.jar
    
    $ ls build/libs/lib/*.jar | wc -l
    61

The JAR file is produced and 61 dependency JAR files resolve.

Deploy to a Graviton instance and verify

This step is outside AWS Transform, as Figure 1 shows. Arm64 is not a single platform: macOS and Linux on aarch64 differ in exactly the dimension that matters here, which native binaries exist. The remediation ran locally, so the change is already on disk and ready to carry onto an instance.

To deploy and verify on Graviton

  1. Launch a c7g.2xlarge instance running Amazon Linux 2023.
  2. Install Amazon Corretto 21, OpenBLAS, and LAPACK as aarch64 packages.
  3. Copy the remediated repository to the instance.
  4. Build it on the instance with ./gradlew classes copyDependencies.
  5. Compile the native BLAS bridge for aarch64. Its C source includes a macOS-only header, so first change #include <vecLib/cblas.h> to #include <cblas.h>, then run:
    gcc -O3 -shared -fPIC -I"$JAVA_HOME/include" -I"$JAVA_HOME/include/linux" \
    -I/usr/include/openblas -o libTasselBlas.so <jni-source>.c \
    -lopenblas -llapack -lm

  6. Run the application and confirm the native library loads.

The build resolves 62 dependency JAR files on the instance. The file command confirms the native library is built for the target architecture:

libTasselBlas.so: ELF 64-bit LSB shared object, ARM aarch64

Running the application on the instance:

os.arch : aarch64
java.vendor : Amazon.com Inc. (Corretto 21)
libTasselBlas : LOADED
DoubleMatrix backend: blas
fast path active : YES (native BLAS/LAPACK)

matmul 512x512 best 12.47 ms | 21.53 GFLOP/s

The native library loads, the BLAS backend is selected, and the matrix algebra runs. The application works on Graviton: the same application and the same JVM, now on Arm64.

It is also faster. In our testing on this c7g.2xlarge instance, the same operation took 60.36 ms on the pure-Java path and 12.47 ms with the native library, roughly five times the throughput. Those two numbers compare the native and pure-Java paths on Graviton rather than Graviton against x86. They are the reason to rebuild the native libraries rather than work around them.

Scale across your portfolio

In this step, you extend the same analysis across a source and put it on a cadence, using AWS Transform-managed infrastructure.

To analyze a portfolio on a recurring schedule

  1. Analyze every repository in a source:
    atx ct remote analysis --type graviton-readiness --mode aws-managed \
    --sources graviton-demo

  2. Create a schedule so the analysis repeats:
    atx ct schedule create --name graviton-weekly --mode aws-managed \
    --execution-role <role-arn> --recurrence weekly:MONDAY \
    --type graviton-readiness --sources graviton-demo

A single submission can include up to 5,000 repositories. Schedules that run on AWS Transform-managed infrastructure need an execution role that AWS Transform assumes on each run. For how to configure it, refer to Execution role for AWS Transform-managed schedules. For how analysis and remediation are billed, refer to AWS Transform pricing.

Clean up

The Graviton-based instance incurs ongoing charges while it runs, and a recurring schedule incurs charges on every run. To avoid them, terminate the instance when you are finished:

aws ec2 terminate-instances --instance-ids <instance-id>

If you created a recurring schedule, delete it with atx ct schedule delete. The source connection and the analysis and remediation records carry no ongoing cost. To remove them, use atx ct remediation delete, atx ct analysis delete, and atx ct source remove.

Conclusion

In this post, you learned how to get a Java application ready for AWS Graviton with AWS Transform continuous modernization. The readiness assessment surfaced Arm64-incompatible native libraries that were not declared anywhere in the project. The remediation skill resolved them in code, in three atomic commits touching two files, and validated the build on Arm64. You then deployed the result to a Graviton instance yourself, where the application ran using its native BLAS library.

The readiness assessment is read-only, so you can point it at all the repositories within your source and see where your estate stands before changing anything. To get started, open the AWS Transform console and run a Graviton readiness analysis, or install the CLI and run the commands in this post.

For more information about the command surface, refer to Working with continuous modernization in the AWS Transform User Guide. For instructions on getting started with AWS Transform, refer to Setting up AWS Transform. For pricing details, refer to AWS Transform pricing.

For a related walkthrough using the interactive transformation, refer to Migrating your Java applications to AWS Graviton using AWS Transform custom. For guidance on tuning workloads after you migrate, refer to the AWS Graviton Technical Guide.

 


About the authors

Harvinder Nagpal

Harvinder Nagpal

Harvinder is a Sr. Specialist on the Agentic AI team at AWS. He focuses on the Agentic AI Developer Experience portfolio and helps customers take Agentic AI to production. He works with AWS field teams and Partners on GTM strategy and executive conversations, and he passes customer feedback to product teams. He spent 15+ years in identity, access management and cybersecurity, so he helps customers build security, governance and compliance into Agentic AI from the start.

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.

Varun Kulkarni

Varun Kulkarni

Varun is a Senior Product Manager–Technical at AWS working on AWS Transform custom and continuous modernization, which use agentic AI to help developers modernize code across their entire portfolio. Varun focuses on helping customers modernize their applications faster and keep them current over time.

Modular regression testing framework built on AWS for large-scale systems

Post Syndicated from Hannah Zhang original https://aws.amazon.com/blogs/architecture/modular-regression-testing-framework-built-on-aws-for-large-scale-systems/

For services handling high-stakes operations such as financial transactions, order processing, or eligibility decisions, regression testing has to catch behavior changes before production deployment. Traditional integration tests help, but they can suffer from unreliable dependencies that cause false positives and slow down deployment pipelines. In this post, I walk through how I built an automated regression testing framework for my team using AWS services. Each run of the framework is a simulation: it replays a sample of production traffic against the new code and compares the results to validate that changes do not break existing functionality.

To build this framework, you need a service whose requests and responses you can capture to a stream such as Amazon DynamoDB Streams, a pre-production environment that can receive replayed requests, and a deployment pipeline with a gate that can read an Amazon CloudWatch alarm.

Minimally invasive design

The framework’s power lies in its modular design. Components fit between existing blocks in your system with minimal changes to your core business logic. Stateless systems need no changes. Stateful systems add a check that recognizes replayed requests and skips side effects. The same components capture, replay, and validate traffic at the API gateway, between microservices, or at internal service boundaries.

Focus: Regression detection

This framework specifically targets no-impact validation, confirming that code changes do not break existing behavior. It does not test new business logic. A/B testing and user acceptance testing handle that. Instead, the framework gives engineering teams confidence that refactors, upgrades, and feature-flagged deployments maintain existing functionality.

Scope and applicability

The framework works best with computation-heavy, stateless systems, where replaying a request produces the same output without side effects. Examples include pricing calculators, validation engines, eligibility decision engines, and data transformation pipelines.

Stateful systems need more coordination. These include transaction processing (payments, orders, inventory) and non-idempotent writes that would create duplicate records or notifications. They also include randomized logic such as A/B assignment, and multi-step workflows such as shopping carts, where each request depends on earlier state. “Handling stateful dependencies” later in this post covers patterns for these systems.

Proven results

In more than 6 months of production use in our system, the framework caught five regressions that would have affected customers, with zero false positives that blocked valid deployments. Teams can set alarms on the share of replayed requests whose results match production (commonly 99.9 percent) to block potentially problematic deployments. This maintains faster deployment velocity through automated quality gates. The framework also standardizes testing approaches across all AWS Regions, which gives consistent validation regardless of deployment location.

Use cases: When and why to simulate for regression detection

The framework addresses three critical scenarios where engineering teams need confidence that code changes do not break existing functionality:

1. Refactoring and technical upgrades

Teams refactoring internal logic or upgrading dependencies need confidence that behavior hasn’t changed. Post-deployment monitoring only catches issues after they affect customers. Simulation provides pre-deployment validation with zero customer impact.

Example: A team upgraded their data processing algorithm’s internal data structures for performance. Unit tests passed, and simulation verified that complex real-world request patterns still produced identical business logic outputs across all Regions.

2. Feature toggle deployments

Code deployed behind feature flags creates a unique challenge: the code is deployed but not yet active. Engineering teams need confidence during the deployment phase, whereas product teams monitor the feature after toggle activation using standard product metrics.

Example: A team added a new validation rule behind a feature flag. Simulation ran against the new code path using production traffic, validating that the deployment itself didn’t introduce regressions before the product team turned on the feature.

3. Validating impact boundaries for significant changes

When product teams predict a change will affect a specific percentage of requests, engineering teams need confidence in that boundary. The change should not affect other request types.

Example: Product predicted a business rule change would affect 15 percent of requests in specific Regions. Simulation confirmed 14.2 percent impact within the predicted request patterns and 0 percent impact on other request types, validating that the change didn’t break functionality outside its intended scope.

Architecture overview: Versatile component-based design

Figure 1 shows the framework. When a deployment reaches the deployment gate, the pipeline publishes an event to Amazon Simple Notification Service (Amazon SNS). Amazon SNS delivers it to an Amazon Simple Queue Service (Amazon SQS) queue. An AWS Lambda function reads the queue and starts the AWS Step Functions workflow. The workflow turns replay on and off. While replay is on, the replay function reads captured requests from the Amazon DynamoDB stream and sends them to the new code. It logs a match result for each request to Amazon CloudWatch Logs. A CloudWatch alarm on the match fraction tells the deployment gate whether to promote the deployment.

Architecture diagram of the regression testing framework

Figure 1: Regression testing framework architecture

Component insertion flexibility

The framework is designed to be versatile. Each component can be positioned to capture inputs and outputs at any system boundary:

  • API level: Capture HTTP requests and responses at gateway or service endpoints.
  • Service level: Capture inter-service communication and message passing.
  • Database level: Capture query inputs and results for data layer validation.
  • Message queue level: Capture message processing for event-driven architectures.

You can compare end-to-end outputs or scope the comparison to one block of business logic. Anything after that block, such as formatting or downstream API calls, falls outside the comparison.

Tech stack and rationale

I chose managed AWS services to keep operational overhead low and to pay only for the resources each simulation consumes:

  • AWS Step Functions: Visual workflow orchestration with built-in error handling and state management for coordinating timed operations.
  • AWS Lambda: Serverless execution with automatic scaling. Pay only for actual simulation time.
  • Amazon DynamoDB: Low-latency access to production request data with global tables for multi-Region support. (Note: We used DynamoDB as part of our existing tech stack. You can adapt the framework to the storage system you currently use.)
  • Amazon CloudWatch: Unified logging, metrics, and alarming. Amazon CloudWatch Logs Insights supports complex queries without additional infrastructure.
  • Amazon SNS and Amazon SQS: Reliable publish/subscribe messaging for pipeline integration with retry logic and dead-letter queues.

Component 1: Traffic capture – universal storage with complete parameter logging

Core function: Captures actual production request documents and their associated responses, not synthetic data or mocks. This complete production dataset is what makes regression detection accurate by replaying the same requests that flowed through the production system with all their complexity and edge cases.

Key challenge: Capturing all parameters and context needed to reproduce the component’s behavior accurately. Missing any input parameter, request context, or metadata can lead to inaccurate replay and false regression signals.

Apply domain-specific knowledge to identify and capture all inputs your system needs for accurate replay. This includes obvious parameters (request body, headers) and less obvious context (user session state, feature flags, regional settings, timestamps). The completeness of your capture directly determines replay accuracy.

Storage flexibility: The framework design works with any storage system that can generate events:

  • Amazon DynamoDB Streams: For document-based systems.
  • Amazon Relational Database Service (Amazon RDS) and Amazon Aurora: Using database triggers or change data capture.
  • Amazon Kinesis Data Streams: For high-throughput event streaming.
  • CloudWatch Logs: For API gateway or application-level capture.
  • Amazon Managed Streaming for Apache Kafka (Amazon MSK): For Kafka-based architectures.

Component 2: Replay engine – running simulated production traffic against test environments

Core function: Takes batched production requests from storage streams and invokes test environment APIs with the same parameters, capturing responses for comparison.

Key challenge: The system needs to distinguish replayed traffic from production traffic. Without this distinction, replayed requests would be processed identically to production requests, leading to duplicate processing and unintended side effects.

The replay engine solves this by attaching simulation IDs to every replayed request:

// Add simulation markers to every replayed request
request.addProperty("simulationId", simulationId);
request.addProperty("isSimulation", true);

Component 3: Comparison engine – domain-specific output analysis

Core function: Compares specific business logic outputs between production and simulation responses to calculate match fractions. The engine extracts the outputs you’ve chosen to focus on and determines whether they match within acceptable thresholds.

Key challenge: Determining what to compare for your specific application. This requires deep domain knowledge. You need to identify which outputs represent your core business logic as opposed to downstream formatting, third-party variations, or environmental differences that do not indicate actual regressions.

Before logging, reduce each response to the fields that carry your business logic, and normalize them so equivalent outputs compare equal, for example by dropping timestamps and sorting lists. The replay engine compares the reduced results and logs one JSON line for each request. Each line has a numeric match field that is 1 when the results are equal and 0 when they differ or the replay fails. Both results stay in the line for investigating mismatches:

{"SimulationId": "<simulationId>", "match": 1, "prod": "<reduced production result>", "sim": "<reduced simulation result>"}

CloudWatch Logs Insights discovers fields in JSON log events, and the query averages match for one simulation:

filter SimulationId = "<simulationId>"
| stats avg(match) as matchFraction

When the replay completes, run the query and publish the match fraction as a custom CloudWatch metric for the deployment gate’s alarm. The implementation reference at the end of this post shows a Lambda function that does this. What constitutes a meaningful comparison depends on your system architecture and business requirements. For the full query language, see the CloudWatch Logs Insights query syntax.

Component 4: Orchestration – CI/CD pipeline integration

Core function: Manages the timing and coordination of simulation components: starts traffic capture, waits for sufficient data collection, stops capture, evaluates results, and provides pass or fail decisions for deployment gates.

Key challenge: Integrating simulation results into continuous integration and continuous delivery (CI/CD) pipelines as reliable quality gates. Deployments need automated pass or fail decisions based on simulation outcomes, not only monitoring data that requires manual interpretation.

Deployment events reach the AWS Step Functions workflow through Amazon SNS, Amazon SQS, and a Lambda function that starts the execution, with retries and error handling.

Replay starts and stops by enabling and disabling the event source mapping between the capture stream and the replay function. Lambda can take several minutes to stop or restart polling after the mapping changes. The workflow waits a few minutes after stopping replay before it evaluates results. When replay is enabled again, the mapping can resume with records captured while it was off. Set a maximum record age on the mapping to skip stale records, and use reserved concurrency on the replay function to cap the burst.

A CloudWatch alarm on the match fraction blocks the deployment when it falls below your threshold. In AWS CodePipeline, for example, an entry condition with a CloudWatchAlarm rule on the production stage blocks promotion while the alarm is in the ALARM state. Otherwise, the pipeline promotes the deployment. The implementation reference at the end of this post shows the state machine definition and the start and stop functions.

Simulation traffic controls and production safety

Critical safeguards prevent overwhelming test environments and maintain production safety:

// Hard limits prevent accidental overload
if (props.trafficFraction > 0.1) throw new Error('Traffic fraction too high');

// Concurrency controls limit resource usage
reservedConcurrentExecutions: 3

Typical configuration: 5 percent traffic replay with 200-record batching provides sufficient coverage while maintaining system stability.

Handling stateful dependencies

As noted in “Scope and applicability,” systems with stateful components can use this framework with additional patterns.

1. Idempotency controls

Services in the simulated logic path can use the simulation IDs described in Component 2 to detect replayed requests. They then skip stateful operations (database writes, notifications, external API calls) while still returning a response.

// Service checks for replay
if (!request.isSimulation()) {
    database.write(result);
    notificationService.send(result);
}

For services that need further isolation, simulation IDs can also be used to route simulation traffic to separate test instances or maintain separate simulation state.

2. Deterministic randomization

For systems using randomization (A/B assignment, sampling, shuffling), use the simulation ID as a seed:

// Production: true randomization
Random rand = new Random();

// Simulation: deterministic based on request
if (request.isSimulation()) {
    rand = new Random(request.getSimulationId().hashCode());
}

This makes simulation responses reproducible and comparable.

When to reconsider

If adding idempotency infrastructure creates an ongoing maintenance burden that exceeds the value of automated regression testing, consider whether this framework is the right fit. Manual testing or alternative validation approaches might be more practical for your system.

Cost and operational efficiency

The framework’s own Lambda functions, logging, streaming, and orchestration cost little. The primary cost driver is your own system processing replayed requests, which varies based on your architecture. The following is a breakdown of the framework costs only. Prices shown are for the US East (N. Virginia) AWS Region as of October 2026. To estimate your own costs, use the AWS Pricing Calculator.

Cost components:

  • Lambda executions: $0.0000166667 per GB-second plus $0.0000002 per request.
  • CloudWatch Logs: $0.50 per GB ingested plus $0.03 per GB stored (monthly).
  • CloudWatch Logs Insights: $0.005 per GB scanned per query.
  • Step Functions: $0.025 per 1,000 state transitions.
  • DynamoDB Streams: no read charge when standard AWS Lambda functions read the stream (Lambda Managed Instances incur Streams charges).
  • Amazon SNS and Amazon SQS: $0.40–$0.50 per million requests.

Example calculation (24-hour simulation, 5 percent of 100,000 daily requests):

  • 5,000 replayed requests × 1 second average duration × 256 MB = about $0.02 Lambda cost.
  • 5,000 log entries × 5 KB average = 25 MB logs = about $0.013 ingestion plus about $0.001 storage.
  • DynamoDB Streams reads: $0 (included in the preceding Lambda cost).
  • One evaluation query scanning 25 MB = about $0.0001 Logs Insights.
  • Step Functions and messaging costs = about $0.01.

Total estimated cost: about $0.05 for this example scenario.

Multi-Region deployment multiplies costs by the number of Regions. Higher traffic volumes scale proportionally. For example, 500,000 daily requests (25,000 replayed) cost approximately $0.25 per simulation.

Scale the calculation based on your traffic volume and simulation frequency. Most importantly, the confidence to deploy faster and the hours saved on manual validation far exceed the simulation costs.

Getting started: Phased implementation approach

Build the framework in three phases. Each phase is usable before the next one starts.

Phase 1 – Core components: Set up traffic capture with your chosen event source, create a replay engine with simulation IDs, implement centralized output analysis with structured logging, and build orchestration with Step Functions.

Phase 2 – Automated verification: Design a match fraction calculation with business logic for filtering variances, create CloudWatch Logs Insights queries, and set up CloudWatch alarms for quality gates.

Phase 3 – Full automation: Integrate with deployment pipelines, deploy across multiple Regions, build monitoring dashboards, and tune thresholds based on real data.

Implementation reference

The following sample code is generalized from my team’s production implementation and is not intended for production use as written. Replace the placeholder names and Amazon Resource Names (ARNs) with your own.

Replay function

@Log4j2
public class ReplayHandler implements RequestHandler<DynamodbEvent, Void> {
    private static final ObjectMapper JSON = new ObjectMapper();
    private final Random random = new Random();
    private final SsmClient ssm = SsmClient.create();
    private final TestServiceClient testService = new TestServiceClient(System.getenv("TEST_ENDPOINT"));

    @Override
    public Void handleRequest(DynamodbEvent event, Context context) {
        SimulationProps sim = SimulationProps.fromJson(
                ssm.getParameter(r -> r.name(System.getenv("SIMULATION_PARAMETER"))).parameter().value());

        for (DynamodbEvent.DynamodbStreamRecord record : event.getRecords()) {
            if (!"INSERT".equals(record.getEventName())) {
                continue;
            }
            CapturedCall captured = CapturedCall.from(record.getDynamodb().getNewImage());
            if (captured.request().isSimulation() || random.nextDouble() > sim.trafficFraction()) {
                continue;
            }
            String prodResult = reduce(captured.response());
            String simResult;
            try {
                simResult = reduce(testService.call(captured.request().withSimulationId(sim.id())));
            } catch (Exception e) {
                simResult = "REPLAY_FAILED: " + e.getMessage();
            }
            log.info(JSON.createObjectNode()
                    .put("SimulationId", sim.id())
                    .put("match", prodResult.equals(simResult) ? 1 : 0)
                    .put("prod", prodResult)
                    .put("sim", simResult)
                    .toString());
        }
        return null;
    }
}

The AWS Systems Manager Parameter Store parameter named in SIMULATION_PARAMETER holds:

{"id": "<execution name>", "trafficFraction": <fraction of traffic to replay>}

CapturedCall, SimulationProps, TestServiceClient, and reduce stand in for your own request model, simulation settings, service client, and response reduction. reduce returns the normalized business-logic fields as a string.

State machine definition

{
  "StartAt": "StartSimulation",
  "States": {
    "StartSimulation": {
      "Type": "Task",
      "Resource": "arn:aws:states:::lambda:invoke",
      "Parameters": {
        "FunctionName": "<start-simulation-function-arn>",
        "Payload": {"id.$": "$$.Execution.Name", "trafficFraction.$": "$.trafficFraction", "durationSeconds.$": "$.durationSeconds"}
      },
      "OutputPath": "$.Payload",
      "Catch": [{"ErrorEquals": ["States.ALL"], "ResultPath": "$.error", "Next": "StopSimulation"}],
      "Next": "WaitForSimulation"
    },
    "WaitForSimulation": {
      "Type": "Wait",
      "SecondsPath": "$.durationSeconds",
      "Next": "StopSimulation"
    },
    "StopSimulation": {
      "Type": "Task",
      "Resource": "arn:aws:states:::lambda:invoke",
      "Parameters": {"FunctionName": "<stop-simulation-function-arn>", "Payload.$": "$"},
      "OutputPath": "$.Payload",
      "Next": "WaitForInFlightReplays"
    },
    "WaitForInFlightReplays": {
      "Type": "Wait",
      "Seconds": 300,
      "Next": "EvaluateSimulationResults"
    },
    "EvaluateSimulationResults": {
      "Type": "Task",
      "Resource": "arn:aws:states:::lambda:invoke",
      "Parameters": {
        "FunctionName": "<evaluate-simulation-results-function-arn>",
        "Payload": {"id.$": "$$.Execution.Name", "simulationStartTime.$": "$$.Execution.StartTime"}
      },
      "End": true
    }
  }
}

Start and stop functions

import {LambdaClient, UpdateEventSourceMappingCommand} from "@aws-sdk/client-lambda"
import {PutParameterCommand, SSMClient} from "@aws-sdk/client-ssm"

const lambda = new LambdaClient({})
const ssm = new SSMClient({})

const setReplayEnabled = (enabled: boolean) =>
    lambda.send(new UpdateEventSourceMappingCommand({
        UUID: process.env.REPLAY_LAMBDA_TRIGGER_UUID,
        Enabled: enabled,
    }))

export const startSimulation = async (event: {id: string; trafficFraction: number; durationSeconds: number}) => {
    await ssm.send(new PutParameterCommand({
        Name: process.env.SIMULATION_PARAMETER,
        Value: JSON.stringify({id: event.id, trafficFraction: event.trafficFraction}),
        Type: "String",
        Overwrite: true,
    }))
    await setReplayEnabled(true)
    return event
}

export const stopSimulation = async (event: object) => {
    await setReplayEnabled(false)
    return event
}

Evaluation function

import {CloudWatchLogsClient, GetQueryResultsCommand, StartQueryCommand} from "@aws-sdk/client-cloudwatch-logs"
import {CloudWatchClient, PutMetricDataCommand} from "@aws-sdk/client-cloudwatch"

const logs = new CloudWatchLogsClient({})
const cloudwatch = new CloudWatchClient({})

const matchFractionQuery = (simulationId: string) =>
    `filter SimulationId = "${simulationId}" | stats avg(match) as matchFraction`

const publishMatchFraction = (value: number) =>
    cloudwatch.send(new PutMetricDataCommand({
        Namespace: "RegressionSimulation",
        MetricData: [{MetricName: "MatchFraction", Value: value, Unit: "None"}],
    }))

export const handler = async (event: {id: string; simulationStartTime: string}) => {
    const {queryId} = await logs.send(new StartQueryCommand({
        logGroupName: process.env.REPLAY_LOG_GROUP,
        startTime: Math.floor(Date.parse(event.simulationStartTime) / 1000),
        endTime: Math.floor(Date.now() / 1000),
        queryString: matchFractionQuery(event.id),
    }))

    let result
    do {
        await new Promise((resolve) => setTimeout(resolve, 5000))
        result = await logs.send(new GetQueryResultsCommand({queryId}))
    } while (result.status === "Scheduled" || result.status === "Running")

    const value = result.results?.[0]?.find((field) => field.field === "matchFraction")?.value
    if (result.status !== "Complete" || !value) {
        await publishMatchFraction(0)
        throw new Error(`Simulation ${event.id} produced no match fraction (query status ${result.status})`)
    }

    const matchFraction = parseFloat(value)
    await publishMatchFraction(matchFraction)
    return {simulationId: event.id, matchFraction}
}

Conclusion

This component-based simulation framework transformed our deployment process from manual and time-intensive to automated and reliable, saving hours per deployment while achieving high accuracy in regression detection. The modular design means the same building blocks can be inserted anywhere in your system architecture to validate that code changes do not break existing functionality.

Look at how your team catches regressions today. If refactors, dependency upgrades, or feature-flagged releases reach production with only synthetic test coverage, or if regressions surface first in post-deployment alarms, replaying production traffic before deployment closes that gap. Start with one stateless component, such as a pricing or validation engine, where replay needs no changes to your service code.

To get started, see the AWS Step Functions detail page and the AWS Step Functions Developer Guide. This framework also uses AWS Lambda, Amazon DynamoDB, Amazon CloudWatch, Amazon SNS, and Amazon SQS.


About the author

Hannah Zhang

Hannah Zhang

Hannah is a Software Development Engineer on the Worldwide Returns and Recommerce Core Tech team at Amazon. Hannah builds large-scale, low-latency services that process high volumes of production traffic.

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.

Optimizing Apache HBase availability on Amazon EMR, Part 2: Diagnose and tune compaction

Post Syndicated from Reekunj Parmar original https://aws.amazon.com/blogs/big-data/optimizing-apache-hbase-availability-on-amazon-emr-part-2-diagnose-and-tune-compaction/

This post shows you how to diagnose and tune compaction in Apache HBase on Amazon EMR. Compaction is the background process that merges store files. When it competes with your workload during peak hours, you can see higher read and write latency, write stalls, and RegionTooBusyException errors. Amazon EMR on Amazon Simple Storage Service (Amazon S3), you can also see more 503 Slow Down responses when you increase your cluster’s request rate.

This is the second post in a two-part series on operating Apache HBase on Amazon EMR:

  • Part 1 covers the three-level troubleshooting model and three availability issues: an HBase coordinator that doesn’t finish initializing, a RegionServer that stops unexpectedly, and HBase regions that stay in transition (RIT).
  • Part 2 (this post) covers performance: how to confirm that compaction is the cause, which parameters to tune first, and when to contact AWS Support.

This post covers the following:

  • How compaction affects performance.
  • How to confirm whether compaction is causing the latency.
  • The compaction parameters to tune, their defaults, and what each one does.
  • Practices that reduce compaction work.
  • When to stop and contact AWS Support, and what to bring to a support case.

This post doesn’t cover the following:

  • Coordinator startup, RegionServers that stop unexpectedly, and regions in transition, which are covered in Part 1 of this series.
  • Compaction algorithm internals or writing custom compaction policies.
  • Schema design and row key distribution (the Practices that reduce compaction work section covers how they affect compaction).

This post is for operations teams, data engineers, HBase administrators, and site reliability engineers (SREs) who see recurring latency spikes, write stalls, RegionTooBusyException errors, or high Amazon S3 request rates during compaction on HBase on Amazon EMR.

Terminology

Apache HBase names the process that coordinates the cluster HMaster, and Amazon EMR runs it on the primary node. This post refers to it as the HBase coordinator. Names that contain master, such as the hbase-master service and the hbase-hbase-master-*.log log files, appear only in commands and log output, where you need the exact name.

In HBase, a region is a range of rows in a table, and a RegionServer is the process that serves regions. Neither is related to an AWS Region.

Prerequisites

  • Read Part 1 of this series, in particular the Three levels of troubleshooting and Quick reference sections.
  • Confirm that you have access to the HBase web UI (coordinator on port 16010, RegionServer on port 16030).
  • Confirm that you have SSH access to the primary and core nodes.
  • Know whether your cluster uses Hadoop Distributed File System (HDFS) or Amazon S3 as its storage mode, and how to apply configuration changes through the hbase-site classification in Amazon EMR. For storage-mode specifics, see HBase on Amazon S3.
  • Be familiar with minor and major compaction in HBase.

How compaction affects performance

By default, HBase runs a major compaction roughly every seven days and uses a jitter factor of 0.5 to spread the start times so that HBase regions don’t all compact at once. For guidance specific to Amazon EMR, see the HBase best practices in the Amazon EMR best practices guide.

Major compaction reads and rewrites all store files in a region. It improves read performance and removes deleted and expired cells, but when it runs during peak hours it competes with client requests and can increase latency. Tuning compaction means controlling when major compaction runs and how much I/O it uses.

Compaction decision flow

Before you change any parameters, use the following decision flow to identify the cause.

Compaction decision flow diagram showing how to confirm compaction pressure and the six tuning steps to work through in order

Figure 1: Compaction decision flow

The flow has the following steps:

  • If latency is high, check whether compaction is running on the affected RegionServer. If it isn’t, investigate garbage collection (GC), disk, and network instead.
  • If compaction is running, check whether the compaction queue is growing. If it isn’t, check for GC pauses.
  • If compaction is running and the queue is growing, work through the following steps in order:
    1. On HBase on Amazon S3 with Amazon EMR 7.10 to 7.13, set the S3A read policy to sequential before you change any compaction parameter. See Step 3 in Diagnose compaction pressure.
    2. Lower the throughput bounds (hbase.hstore.compaction.throughput.*) to reduce the I/O that compaction takes from client requests. The queue can grow while the limit is lower. HBase removes the limit when any store reaches hbase.hstore.blockingStoreFiles, so the limit doesn’t keep a store at the blocking threshold.
    3. If latency is still high, tune compaction frequency (hbase.hstore.compaction.min, hbase.hstore.compaction.max, and hbase.hstore.compaction.min.size).
    4. If latency is high only during peak hours, set off-peak hours (hbase.offpeak.start.hour and hbase.offpeak.end.hour) so that more compaction work runs outside them.
    5. If compaction still affects peak traffic, turn off automatic major compaction (hbase.hregion.majorcompaction=0) and schedule it yourself.
    6. If none of these steps resolves the issue, contact AWS Support. The cause might be cluster capacity or schema design.

Note: Changing the previous configuration requires EMR HBase Restart. For reconfiguration behavior, refer to Reconfiguration behaviors in the Amazon EMR Management Guide.

Signs of compaction pressure

The following symptoms indicate compaction pressure. They don’t all appear at once. Start with the first two, because you can confirm them in the HBase web UI:

  • Read and write latency rises on some RegionServers but not others. The affected set changes over time as different regions reach their compaction window.
  • The compaction queue length on the affected RegionServer keeps increasing.
  • Long-running reads (report generation, Apache Spark table scans) pause and then resume.
  • Clients receive RegionTooBusyException, call timeouts, or retries. The RegionServer log shows Region is too busy due to exceeding memstore size limit warnings for the same regions.
  • Writes stall periodically. When a store reaches hbase.hstore.blockingStoreFiles store files, HBase delays MemStore flushes until compaction reduces the count, for up to hbase.hstore.blockingWaitTime (90 seconds by default). If the MemStore exceeds hbase.hregion.memstore.flush.size multiplied by hbase.hregion.memstore.block.multiplier in the meantime, HBase blocks updates to the region.
  • On HBase on Amazon S3, more requests return 503 Slow Down when the request rate from your cluster to an Amazon S3 prefix is high. These responses ask your cluster to reduce its request rate. Compaction reads and rewrites store files in Amazon S3, so it adds to that rate.
  • On Amazon EMR 7.10 to 7.13 with HBase on Amazon S3, compactions, scans, and bulk loads run slower than expected and the number of HFiles keeps increasing. See Step 3 in Diagnose compaction pressure.
  • The pattern recurs on a weekly rhythm, which matches the default seven-day major compaction interval.

Diagnose compaction pressure

Work through the following steps in order. Step 1 uses the HBase web UI (Level 1). Steps 2 and 3 use logs, operating system tools, and configuration files (Level 2). None of these checks change the cluster.

Step 1 (Level 1): Check the HBase web UI

  • In the HBase web UI, sort RegionServers by request count and by store file count to find the outliers. A server with a much higher store file count might be running, or waiting for, a compaction.
  • On the RegionServer web UI of an affected server, check the compaction queue length and store file count per region. A queue that keeps growing means compaction can’t keep up with your write volume, so add capacity or tune your configuration.
  • Check the BlockCache hit rate. A lower hit rate also increases latency. On HBase on Amazon S3, RegionServers cache reads in the BlockCache (memory) and the BucketCache (local disk). A cache miss reads the store file from Amazon S3, which has higher latency than a local read. If the hit rate dropped when compaction started, compaction might be replacing frequently read data in the cache.

Step 2 (Level 2): Check the logs and the operating system

Confirm that compaction is running, and on which HBase regions:

grep -E "Starting compaction|Completed (major )?compaction|too many store files" \
/var/log/hbase/hbase-hbase-regionserver-*.log | tail -40

Rule out GC as the cause, because heavy compaction and heap pressure look the same to clients:

grep -E "JvmPauseMonitor|Detected pause in JVM" \
/var/log/hbase/hbase-hbase-regionserver-*.log | tail -20

Check CPU, memory, and disk usage on the host:

free -m                  # check free memory
top -b -n1 | head -20    # CPU
df -h                    # disk capacity

Use the canary tool to measure read latency per HBase region. The tool writes its results to the console and to /var/log/hbase/hbase.log. Save the output as a baseline to compare against after each change:

sudo -u hbase hbase canary my_table

Check the store file layout of the table to see whether it has many small files (from frequent flushes) or a few large ones. Store files are under the HBase root directory, which is in HDFS or Amazon S3, depending on your storage mode. On HBase on Amazon S3 with Amazon EMR 7.4 and later, HBase tracks the store files it reads in a meta file in each store directory instead of relying on directory listings, so use the store file count in the RegionServer web UI as the count of active files:

grep -A1 hbase.rootdir /etc/hbase/conf/hbase-site.xml   # find the HBase root directory
sudo -u hbase hbase hfile -f <hbase.rootdir>/data/default/my_table/<region>/<cf>/<hfile> -m -s

Step 3 (Level 2): Check the S3A read policy (Amazon EMR 7.10 to 7.13)

Starting with Amazon EMR 7.10, HBase on Amazon S3 uses the S3A file system client, and fs.s3a.experimental.input.fadvise defaults to normal. In this mode, S3A can switch to a random read policy even when HBase continues to read sequentially, which slows compactions, scans, and bulk loads. Use the recommended setting for Amazon EMR 7.10, 7.11, 7.12, and 7.13. The symptoms are similar to compaction pressure: slow compactions, an increasing number of HFiles, and blocked flushes that return RegionTooBusyException.

Check the release label and the current setting:

aws emr describe-cluster --cluster-id <cluster-id> --query 'Cluster.ReleaseLabel'
grep -A1 fs.s3a.experimental.input.fadvise /etc/hbase/conf/hbase-site.xml

If the release is 7.10 to 7.13 and the property isn’t set, or is set to normal, set it to sequential in the hbase-site classification before you tune compaction. Changing the setting requires a restart, so it’s a Level 3 action:

[
    {
        "Classification": "hbase-site",
        "Properties": {
            "fs.s3a.experimental.input.fadvise": "sequential"
        }
    }
]

Apply the setting to hbase-site.xml on all nodes, then restart the HBase coordinator and RegionServer processes. Setting the property on individual commands instead doesn’t improve compaction and scan performance. For more information, see HBase on Amazon S3 in the Amazon EMR Release Guide.

Compaction tuning parameters

The following table lists the compaction parameters that this post covers. Apply changes through the hbase-site configuration classification in Amazon EMR. Changing these parameters is a Level 3 action. Change one parameter at a time and compare the results with the canary baseline from Step 2, because several of these parameters interact.

Note: The Amazon EMR column lists defaults from the HBase on Amazon S3 documentation. Where a default isn’t listed there, check the effective value in /etc/hbase/conf/hbase-site.xml on your cluster, and verify component versions on the Amazon EMR release components page. For example, hbase.hstore.blockingStoreFiles is 16 in Apache HBase 2.x, but Amazon EMR sets it to 10 for HBase on Amazon S3.

Parameter What it does Apache HBase 2.x default Amazon EMR default (HBase on Amazon S3)
hbase.hstore.compaction.throughput.higher.bound Upper limit on compaction throughput per RegionServer when store file pressure is high. 104857600 (100 MB/s) Not listed
hbase.hstore.compaction.throughput.lower.bound Lower limit on compaction throughput per RegionServer when store file pressure is low. 52428800 (50 MB/s) Not listed
hbase.hstore.compaction.min Minimum number of eligible store files before a minor compaction runs. If it isn’t set, HBase uses hbase.hstore.compactionThreshold. 3 Not listed
hbase.hstore.compaction.max Maximum number of store files included in a single minor compaction. 10 Not listed
hbase.hstore.compaction.min.size HBase always considers store files smaller than this size eligible for minor compaction. 134217728 (128 MB) Not listed
hbase.hstore.compaction.ratio Size ratio that decides which larger files are included in a minor compaction. 1.2 Not listed
hbase.hstore.blockingStoreFiles Number of store files in a store at which HBase delays MemStore flushes, for up to hbase.hstore.blockingWaitTime (90 seconds), until compaction reduces the count. 16 10
hbase.hregion.memstore.flush.size MemStore size, in bytes, at which HBase flushes to a new store file. 134217728 (128 MB) 134217728 (128 MB)
hbase.hregion.memstore.block.multiplier HBase blocks updates when a MemStore exceeds the product of hbase.hregion.memstore.flush.size and this value. 4 4
hbase.hregion.max.filesize Region size at which HBase splits the region. 10737418240 (10 GB) 10737418240 (10 GB)
hbase.offpeak.start.hour hbase.offpeak.end.hour Off-peak window (hours 0–23). During this window, the larger hbase.hstore.compaction.ratio.offpeak (default 5.0) applies, and compaction throughput isn’t limited unless you set hbase.hstore.compaction.throughput.offpeak. -1 (no off-peak window) Not listed
hbase.hregion.majorcompaction Time between automatic major compactions, in milliseconds. 0 turns off automatic major compaction. 604800000 (7 days) Not listed
hbase.hregion.majorcompaction.jitter HBase uses this value to spread major compaction start times so that Regions do n’t all compact at once. 0.5 Not listed
hbase.bucketcache.size Local disk space, in MB, on each RegionServer for the BucketCache (instance store and Amazon Elastic Block Store (Amazon EBS) volumes). Not set 8,192 MB
fs.s3a.experimental.input.fadvise S3A read policy for HBase on Amazon S3. See Step 3 in Diagnose compaction pressure. Not applicable normal (7.10 and later)

Warning: If you turn off automatic major compaction (hbase.hregion.majorcompaction=0), you are responsible for scheduling it. Minor compactions still merge store files, but delete markers and deleted cells stay in store files until a major compaction runs. This slows reads and delays reclaiming storage. If you turn it off:

  • Schedule major_compact yourself, per table, in a maintenance window. Run it on the primary cluster only, because read-replica clusters must not run manual compactions. On Amazon EMR releases earlier than 7.4.0, also turn off compaction on the read-replica cluster (hbase.regionserver.compaction.enabled=false). From 7.4.0, store file tracking makes this unnecessary.
  • Alarm when the store file count of any store approaches hbase.hstore.blockingStoreFiles (for example, at 80 percent of that value), so that you notice if the schedule slips before writes are delayed.

Use the following HBase shell commands to run a major compaction and check its progress:

hbase> major_compact 'my_table'
hbase> major_compact 'my_table', 'cf1'   # a single column family
hbase> compaction_state 'my_table'       # check progress

Practices that reduce compaction work

Tuning limits the effect of compaction on your workload. The following practices reduce how much compaction work the cluster has to do:

  • Limit region size and the number of regions per RegionServer. Large regions make major compaction expensive, because major compaction rewrites every store file in the region. HBase splits a region when it reaches hbase.hregion.max.filesize (10737418240 bytes, or 10 GB, by default on HBase on Amazon S3). Pre-split tables where you can predict the key distribution, using the SPLITS option of the HBase shell create command or the RegionSplitter tool.
  • Fix hotspotting at the row key. A row key that concentrates writes on one region (sequential timestamps, monotonically increasing IDs) produces frequent flushes and repeated compaction on a single RegionServer. To spread writes across HBase regions, salt, hash, or reverse the key.
  • Reduce small flushes. Many small MemStore flushes create many small store files, which increases compaction work. Compare the MemStore flush size (hbase.hregion.memstore.flush.size) with your write pattern. If regions flush every few seconds, the flush size might be too small, or the RegionServer might be under memory pressure. On HBase on Amazon S3, consider increasing hbase.hregion.memstore.flush.size and hbase.hregion.memstore.block.multiplier. This increases the time between compactions, but it also increases replication lag if you use a read-replica cluster. Make sure that the RegionServer heap can hold the larger MemStores.
  • Size the BucketCache on HBase on Amazon S3. The BucketCache stores reads on the local instance store and Amazon EBS volumes of each RegionServer. The more of your dataset it holds, the fewer reads go to Amazon S3, so compaction competes less with client reads. Increase hbase.bucketcache.size (default 8,192 MB) and choose an instance type with enough instance storage. See HBase on Amazon S3 and the Amazon S3 best practices in the Amazon EMR best practices guide.
  • Use multiple primary nodes. On an Amazon EMR cluster with multiple primary nodes, the HBase coordinator keeps running if one primary node in your cluster stops, so region assignment and split procedures continue. See Plan and configure primary nodes.
  • Alarm on compaction metrics. Set alarms on compaction queue length and store file count per region, which increase as compaction falls behind. Also alarm on Java virtual machine (JVM) pause frequency and the number of stopped RegionServers. For the metrics that are available, see the observability guidance in the Amazon EMR best practices guide.

When to stop and contact AWS Support

Some repair actions change cluster metadata and are difficult to reverse. Stop and open a case with AWS Support when any of the following is true:

  • HBCK2 bypass or setRegionState is your next step. Both can leave procedures or regions in an inconsistent state that you then must correct, and bypass might require a coordinator restart to release locks. AWS Support can validate your diagnosis and confirm the command before you run it.
  • Your next step is to delete znodes. Removing /hbase children discards state that HBase keeps in ZooKeeper, such as the location of hbase:meta, RegionServer registrations, and, on Amazon EMR, store file tracking data. This makes the problem harder to resolve. Don’t delete znodes as a first step.
  • A procedure is stuck and you cannot identify why from the logs. If three thread dumps and the coordinator log have not explained what is holding the procedure, AWS Support can help identify the cause.
  • Several RegionServers stop at the same time. Look for a cause on your cluster that the RegionServers share, such as the network configuration between cluster nodes, the ZooKeeper ensemble, or HDFS.
  • You have tuned compaction parameters twice and latency has not improved. The cause might be schema design, row key distribution, or cluster capacity, and further tuning can hide it without resolving it.
  • The stack trace contains exceptions that you don’t recognize. If the error doesn’t appear in this post or the Apache HBase Reference Guide, it might be an Apache HBase issue that is fixed in a later release. Check the Amazon EMR Release Guide and the Apache HBase JIRA before debugging further.

What to bring to the support case

Collect the following information before you open the case:

Artifact How to get it
Coordinator log extract (first ERROR plus 100 lines of context) Run grep -n -m1 "ERROR" /var/log/hbase/hbase-hbase-master-*.log, then sed -n 'X,+100p' from that line number
RegionServer log extract from the affected server Run the same commands on the affected core node against /var/log/hbase/hbase-hbase-regionserver-*.log
Thread dumps (3, taken 30 seconds apart) from the affected JVM Find the process ID with sudo jps -l, then run sudo -u hbase jstack -l <PID> three times, 30 seconds apart
Stuck procedure identifiers list_procedures in the HBase shell, or the Procedures and Locks page in the HBase web UI
Encoded region names involved From the HBCK Report tab or the Regions in Transition list
Amazon EMR release and HBase version aws emr describe-cluster --cluster-id <cluster-id> --query 'Cluster.ReleaseLabel' for the release, and sudo -u hbase hbase version for the HBase version
Storage mode and S3A read policy grep -A1 -E "hbase.rootdir\|fs.s3a.experimental.input.fadvise" /etc/hbase/conf/hbase-site.xml
Timeline: when it started, what changed Amazon CloudWatch metrics, cluster events in the Amazon EMR console, and any configuration changes or scaling actions
Compaction metrics: queue length, store file count, duration of recent compactions The RegionServer web UI, or the Completed compaction and Completed major compaction log lines, which include how long each compaction took
Any configuration changes you have already made List the parameters you changed and their before and after values

Providing this information up front reduces the number of follow-up requests from AWS Support.

Quick reference: Compaction log signatures

Search for the first occurrence of each signature in the following table, which shows when the condition started. Unless the table says otherwise, the signatures appear in the RegionServer log. For example:

grep -m1 -n "too many store files" /var/log/hbase/hbase-hbase-regionserver-*.log
Signature Meaning
too many store files A store reached the blocking threshold. HBase is delaying MemStore flushes until compaction reduces the number of store files.
RegionTooBusyException A MemStore exceeded hbase.hregion.memstore.flush.size multiplied by hbase.hregion.memstore.block.multiplier, for example because flushes are delayed by too many store files. The RegionServer logs Region is too busy due to exceeding memstore size limit, and clients receive the exception.
Completed major compaction A major compaction finished on that store. A major compaction that rewrote every file also shows (all).
Completed compaction A minor compaction finished. The line includes the number of files, the resulting store size, and how long the compaction took. Use it to establish a baseline.
Detected pause in JVM / JvmPauseMonitor A GC pause. Compare its timestamp with the compaction start time to see which came first.
SlowDown Amazon S3 returned HTTP 503 with the error code SlowDown, which asks your cluster to reduce its request rate to a prefix. Compaction adds to the request rate on HBase on Amazon S3.
ServerCrashProcedure Appears in the coordinator log (hbase-hbase-master-*.log). HBase is reassigning the regions of a RegionServer that stopped. Check whether a GC pause during heavy compaction caused it to stop.
Finished flush of A MemStore flush completed and wrote a new store file. Many of these lines in a short period mean frequent small flushes, which increase compaction work.

Conclusion and next steps

In this post, you learned how to confirm whether compaction is causing latency on HBase on Amazon EMR, and how to tune it, starting with the least invasive change.

For coordinator startup, RegionServers that stop unexpectedly, and regions in transition, see Part 1 of this series.

Next steps

  • Add the triage flow from both posts to your team’s runbook, with your own alarm names, dashboards, and on-call procedures.
  • Set up the alarms described in Practices that reduce compaction work.
  • Stage the HBCK2 jar for your HBase version on the cluster now, so that it’s ready before you need it.
  • Record a compaction baseline. Run grep -E "Completed (major )?compaction" across a week of RegionServer logs to learn the normal duration and frequency for your tables, so that you can recognize unusual behavior.
  • Review the guidance in the HBase best practices and troubleshooting sections of the Amazon EMR best practices guide.

About the authors

Reekunj Parmar

Reekunj Parmar

Reekunj is a Senior Technical Account Manager at Amazon Web Services, focused on Data Analytics. He works with customers to design and architect solutions based on Analytics services in their enterprise cloud environments. With more than 10 years of experience in Analytics, Reekunj helps organizations build secure, resilient architectures.

Ishan Sharma

Ishan Sharma

Ishan is a Cloud Support Engineer at Amazon Web Services and an Amazon EMR subject matter expert. He specializes in helping enterprise customers troubleshoot, optimize, and architect solutions across Amazon EMR and big data technologies. Ishan works closely with organizations to design and operate reliable, high-performance data processing workloads in the cloud.

Ram Nethi

Ram Nethi

Ram is a Senior Solutions Architect at Amazon Web Services, specializing in generative AI, agentic AI architectures, big data, cloud migrations, and application modernization. He guides enterprise and strategic customers across industry domains from legacy environments to production-ready AI workloads on AWS, designing scalable solutions that span infrastructure, DevOps automation, cybersecurity, and end-to-end cloud-native architectures.

Navigating messaging requirements in betting and gaming technology applications (Part 2: Executing the registration and maintaining compliance)

Post Syndicated from Meghana Dasigi original https://aws.amazon.com/blogs/messaging-and-targeting/navigating-messaging-requirements-in-betting-and-gaming-technology-applications-part-2-executing-the-registration-and-maintaining-compliance/

This is Part 2 of a two-part series for developers and technical teams at betting and gaming operators registering SMS messaging for multi-factor authentication (MFA) and account verification through AWS End User Messaging. Part 1 covered why betting and gaming operators face heightened carrier scrutiny, how the AWS and carrier registration roles work, and how to prepare before you apply.

Here in Part 2, we move from preparation to execution: what to include in your application to maximize approval odds, how to maintain compliance and deliverability after approval, and what to do if your registration is denied.

Prerequisites: This guidance applies exclusively to transactional and MFA messaging (for example, one-time passcodes, account verification, and security alerts). AWS End User Messaging does not support marketing or promotional messages for the betting and gaming industry. If you have not read Part 1, we recommend starting there.

The registration process: Best practices for approval

The following sections cover what to include in your application to maximize your chances of registration approval.

Provide detailed use cases

Don’t submit vague use-case descriptions. “We send notifications to users” is not sufficient. For each message type, explain:

  • The specific trigger (for example, “sent when a user logs in from an unrecognized device”).
  • The audience (for example, “verified players who have completed account registration and opted in to MFA”).
  • The content, including your actual one-time password (OTP) template.
  • The basis (for example, “account security notification, MFA only, not promotional”).
  • The expected volume (for example, “approximately 5,000 to 15,000 messages monthly based on current active user count”).

Document your opt-in workflow

Opt-in documentation is one of the most scrutinized components of a betting and gaming technology company’s registration. Include the following:

Implement double opt-in – A double opt-in process (where a user provides their number, receives a confirmation message, and replies to confirm) creates a clear consent record and reduces complaint rates.

Make opt-out instructions explicit in every message – Every message you send should include clear opt-out instructions (for example, “Reply STOP to unsubscribe”).

Document the consent flow with screenshots or flow diagrams – Show exactly where and how users provide consent on your application. Include the exact language of your consent disclosure.

Sample MFA opt-in screen for exampleGames showing the text-message consent disclosure, STOP and HELP instructions, and Terms & Conditions and Privacy Policy links

Figure 1: A sample double opt-in consent flow showing the SMS consent disclosure, STOP and HELP instructions, and links to terms and conditions and the privacy policy

Include relevant operating documentation

Don’t wait to be asked. Include your betting and gaming technology licenses, regulatory approvals, and messaging compliance documentation with your initial application. Providing this detail helps reduce back-and-forth with reviewers and increases your chances of approval.

Post-registration: Maintaining compliance and deliverability

Approval by the carrier is the beginning, not the end. Betting and gaming technology operators that treat registration as a one-time hurdle often find their messaging programs throttled or suspended months later. Long-term deliverability requires ongoing discipline, including the following best practices:

Manage message volume carefully

Declare your expected message volume during registration. Expressly state how many messages you plan to send monthly in the registration.

Maintain consistent sending patterns. Irregular volume (quiet for weeks, then a massive burst) looks like spam or suspicious activity to carriers, aggregators, and AWS monitoring systems. Sudden spikes can result in throttling or suspension, even if the traffic is legitimate. If you expect a temporary increase (major sporting events or new market launches, for example), open an AWS Support case in advance so the team can note the expected volume change and help prevent automated throttling during the spike.

Monitor and optimize your content

Regularly review message content. Regulations change, carrier policies evolve, and language that was acceptable last year might be filtered today.

Avoid language that could trigger gambling-related filters. Work with AWS Support to understand which terms are most likely to cause issues in your specific use cases.

Focus on account security messaging only. Keeping your active message templates strictly within that scope is both a compliance requirement and an effective way to maintain deliverability.

Manage feedback proactively

Set up alerts for spam complaint spikes. Investigate immediately. Carriers, aggregators, and AWS can suspend your messaging if complaint rates stay elevated.

Track delivery rates by template. If your password reset messages drop while OTP delivery stays stable, that’s a signal worth investigating. It is a sign of content-based carrier filtering, origination identity blocking, or malicious account takeover attempts targeting your application.

Maintain open communication with AWS Support. Do not hesitate to reach out to AWS Support if you have any questions.

If your registration is denied

Denial is a common outcome for gaming and betting registrations. If your application is rejected, here is how to move forward.

Understand the rejection

Review the rejection reason against official documentation. AWS publishes the full list of rejection reasons with remediation steps at Understanding rejection reasons. When your registration is rejected, the console displays a specific reason. Match it to the documentation to understand exactly what needs to be changed.

Rejection reasons most relevant to gaming registrations:

Category Rejection Reason (exact text) What It Means Action
Brand Brand associated with or website references gambling which is prohibited by mobile operators The carrier flagged your brand based on your website content or industry classification, regardless of your messaging use case. Make sure your website clearly separates gaming operations from your MFA/security messaging program. Consider whether a dedicated subdomain for account security communications would reduce this signal.
Campaign Use case is considered restricted or disallowed by mobile operators: Gambling Your campaign use case was categorized as gambling-related by the carrier, even if scoped to MFA. Rewrite your use case description to emphasize transactional/security messaging exclusively. Remove any language that references gaming operations beyond identifying your industry.
Campaign Campaign description does not match sample messages or use case The reviewer found a mismatch between your stated use case and the sample messages you provided. Align your campaign description, use case selection, and sample messages, so they all describe the same MFA-only program consistently.
Opt-in workflow Opt-in workflow indicates that use case is considered restricted or disallowed by mobile operators: Gambling Your opt-in screenshots or workflow revealed gambling-related content, causing the reviewer to flag it as a restricted use case. Remove gambling-related branding, imagery, or language from the screens shown in your opt-in flow. The opt-in should present a clean, security-focused experience.
Opt-in workflow Opt-in workflow does not obtain sufficient consent Your opt-in screenshots did not demonstrate explicit, affirmative user consent for SMS messaging (express written consent is required). Update your opt-in flow to show a clear, unchecked checkbox or button that the user must actively select. Provide new screenshots showing the revised flow.
Opt-in workflow Opt-in workflow URL or image is missing or inaccessible and could not be verified No opt-in workflow screenshot or URL was provided, or the URL you submitted was inaccessible to the reviewer. Provide a working URL to your live opt-in page or upload a screenshot/mockup showing your complete opt-in flow. Verify that the URL is publicly accessible before resubmitting.
Opt-in workflow Opt-in workflow not compliant or is missing required terms and conditions language Your opt-in page does not include complete terms and conditions language or a link to your full T&C. Add a visible link to your complete messaging terms and conditions at the point of consent or include the full T&C language inline. Resubmit with updated screenshots.
Opt-in workflow Opt-in workflow not compliant or is missing statement that data will not be shared with third parties or link to privacy policy disclosure Your opt-in page does not include a privacy policy link or a statement that mobile opt-in data will not be shared with third parties. Add a visible link to your privacy policy and a statement that phone numbers/opt-in data will not be shared with third parties at the point of consent.
Sample messages Sample message(s) indicates that message content is related to gambling and is not permitted by US carriers Your message templates contain language or keywords that trigger gambling content filters. Revise message templates to remove any gambling-related terms (brand names containing “bet” or “casino,” for example). Use neutral phrasing for OTP delivery (for example, “Your verification code is 123456”).

Revise and resubmit

If the rejection includes actionable feedback:

  1. Address every point raised in the denial specifically.
  2. Strengthen areas the reviewer questioned (additional documentation, revised message samples, clearer use case scoping).
  3. Consider narrowing your initial scope further (for example, registering for a single message type such as login OTP before expanding).
  4. Resubmit with a cover note explaining what you changed and why.

If the rejection is generic or provides no actionable detail, a resubmission with the same information is unlikely to produce a different result.

Conclusion

Messaging registration for betting and gaming technology operators is complex, and approval is never guaranteed. Carrier and registry decisions are ultimately outside an applicant’s control. However, companies that position themselves well approach registration as a thoughtful compliance exercise, not a technical checkbox. They invest time in documentation before they apply, lead with their MFA use cases, and treat post-approval compliance as an ongoing operational responsibility. Even when initial applications are denied, a well-prepared submission strengthens the foundation for appeals and future attempts.

Betting and gaming technology operators that follow this approach (thorough pre-registration documentation, a clearly scoped MFA-only program, and consistent post-approval hygiene) are better positioned for carrier approval and sustained message deliverability. That translates directly to fewer failed logins, lower account lockout rates, and a smoother onboarding experience for new players.

With AWS End User Messaging, you have the infrastructure to help you deliver MFA more reliably at scale. The suggested best practices described in this post give you the framework to support carrier approval and keep your messaging program running reliably.

Missed Part 1?

If you have not yet read Part 1, start there for the landscape and preparation steps. Together, the two parts give you an end-to-end playbook for getting your MFA messaging approved and keeping it deliverable.


About the authors

Meghana Dasigi

Meghana Dasigi

Meghana is a Sr. Technical Account Manager at AWS Enterprise Support, specializing in messaging, generative AI, and serverless architectures for Media, Entertainment, and Ticketing customers.

Sirinda Glasgow

Sirinda Glasgow

Sirinda is a Sr. Technical Account Manager at AWS Enterprise Support, specializing in security and compliance and hybrid edge infrastructure for Betting and Gaming customers operating regulated workloads.

Navigating messaging requirements in betting and gaming technology applications (Part 1: Understanding the landscape and preparing your application)

Post Syndicated from Meghana Dasigi original https://aws.amazon.com/blogs/messaging-and-targeting/navigating-messaging-requirements-in-betting-and-gaming-technology-applications-part-1-understanding-the-landscape-and-preparing-your-application/

Global betting and gaming technology operators face a distinct challenge. Despite operating as fully licensed and regulated businesses in their respective jurisdictions, they consistently encounter messaging service registration challenges when registering their phone numbers for SMS messaging with telecommunication carriers.

Carriers and messaging providers classify betting and gaming technology operators as “high-risk” or gambling. This classification subjects their applications to heightened scrutiny, stricter content filtering, and rejection rates that far exceed those seen in other industries. A betting and gaming operator that follows the same registration steps that might work for a retail or software as a service (SaaS) company will often find that their application requires additional documentation or revision. These revisions can span multiple review cycles, often without clear guidance on what to change.

This post is written for developers and technical teams at betting and gaming operators who need to submit an SMS messaging registration for multi-factor authentication (MFA) and account verification use cases through AWS End User Messaging. The guidance below represents suggested best practices that can help betting and gaming operators give their application a stronger foundation when seeking SMS messaging approval from carriers. We cover the specific challenges such operators may face, how to prepare before submitting a registration application, what to do during the registration process, what happens if the application is denied by the telecommunications carrier, and the ongoing practices that help keep operator MFA messaging active and deliverable after approval.

Important note: This guidance applies exclusively to transactional and MFA messaging (for example, one-time passcodes, account verification, and security alerts). AWS End User Messaging does not support marketing or promotional messages for the betting and gaming industry.

How registration works: AWS and telecommunication carrier roles

Understanding the registration flow helps set expectations. Your application is submitted through AWS, but the carrier or aggregator decides whether to approve it.

Registration through AWS End User Messaging includes the following steps:

  1. You submit a registration request through the AWS End User Messaging console that includes your business details, use case descriptions, and relevant compliance documentation.
  2. AWS forwards your registration to the downstream carrier or aggregator (based on the origination identity type you selected, such as 10DLC, toll-free, or short code).
  3. The carrier or aggregator reviews your application and makes an approval or denial decision. An aggregator is the application-to-person (A2P) messaging provider that routes traffic to carriers such as T-Mobile and AT&T. AWS does not control this decision.
  4. AWS communicates the approval or denial to you through the AWS End User Messaging console. You can also configure event notifications to be alerted automatically.

The key takeaway: AWS facilitates the submission and relays the outcome, but the aggregator or carrier holds the approval authority.

The challenges: Why betting and gaming technology is different

Betting and gaming technology operators face two primary obstacles that generic messaging registration guides may not address. First, messages from this industry historically generate higher complaint rates. For that reason, The Campaign Registry (TCR) classifies gambling as a Special Use Case that requires enhanced vetting, which makes carriers more cautious about approving new betting and gaming registrations. Second, certain words or phrases can trigger content filters at the carriers, which can cause service disruption and increased scrutiny for future applications. Even legitimate one-time password (OTP) messages can get blocked if your company name contains gambling-related keywords. For example, a message such as “exampleGames: here is your OTP 1234 to start betting” may be filtered because “betting” triggers automated content rules, even though the message is a valid security code. This contributes to higher rejection rates by carriers during number registration. To reduce registration approval delays, provide as detailed and accurate a description of your use case as possible in your application.

Pre-registration preparation

Carriers and aggregators want to see that you’re a legitimate business operating legally before they approve your registration. To help do so, you should:

Establish a clear business identity

  1. Use a legitimate business domain email – Registration applications submitted with Gmail or other personal email addresses signal a lack of organizational legitimacy. Use a duly registered email address on your company’s registered domain.
  2. Make your website transparent – Your website should clearly describe your services, the jurisdictions where you’re licensed to operate, and links to your active gaming licenses or regulatory approvals. Carriers will review it. Include links to your applicable licenses, terms of service, and privacy policy in accessible locations.

Plan your messaging content strategically

  1. Develop message templates before you apply – Your registration application will ask for sample messages. Your samples should focus exclusively on:
    • One-time passcodes for account login.
    • Multi-factor authentication (MFA) verification codes.
    • Account security alerts (new device login, password changes, and suspicious activity).
  2. Avoid promotional gambling language in your samples – Use clear language, accurately describe your use case, and provide all the necessary details.
  3. Prepare examples of your message types – For each template, document who receives it, what triggers it, what the message contains, and how the recipient opted in. The more specific and operational your use case descriptions, the more confidence you give reviewers that this is a well-governed program.
  4. Assemble your applicable compliance documentation

Before submitting any registration through AWS End User Messaging, gather:

  • Your business registration and tax identification documents.
  • Your opt-in consent process documentation.
  • Your Telephone Consumer Protection Act (TCPA) compliance policy or equivalent.
  • Your data retention and privacy policy.
Flowchart of the 10DLC registration journey for OTP messaging across pre-registration, registration, and post-registration phases

Figure 1: The 10DLC registration journey for OTP messaging, from pre-registration preparation through carrier review to post-registration compliance

Coming up in Part 2

You now understand why betting and gaming operators face heightened scrutiny, how the AWS and carrier registration roles work, and how to prepare a strong application before you submit. In Part 2, we cover the registration process itself: how to write use-case descriptions and opt-in documentation that get approved, how to maintain compliance and deliverability after approval, and what to do if your registration is denied.

Read Part 2: Navigating messaging requirements in betting and gaming technology applications (Part 2: Executing the registration and maintaining compliance).


About the authors

Meghana Dasigi

Meghana Dasigi

Meghana is a Sr. Technical Account Manager at AWS Enterprise Support, specializing in messaging, generative AI, and serverless architectures for Media, Entertainment, and Ticketing customers.

Sirinda Glasgow

Sirinda Glasgow

Sirinda is a Sr. Technical Account Manager at AWS Enterprise Support, specializing in security and compliance and hybrid edge infrastructure for Betting and Gaming customers operating regulated workloads.

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.

Test your applications against AWS locally with AWS Emulator

Post Syndicated from Daniel Abib original https://aws.amazon.com/blogs/aws/test-your-applications-against-aws-locally-with-aws-emulator/

Today we’re announcing AWS Emulator, a local emulator for Amazon Web Services (AWS) that you run on your machine. The AWS Command Line Interface (AWS CLI), the AWS SDKs, and your coding agents speak to it over a local HTTPS endpoint using the same AWS APIs they would use in the cloud, from your laptop. AWS Emulator has no additional service fee. You pay only for AWS resources when you deploy on AWS. Its source is on GitHub. You install it from an RPM or Debian package on Linux, and on macOS and Windows you run it in Docker.

How it works
You install the emulator, start it, and point your tools at the local endpoint. When AWS Emulator starts, it generates its own credentials, a config file, and a certificate, and writes them to ~/.aws/emulator/9297/. You set environment variables so the AWS SDK talks to your laptop instead of AWS, and your application code stays unchanged.

From there, your existing tests, CLI scripts, and coding agents keep working the way they already do. A unit test that creates an Amazon DynamoDB table, writes an item, and reads it back is the same test, and it runs on your machine without a deployment. A coding agent can create resources, check the result, and iterate again without waiting on a deployment in a Region.

The emulator is implemented in Rust so that it stays light on CPU and memory on a laptop. It supports the APIs of AWS services that have an API model in the AWS API models repository on GitHub, and because it’s built from those models, the same ones the AWS SDKs use, your requests and the errors you get back have the same shape as on AWS.

If you are a developer, especially one working with coding agents such as Kiro or Claude Code, you can use that loop to test AWS interactions of real complexity locally.

Let’s try it out
To get started, I installed the package on Amazon Linux 2023. The package adds the aws-emulator command to /usr/bin/, so it’s on the path.

PKG=https://downloads.aws.com/aws-emulator/packages/aws-emulator/LTS/latest
sudo dnf install -y $PKG/aws-emulator-x86_64.rpm

aws-emulator -v

On macOS and Windows, you build a Docker image from the short Dockerfile in the documentation and run the emulator in a container. We don’t publish a ready-made image.

I started the emulator with aws-emulator. It serves HTTPS on 127.0.0.1:9297, so only my own computer can reach it, and it writes its log as JSON lines that show the address, the config file, and the certificate file.

aws-emulator

In another terminal, I set the environment variables that point the AWS CLI at the emulator, and unset any variables that could supply real AWS credentials.

export AWS_ENDPOINT_URL=https://127.0.0.1:9297
export AWS_SHARED_CREDENTIALS_FILE=~/.aws/emulator/9297/emulator_credentials
export AWS_CONFIG_FILE=~/.aws/emulator/9297/config
export AWS_EC2_METADATA_DISABLED=true
export AWS_DISABLE_HOST_PREFIX_INJECTION=true
export AWS_REGION=us-east-1
export AWS_DEFAULT_REGION=us-east-1
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AWS_PROFILE

The emulator generates new keys each time it starts. Its access key IDs start with EMULATOR, so you can’t mistake them for real AWS keys, and it rejects requests signed with any other keys. To confirm that my shell was talking to the emulator, I checked the health endpoint and the caller identity. The emulator uses a single account, 000000000000.

curl --cacert ~/.aws/emulator/9297/ca.pem https://127.0.0.1:9297/__admin/health

aws sts get-caller-identity

Then I created a bucket, copied in a small object, and listed it.

$ aws s3 mb s3://local-getting-started
make_bucket: local-getting-started

$ echo "hello from the emulator" > hello.txt

$ aws s3 cp hello.txt s3://local-getting-started/
upload: ./hello.txt to s3://local-getting-started/hello.txt

$ aws s3 ls s3://local-getting-started/

With the AWS CLI pointed at my laptop, I had the same commands I already use and a local endpoint that answered them.

Next I wanted to see it the way I actually work now, so with the emulator still running I opened Kiro and asked it to create an Amazon DynamoDB table, write an item, and read it back, all against AWS Emulator rather than my AWS account.

kiro> Using the local AWS Emulator (the environment variables
      are already set in this shell), create a DynamoDB table
      "kiro-demo" with a string key "id", put an item
      {id: "item-1", msg: "hello from kiro"}, then read it
      back with get-item.

$ aws dynamodb create-table --table-name kiro-demo \
    --attribute-definitions AttributeName=id,AttributeType=S \
    --key-schema AttributeName=id,KeyType=HASH \
    --billing-mode PAY_PER_REQUEST

$ aws dynamodb put-item --table-name kiro-demo \
    --item '{"id": {"S": "item-1"}, "msg": {"S": "hello from kiro"}}'

$ aws dynamodb get-item --table-name kiro-demo --key '{"id": {"S": "item-1"}}'

To use the same setup with an existing test suite, I would start the emulator, set the same environment variables in the script that runs the tests, and run them as usual.

Using the emulator in process
Running the emulator as a local process gives you an HTTPS endpoint that works with the AWS CLI and the AWS SDKs through environment variables. Some SDKs need an extra setting to trust the emulator certificate, for example a trust store for the AWS SDK for Java. For tests, there is a second option. AWS Emulator ships an embedded mode that you instantiate directly inside your test process and wire into the SDK through its HTTP client, rather than talking to a separate server over the network. Each embedded instance keeps its own state, so tests do not share buckets, tables, or queues, and you can run many of them in parallel. Embedded mode is available for the AWS SDK for Rust. You add the aws-emulator-embedded crate from GitHub to the [dev-dependencies] section of your Cargo.toml file. The following example creates an Amazon DynamoDB table, writes an item, and reads it back, entirely in process.

use aws_emulator_embedded::{AwsEmulatorEmbedded, EmbeddedOptions};
use aws_sdk_dynamodb::types::{
    AttributeDefinition, AttributeValue, BillingMode, KeySchemaElement, KeyType,
    ScalarAttributeType,
};

#[tokio::test]
async fn put_then_get_returns_the_item() {
    let emulator = AwsEmulatorEmbedded::new(EmbeddedOptions::default());
    let config = aws_config::defaults(aws_config::BehaviorVersion::latest())
        .http_client(emulator.http_client())
        .region(aws_config::Region::new("us-east-1"))
        .credentials_provider(emulator.aws_credentials_provider())
        .load()
        .await;
    let ddb = aws_sdk_dynamodb::Client::new(&config);

    ddb.create_table()
        .table_name("emulator-demo-table")
        .attribute_definitions(
            AttributeDefinition::builder()
                .attribute_name("id").attribute_type(ScalarAttributeType::S)
                .build().unwrap())
        .key_schema(
            KeySchemaElement::builder()
                .attribute_name("id").key_type(KeyType::Hash)
                .build().unwrap())
        .billing_mode(BillingMode::PayPerRequest)
        .send().await.unwrap();

    ddb.put_item()
        .table_name("emulator-demo-table")
        .item("id", AttributeValue::S("item-1".into()))
        .item("msg", AttributeValue::S("hi".into()))
        .send().await.unwrap();

    let got = ddb.get_item()
        .table_name("emulator-demo-table")
        .key("id", AttributeValue::S("item-1".into()))
        .send().await.unwrap();
    assert_eq!(got.item().unwrap().get("msg").unwrap().as_s().unwrap(), "hi");
}

When it runs as a local process, the emulator requires every request to be signed with Signature Version 4 (SigV4), the same way AWS does, and it exposes a /__admin/health endpoint on the same port so a script or a container can wait until it is ready before running tests. By default it also sends anonymous usage and error data, and you can turn it off.

How we measure fidelity
An emulator is only useful if a test that passes against it would also pass against AWS, so we measure that directly with fidelity tests. A fidelity test is a short program that uses an AWS SDK to run a workflow, such as storing an object and then reading and deleting it, and asserts how AWS behaves. We verify each fidelity test against real AWS. A fidelity test passes only if the emulator matches AWS on the response to every call, including the status code, the body, and the exact error code and message, and on the resources and data that the workflow creates.

With each release, we publish how many fidelity tests pass for each service, as k of n. For example, 40 of 50 means that 40 of the service’s 50 fidelity tests pass. The set of fidelity tests is public in the aws-emulator-evaluation-suite repository on GitHub, including the ones that don’t pass yet, so you can see what we verified and run the fidelity tests yourself. Read a score as a snapshot of a product that’s improving. When we add fidelity tests, a score can go down even while the emulator gets better.

If the emulator doesn’t implement an operation yet, it returns HTTP 501 (Not Implemented), so your tests fail right away. If the emulator acts differently from AWS, you can tell us by opening an issue in the AWS Emulator repository on GitHub.

How the emulator is built
AWS Emulator is built and maintained by agents from the AWS API models using Amazon Bedrock AgentCore Runtime Instances, AWS CodePipeline, and AWS CodeCommit, so it stays current with AWS as those models change.

One group of agents looks for gaps, both by comparing emulator responses against real AWS and by statically comparing the emulator’s code against the published Smithy models, and files an issue for each gap it finds. Another group picks up an issue, writes tests, implements the behavior, and reviews the change for correctness, performance, and security. When the change is ready, it is pushed to a source repository, and that push triggers an AWS CodePipeline run that runs the fidelity tests before the change is published to the public GitHub repository.

How we keep it secure
Because the code is written by agents, an independent security agent reviews changes adversarially, both while the fix is being made and again in the release pipeline as a final check before anything ships.

Security of your own use remains a shared responsibility. We build the emulator to run safely on your machine: it listens only on your own computer by default and rejects requests that aren’t signed with its own keys. You decide where it runs, what data you put in it, and how you test before production. Don’t use the emulator to test whether your application is secure. It doesn’t evaluate AWS Identity and Access Management (IAM) policies and resource-based policies the way AWS does, so a request that AWS denies might succeed in the emulator. Keep real credentials out of the environment of your test jobs, and test your security settings and your whole application on AWS before you go to production.

Now available
AWS Emulator is generally available today. It has no additional service fee. You pay only for AWS resources when you deploy on AWS. You can install it from RPM or Debian packages on Linux, run it in Docker on macOS and Windows, or build from source, and it works with the AWS SDKs and the AWS CLI once you set environment variables. At launch, it has some limits. It doesn’t evaluate IAM policies the way AWS does, and each emulator acts as a single account, with no cross-account or cross-Region behavior. How closely it matches AWS varies by service and feature. To see how well the emulator covers the services that you use, check the fidelity scores in the AWS Emulator documentation.

If you want to check regional availability, visit the AWS Capabilities by Region page in AWS Builder Center. If you want to call APIs, search documentation, find regional availability, and check troubleshooting about this new feature, try using the AWS MCP Server and plugins with your preferred AI tool.

To get started, see the AWS Emulator documentation.

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.

Track SMS spend by team and use case with AWS End User Messaging

Post Syndicated from Rommel Sunga original https://aws.amazon.com/blogs/messaging-and-targeting/track-sms-spend-by-team-and-use-case-with-aws-end-user-messaging/

If you send SMS for several teams or applications from one AWS account, you’ve probably been asked which team drove last month’s bill. The bill and the default AWS Cost Explorer view show one total for AWS End User Messaging. Grouping by usage type doesn’t help when teams send to the same country with the same type of origination identity, because their message fees land on one line. So each month, someone splits the bill by hand in a spreadsheet.

In this post, we show how to attribute AWS End User Messaging SMS spend to the teams, cost centers, and use cases that generate it. We walk through tagging your origination identities, activating those tags for cost allocation, and reading the results in Cost Explorer. Every step uses the AWS Management Console, and we include the equivalent AWS Command Line Interface (AWS CLI) commands if you want to script the setup.

This post is for FinOps practitioners, platform owners, and solutions architects who run shared SMS workloads and need showback or chargeback by team.

Challenges with tracking SMS spend

Organizations that send SMS for several teams from one AWS account commonly face these challenges:

  • The bill and the default Cost Explorer view report AWS End User Messaging as a single service, with no split by team or application.
  • Grouping by usage type shows what you paid for, such as message fees by destination country and origination identity type, but not who sent the messages.
  • When two or more teams send to the same country with the same type of origination identity, their message fees combine into one usage type line. For example, three sender IDs that all send to the United Kingdom share one line.
  • Finance teams need a monthly showback or chargeback report that they can rerun without manual spreadsheet work.

To address these challenges, you can tag each origination identity with the team and use case that owns it, and then activate those tag keys as cost allocation tags. Cost Explorer can then group your SMS spend by any of those keys, and the same tags flow into your AWS Cost and Usage Report (CUR) and AWS Data Exports.

Solution overview

Cost allocation for AWS End User Messaging SMS works at the level of the origination identity. Phone numbers, sender IDs, and phone pools are AWS resources with their own Amazon Resource Names (ARNs), and each one can carry up to 50 tags. When you send a message from a tagged phone number or sender ID, AWS records the charges for that message against that resource, along with its tags. The monthly fee for a tagged phone number carries its tags too.

The process has four stages, and each stage maps to one or more of the steps in this post:

  1. Tag your origination identities (Steps 1 and 2) – Assign each phone number and sender ID a set of tags, such as business-unit, cost-center, and use-case.
  2. Send traffic (Step 3) – Messages from your tagged identities generate charges that carry the tags. New tag keys can take up to 24 hours to appear in AWS Billing and Cost Management.
  3. Activate the tag keys (Steps 4 and 5) – In the management account of your organization, or in a standalone account, activate the keys as cost allocation tags. Activation can take up to another 24 hours.
  4. Analyze (Steps 6 and 7) – Group your SMS spend by tag in Cost Explorer, or use the tags in your cost and usage reports.

Cost Explorer places charges that don’t belong to a tagged resource in the untagged group, a group that it labels No tag key: key-name.

The following diagram illustrates how the charges from a tagged sender ID reach Cost Explorer.

Figure 1: Each business unit sends from its own tagged sender ID. After the business-unit key is activated, Cost Explorer splits SMS spend by team. Charges from identities or resources without the key appear under No tag key.

Figure 1: Each business unit sends from its own tagged sender ID. After the business-unit key is activated, Cost Explorer splits SMS spend by team. Charges from identities or resources without the key appear under No tag key.

Example scenario

Throughout this post, AnyCompany runs three business units that send SMS from one AWS account. All three send to the United Kingdom, each with its own sender ID, so usage type alone can’t separate their spend. AnyCompany uses the following tagging plan.

Origination identity business-unit cost-center use-case
Sender ID 1 (United Kingdom) retail cc-4100 order-notifications
Sender ID 2 (United Kingdom) banking cc-7250 otp
Sender ID 3 (United Kingdom) marketing cc-3300 promotional

Prerequisites

Before you begin, make sure you have the following components and permissions in place:

  • An AWS account with AWS End User Messaging SMS and at least one origination identity (phone number or sender ID) that you send messages from.
  • Access to the management account of your organization in AWS Organizations, or a standalone account. Only these accounts can activate cost allocation tags. If your SMS runs in a member account, you tag the origination identities there, and the management account activates the keys and requests any backfill.
  • Cost Explorer enabled. The management account sees costs for every account. A member account sees only its own costs, and the management account can turn off Cost Explorer access for member accounts.
  • AWS Identity and Access Management (IAM) permissions to view and tag AWS End User Messaging SMS resources (sms-voice:DescribePhoneNumbers, sms-voice:DescribeSenderIds, sms-voice:DescribePools, sms-voice:TagResource, sms-voice:UntagResource, and sms-voice:ListTagsForResource). If you use the AWS Resource Groups Tagging API, you also need tag:TagResources and tag:GetResources.
  • IAM permissions in the management account or standalone account to activate and backfill cost allocation tags (ce:ListCostAllocationTags, ce:UpdateCostAllocationTagsStatus, ce:StartCostAllocationTagBackfill, and ce:ListCostAllocationTagBackfillHistory), and to view Cost Explorer reports, such as ce:GetCostAndUsage, ce:GetDimensionValues, and ce:GetTags.

Step 1: Plan your tag keys

Decide your keys before you tag anything. Tag keys and values are case sensitive, so Business-Unit and business-unit become two separate keys in your cost reports. Pick one convention, such as lowercase with hyphens, and use it everywhere.

AnyCompany uses three keys: business-unit (which team owns this spend), cost-center (which budget to charge), and use-case (what the traffic is for).

A tag describes the resource, so a sender ID that two teams share can only carry one business-unit value. If you need to split spend between teams, give each team its own origination identity. To see spend for each origination identity, for example, when one team owns several sender IDs, add a key that names the identity, such as identity-name.

Don’t include sensitive information, such as customer names or phone numbers, in tags. Cost allocation tags appear in billing reports that many people in your organization can read.

Step 2: Tag your origination identities

The following steps tag a sender ID. The steps for a phone number are the same, starting from Phone numbers under SMS & RCS.

  1. Open the AWS End User Messaging console.
  2. In the navigation pane, under SMS & RCS, choose Sender IDs.
  3. Choose the sender ID that you want to tag.
  4. On the Tags tab, choose Manage tags.
  5. Choose Add new tag, and then enter a Key and Value. Repeat for each key in your tagging plan.
  6. Choose Save changes.
Figure 2: The Tags tab of a sender ID that has no tags yet. Choose Manage tags to add, edit, or remove tags.

Figure 2: The Tags tab of a sender ID that has no tags yet. Choose Manage tags to add, edit, or remove tags.

Figure 3: The Manage tags dialog for the retail sender ID. Enter a key and value for each tag in your tagging plan.

Figure 3: The Manage tags dialog for the retail sender ID. Enter a key and value for each tag in your tagging plan.

If you send through a phone pool, tag every phone number and sender ID in the pool. Message charges carry the tags of the origination identity that sends the message, not the tags on the pool.

The AWS Resource Groups Tag Editor console doesn’t list AWS End User Messaging SMS resources, but the Resource Groups Tagging API supports them. To tag many identities at once, use the TagResource operation with the AWS CLI or an AWS SDK, or the Tagging API. For examples, see Automate with the AWS CLI later in this post.

Step 3: Send traffic and wait for the tag keys to appear

Send messages from your tagged identities as usual. A new key can take up to 24 hours to appear on the Cost allocation tags page. You can’t activate it until it does, but you can attribute charges from that period with a backfill in Step 5.

If a key still isn’t listed after 24 hours, check the tag on the resource’s Tags tab. Also confirm that the key’s spelling and case match your plan, and that you’re signed in to the management account or standalone account.

Step 4: Activate the tag keys

  1. Sign in to the management account, or your standalone account, and open the AWS Billing and Cost Management console.
  2. In the navigation pane, choose Cost Allocation Tags.
  3. In the Cost allocation tags table, select business-unit, cost-center, and use-case. To find a key, enter it in Find cost allocation tags. Keys from tags on your resources have the type Resource.
  4. Choose Activate.
Figure 4: The Cost allocation tags page showing AnyCompany’s three keys after activation.

Figure 4: The Cost allocation tags page showing AnyCompany’s three keys after activation.

After you activate a key, it can take up to 24 hours to become active in Cost Explorer. Activation applies from that point forward, so charges from before activation stay in the untagged group unless you backfill them.

Step 5 (optional): Backfill earlier months

If you tagged your origination identities before activating the keys, the management account can backfill up to 12 months.

  1. On the Cost allocation tags page, choose Backfill tags.
  2. Choose the earliest month in which your origination identities carried the tags.
  3. Choose Confirm.
Figure 5: The Backfill tags dialog. Choose the earliest month when your origination identities carried the tags.

Figure 5: The Backfill tags dialog. Choose the earliest month when your origination identities carried the tags.

A backfill only adds tag values for periods when the tag was attached to the resource. For example, if you tagged a sender ID on September 17 and request a backfill from September 1, charges from September 1–16 remain untagged. You can submit one backfill request every 24 hours, and Cost Explorer shows the results after its next daily data refresh. A backfill applies each key’s current status, so any key you’ve since deactivated is also removed from earlier months.

Step 6: View SMS spend by tag in Cost Explorer

  1. Open Cost Explorer.
  2. In the Report parameters panel, set Date Range and Granularity. For example, choose the last three months and Monthly.
  3. Under Group by, for Dimension, choose Tag, and then for Tag, choose your key, such as business-unit. Group by with a tag key splits your spend into one line per tag value. A Tag filter only narrows the data to the values that you select.
  4. Under Filters, for Service, choose End User Messaging, and then choose Apply.

Note: SMS carrier fees are billed under this service. The separate End User Messaging Third Party Fees service covers fees such as the WhatsApp fees that Meta charges.

From the management account, you can also filter by Linked account to see the costs of one member account.

Before any tagged usage is metered for a key, every charge sits in a single group, as shown in the following screenshot.

Figure 6: Cost Explorer grouped by business-unit for the months before the sender IDs were tagged. All AWS End User Messaging spend appears under No tag key: business-unit.

Figure 6: Cost Explorer grouped by business-unit for the months before the sender IDs were tagged. All AWS End User Messaging spend appears under No tag key: business-unit.

If you still see only No tag key more than 24 hours after activation, check that the key shows Active on the Cost allocation tags page. Also confirm that you’ve sent messages from a tagged identity since activation, or that you requested a backfill.

After the key is active and tagged usage has been metered, Cost Explorer shows one group for each tag value.

Figure 7: AnyCompany’s AWS End User Messaging spend for September, grouped by business-unit. Charges from resources without the key appear under No tag key: business-unit.

Figure 7: AnyCompany’s AWS End User Messaging spend for September, grouped by business-unit. Charges from resources without the key appear under No tag key: business-unit.

The No tag key group holds charges that have no value for the key. These include:

  • Origination identities that you haven’t tagged yet, or that use a different spelling or case of the key.
  • Other AWS End User Messaging resources that don’t carry the key, such as RCS agents.
  • Messages sent over shared routes, which don’t use one of your origination identities.
  • 10DLC registration fees, such as brand, vetting, and campaign fees.
  • Charges from before the tag was attached or the key was activated.

To reuse this view each month, keep a relative date range, such as the last three months, and choose Save to report library.

Step 7: Combine usage type and tags

Group by Usage type to see what you’re paying for. Usage type names include the AWS Region prefix, the destination country, the origination identity type, and the type of charge, for example USE1-OutboundSMS-GB-Standard-Senderid-MessageFees. Message fees for all three AnyCompany United Kingdom sender IDs appear on this one line.

To split that line by team, set Group by to your tag key and add a Usage type filter for that line. The table then lists a costs row and a usage row for each tag value. To see only the cost rows, enter costs in the search box above the table.

Figure 8: United Kingdom sender ID message fees split by business unit, with Group by set to the business-unit tag and a Usage type filter applied.

Figure 8: United Kingdom sender ID message fees split by business unit, with Group by set to the business-unit tag and a Usage type filter applied.

Automate with the AWS CLI

If you manage many origination identities, or you want to add tagging to your provisioning scripts, you can run the same steps with the AWS CLI. Replace the example ARNs and account ID with your own. To list your ARNs, run aws pinpoint-sms-voice-v2 describe-sender-ids or aws pinpoint-sms-voice-v2 describe-phone-numbers.

To tag a sender ID when you request it, add --tags. The request-phone-number and create-pool commands accept the same option.

aws pinpoint-sms-voice-v2 request-sender-id \
  --sender-id ANYCOMPANY \
  --iso-country-code GB \
  --tags Key=business-unit,Value=retail Key=cost-center,Value=cc-4100 Key=use-case,Value=order-notifications

To tag an existing sender ID or phone number (Step 2), run the following command:

aws pinpoint-sms-voice-v2 tag-resource \
  --resource-arn arn:aws:sms-voice:us-east-1:111122223333:sender-id/ANYCOMPANY/GB \
  --tags Key=business-unit,Value=retail Key=cost-center,Value=cc-4100 Key=use-case,Value=order-notifications

To apply the same tags to several identities in one call, use the Resource Groups Tagging API. Each call accepts up to 20 ARNs:

aws resourcegroupstaggingapi tag-resources \
  --resource-arn-list \
    arn:aws:sms-voice:us-east-1:111122223333:sender-id/ANYCOMPANY/GB \
    arn:aws:sms-voice:us-east-1:111122223333:phone-number/phone-1234567890abcdef0 \
  --tags business-unit=retail,cost-center=cc-4100,use-case=order-notifications

To check which sender IDs carry a key, filter by that key. For phone numbers and pools, use sms-voice:phone-number and sms-voice:pool.

aws resourcegroupstaggingapi get-resources \
  --resource-type-filters sms-voice:sender-id \
  --tag-filters Key=business-unit

To activate the tag keys (Step 4), run the following command in the management account or standalone account. If a key hasn’t appeared yet, the command returns a Tag keys not found error. Wait and try again, as described in Step 3.

aws ce update-cost-allocation-tags-status \
  --cost-allocation-tags-status \
    TagKey=business-unit,Status=Active \
    TagKey=cost-center,Status=Active \
    TagKey=use-case,Status=Active

To backfill earlier months (Step 5), set --backfill-from to the first day of a month, and then check the status of the request:

aws ce start-cost-allocation-tag-backfill --backfill-from 2026-09-01T00:00:00Z
aws ce list-cost-allocation-tag-backfill-history

To get the monthly split by tag (Step 6), run the following command. In the API, the service name is AWS End User Messaging. Charges without the key are returned under business-unit$, which is the API form of No tag key.

aws ce get-cost-and-usage \
  --time-period Start=2026-09-01,End=2026-10-01 \
  --granularity MONTHLY \
  --metrics UnblendedCost \
  --group-by Type=TAG,Key=business-unit \
  --filter '{"Dimensions":{"Key":"SERVICE","Values":["AWS End User Messaging"]}}'

To split a single usage type line by team (Step 7), add a USAGE_TYPE dimension to the filter, for example:

--filter '{"And":[{"Dimensions":{"Key":"SERVICE","Values":["AWS End User Messaging"]}},{"Dimensions":{"Key":"USAGE_TYPE","Values":["USE1-OutboundSMS-GB-Standard-Senderid-MessageFees"]}}]}'

Going further

With your tag keys active, you can reuse them in other AWS Cost Management features:

  • Budgets per team – Create an AWS Budgets cost budget filtered by business-unit to alert each team when its SMS spend crosses a threshold. To receive those alerts on WhatsApp, see Establishing finops management: Integrating AWS Budgets with WhatsApp using AWS End User Messaging.
  • Anomaly alerts – Create an AWS Cost Anomaly Detection monitor for a cost allocation tag, so that an unexpected spike in one team’s SMS spend raises an alert for that team. Create the monitor in the management account, because monitors for cost allocation tags can only be created there.
  • Chargeback reports – Activated tags are included in the cost and usage reports that you create with AWS Data Exports, so you can build monthly chargeback reports in Amazon Athena or your business intelligence tool.

Best practices for SMS cost allocation

  • Tag origination identities when you provision them, so that the first message they send is attributed.
  • Give each team its own origination identity when you need to split its spend.
  • Tag every phone number and sender ID in a phone pool. Tags on the pool itself don’t appear on message charges.
  • Use the same tag keys that your organization uses for other AWS services, so that SMS spend rolls up with the rest of each team’s costs.
  • Review the No tag key group each month. If it grows, check for new origination identities that are missing tags.

Conclusion

By tagging your AWS End User Messaging SMS origination identities and activating those tags for cost allocation, you can see SMS spend by team, cost center, and use case next to the rest of your AWS costs. Tags also separate teams that send to the same country, which usage type alone can’t do.

Tag your identities and send traffic first, and then activate the keys after they appear. If you tagged before activating, backfill up to 12 months so that earlier charges are attributed too. Review the No tag key group each month to catch new identities that are missing tags. To build upon this foundation, consider adding per-team budgets and anomaly monitors on the same tag keys.

For additional implementation guidance and best practices, refer to the following resources:


About the authors

Rommel Sunga

Rommel Sunga

Rommel is a Senior Solutions Architect at AWS, based in Singapore. He specializes in AWS End User Messaging and Amazon Simple Email Service, helping customers build scalable and reliable communication solutions. With expertise in cloud-based messaging architectures, he works with organizations to improve their customer engagement.

Brett Ezell

Brett Ezell

Brett is a Solutions Architect for AWS End User Messaging and Amazon Simple Email Service. Outside of work, Brett spends his time collecting vinyl, comic books, catching live shows, and training at the gym.

Monitor application health with Amazon EC2 application status checks

Post Syndicated from Caroline Frost original https://aws.amazon.com/blogs/compute/monitor-application-health-with-amazon-ec2-application-status-checks/

Amazon Elastic Compute Cloud (Amazon EC2) application status checks monitor application health and responsiveness alongside instance, system, and Amazon Elastic Block Store (Amazon EBS) status checks. You can use them to identify a web server that has stopped accepting requests, a Docker daemon that is not running, an incorrect networking configuration, or a network interface that is no longer passing traffic. Amazon EC2 reports application, instance, system, and Amazon EBS status checks through the DescribeInstanceStatus API and Amazon CloudWatch, so you can monitor application health through these EC2 signals rather than publish a custom health metric.

Application status checks can monitor an EC2 instance whether it is launched using RunInstances, Amazon EC2 Fleet, or Amazon EC2 Auto Scaling. For RunInstances and EC2 Fleet, launch the instance with the tag used by the check association. EC2 reports the application status, and you choose how to respond. Amazon EC2 Auto Scaling monitors instance health and can use included application status checks to automate recovery by replacing an instance when its application status is impaired. When Auto Scaling launches a replacement with the app=database tag, the existing tag-based association includes it, so the application status check monitors the new instance without another association call. This walkthrough uses an Auto Scaling group and also covers CloudWatch alarms, staged onboarding, and application maintenance.

For additional details about the feature and pricing, you can refer to the What’s New post and application status checks in the Amazon EC2 User Guide.

Solution overview

Application status checks report through the DescribeInstanceStatus API and Amazon CloudWatch, so you can consume the result in more than one way. You can poll the status from your own tooling, alarm on the CloudWatch metric and run your own remediation, or rely on Amazon EC2 Auto Scaling to replace an instance whose application status is impaired.

In this example, we use the feature with EC2 Auto Scaling groups. Auto Scaling groups help you manage the instance lifecycle across launching, monitoring, and refreshing instances, and they maintain the number of running instances you specify by replacing an instance that fails a health check. For simplicity, we assume the group is a fixed size, with its desired, minimum, and maximum capacity set to the same value, so replacing an instance keeps capacity steady. We assume we have already set up application monitoring for an application running on EC2 instances in an Amazon EC2 Auto Scaling group. Our goal is to replace an impaired application quickly.

The walkthrough adds one application status check across your instances, surfaces the result in CloudWatch, and configures Auto Scaling to replace an instance whose application status is impaired.

You configure the protocol, port, path, accepted response codes, and failure and success thresholds. EC2 evaluates the endpoint every 60 seconds. A matching response code passes. A different response code, a refused or reset connection, or a timeout counts as a failure. The check reports failed after FailureThreshold consecutive failures and passed after SuccessThreshold consecutive successes. Both thresholds default to 2.

The application status of the instance is separate from the result of any single check. It is the aggregation of the checks associated with the instance that have Aggregation set to included. It reports impaired when at least one included check has a failed result. This is the value that appears as ApplicationStatus in describe-instance-status and that Amazon EC2 Auto Scaling acts on. An initialization grace period delays evaluation after launch, so an application that is still starting is not reported impaired before it is ready. You can associate more than one check with an instance, for example a liveness path and a readiness path, and include or exclude each one from the aggregated instance-level status.

Prerequisites

Before you start, you need the following:

  • An application running on EC2 instances in an Auto Scaling group. If you need to create a group for this walkthrough, see Create an Auto Scaling group using a launch template. Configure the Amazon Machine Image (AMI) or user data in the launch template to install and start the application on each instance.
  • A tag on those instances that you can target, for example app=database.
  • Instances reachable on the health check port from within your virtual private cloud (VPC). With AWS-managed network paths, EC2 matches the health check source to the subnet and security group combinations used by the associated instances. Before creating the check, add an inbound rule to each instance security group that allows health check traffic on the check port from the same security group. The host firewall must also allow the port. The instances do not need public IP addresses.
  • An AWS Identity and Access Management (IAM) principal with permissions for the EC2 application status check actions and EC2 Auto Scaling.
  • Make sure your AWS Command Line Interface (AWS CLI) is up to date. Older releases might not include the application status check commands. If the CLI does not recognize create-application-status-check, follow Installing or updating to the latest version of the AWS CLI before continuing.

If you do not have an application on a health path yet, add a lightweight endpoint that returns a success code when the instance is ready (most web frameworks expose one), or point the check at an existing readiness path. You need at least one running instance in the Auto Scaling group that is reachable on the check port and serving that endpoint to see a passing result.

To add a lightweight endpoint for an instance running Amazon Linux 2023, install nginx and serve a path that returns 200:

sudo dnf install -y nginx
sudo tee /etc/nginx/conf.d/health.conf >/dev/null <<'EOF'
server {
    listen 8080;
    location = /health {
        access_log off;
        default_type text/plain;
        return 200 'ok';
    }
}
EOF
sudo nginx -t
sudo systemctl enable --now nginx
curl -I http://127.0.0.1:8080/health

The final curl command confirms that nginx is listening locally and returning a 200 response. Before you create the application status check, configure the instance security group to allow health check traffic on port 8080 from the same security group. For instructions, see Security group referencing.

Create an application status check

Create a check that requests /health on port 8080 over HTTP and treats 200 as healthy. Keep the default thresholds and set an initialization grace period so that newly launched instances have time to start.

aws ec2 create-application-status-check \
  --protocol http \
  --port 8080 \
  --path /health \
  --status-code-matcher "200" \
  --initialization-grace-period-seconds 300 \
  --tag-specifications 'ResourceType=application-status-check,Tags=[{Key=Name,Value=database-health}]'

The response returns an application status check ID, for example asc-0123456789abcdef0.

Name=database-health identifies the application status check. The app=database tag used in the next step selects the instances to monitor.

The status code matcher defaults to 200 and accepts a comma-separated list of individual codes or ranges, for example "200,204", up to 64 characters.

Associate the check with your instances

Use the application status check ID returned by the create step to associate the check with every instance that carries the app=database tag. Tag-based association covers instances that already carry the tag and instances that launch with it later, which suits an Auto Scaling group where replacement instances launch with the tag.

aws ec2 associate-application-status-check \
  --application-status-check-id asc-0123456789abcdef0 \
  --target-tag-associations Key=app,Value=database

You can also associate specific instances with --instance-ids instead of --target-tag-associations.

View the application status

The describe-instance-status call returns the application status alongside the instance and system status checks, so a query you already run surfaces it without a new API call.

aws ec2 describe-instance-status --instance-ids i-0abc123def4567890

The following example response shows a case where the system and instance status checks pass, while the application status reports impaired.

{
    "InstanceStatuses": [
        {
            "AvailabilityZone": "us-east-1d",
            "InstanceId": "i-0abc123def4567890",
            "InstanceState": {
                "Code": 16,
                "Name": "running"
            },
            "SystemStatus": {
                "Status": "ok",
                "Details": [
                    {
                        "Name": "reachability",
                        "Status": "passed"
                    }
                ]
            },
            "InstanceStatus": {
                "Status": "ok",
                "Details": [
                    {
                        "Name": "reachability",
                        "Status": "passed"
                    }
                ]
            },
            "ApplicationStatus": {
                "Status": "impaired",
                "ImpairedSince": "2026-08-07T14:32:10.000Z"
            }
        }
    ]
}

describe-instance-status returns the aggregation of the included application status checks associated with an instance. For details on every application status check associated with an instance, use describe-application-status, which returns each associated check’s individual result, the reason code, and the HTTP status code your application returned. Use describe-instance-status to see the aggregated application health next to other status checks, and describe-application-status for details on which check failed and why.

aws ec2 describe-application-status --instance-ids i-0abc123def4567890

A failed check includes a reason that explains the outcome. For example:

{
    "ApplicationStatuses": [
        {
            "InstanceId": "i-0abc123def4567890",
            "ApplicationStatus": {
                "Status": "impaired",
                "Details": [
                    {
                        "ApplicationStatusCheckId": "asc-0123456789abcdef0",
                        "Aggregation": "included",
                        "Status": "failed",
                        "Reason": {
                            "Code": "ResponseCodeMismatch",
                            "StatusCode": 503,
                            "Protocol": "HTTP"
                        }
                    }
                ]
            }
        }
    ]
}

For ResponseCodeMatched and ResponseCodeMismatch, the Reason includes the returned StatusCode and the Protocol, so you can distinguish a 500 from a 503. Connection reasons such as ConnectionTimeout, ConnectionRefused, and ConnectionReset indicate that the application did not complete a response at all, and do not include a StatusCode.

Replace instances with an impaired status check

When an application status check reports impaired, the right response depends on what failed, and not every impairment calls for terminating the instance. Common responses include rebooting the instance, rolling back a recent deployment, or terminating the instance and replacing it, and your workload may call for others. A transient fault may clear with a reboot, a bad deployment may call for a rollback, and a crashed or wedged instance usually calls for termination and replacement.

Amazon EC2 Auto Scaling evaluates the aggregated application status as part of its EC2 health checks. When the status is impaired, the group marks the instance unhealthy, terminates it, and attempts to launch a replacement from the group’s launch template. Auto Scaling does not copy the application from the terminated instance. Configure the AMI, user data, or deployment system for the group to install and start the application on each replacement. Because the group has fixed capacity in this example, it replaces the impaired instance rather than changing capacity. Auto Scaling includes application status checks in the group’s EC2 health checks by default, so no separate Auto Scaling health check configuration is required.

Terminate and replace is the default an Auto Scaling group gives you. If your remediation is a reboot or a rollback instead, keep the same impaired signal and act on it yourself, using the CloudWatch alarm in the next section to trigger your own automation.

Set the check’s InitializationGracePeriodSeconds to at least the time your application needs to start, and make sure the Auto Scaling group’s health check grace period is no shorter. Then neither the check nor the group acts on an instance that is still initializing. Detection and remediation then run without a separate monitoring system.

Alarm on the application status in Amazon CloudWatch

EC2 publishes the application status to CloudWatch, so you can alarm on it without a custom metric. This step is optional. Auto Scaling replaces an impaired instance whether or not you create an alarm. Add one when you want notification or a dashboard alongside the replacement. The following alarm notifies an operations topic when the application status check fails for an instance.

aws cloudwatch put-metric-alarm \
  --alarm-name database-impaired \
  --namespace AWS/EC2 \
  --metric-name StatusCheckFailed_Application \
  --dimensions Name=InstanceId,Value=i-0abc123def4567890 \
  --statistic Maximum \
  --period 60 \
  --evaluation-periods 3 \
  --threshold 1 \
  --comparison-operator GreaterThanOrEqualToThreshold \
  --alarm-actions arn:aws:sns:us-east-1:111122223333:ops-notifications

The alarm enters the ALARM state when the application status is impaired for three consecutive minutes. StatusCheckFailed_Application aggregates across every associated check whose aggregation is included. EC2 also publishes a per-check metric named StatusCheckFailed_Application_{application-status-check-id}, so you can alarm on an individual check when an instance has more than one associated.

To see the behavior end to end, stop the application process on one instance without stopping the instance. After the configured thresholds are met, the application status can turn impaired, the CloudWatch alarm can enter the ALARM state, and the Auto Scaling group can replace the instance while the remaining healthy instances can continue to serve traffic.

Rollout and maintenance strategies

Use the following strategies to stage deployment across your instances and suppress reporting during planned application maintenance.

Onboard checks across your instances

Roll application status checks out to a large number of instances in stages. An excluded check does not contribute to replacement decisions while you validate it.

Start in observe-only mode

Create the check with Aggregation set to excluded. An excluded check still runs and reports its result through describe-application-status and CloudWatch, but it does not contribute to the instance-level application status and does not cause Auto Scaling to replace an instance. Watch it for a representative period, confirm it returns the codes you expect, and tune the StatusCodeMatcher, FailureThreshold, SuccessThreshold, and initialization grace period. When you are confident, move the check to included with ModifyApplicationStatusCheck, and the result begins contributing to the instance-level status and to Auto Scaling replacement.

Associate by tag

Associate the check with a tag rather than a list of instance IDs. A tag-based association also covers a new instance when it launches with the tag, without another API call. This fits an Auto Scaling group, an instance refresh, or any workflow that replaces instances over time.

Amazon EKS and Karpenter

Application status checks can monitor an application endpoint on an EC2 worker node, including nodes launched for Amazon Elastic Kubernetes Service (Amazon EKS) managed node groups or by Karpenter. Each associated node must expose the HTTP or HTTPS health path on the configured port and carry the tag used by the check association. For an EKS managed node group, apply the tag to the EC2 instances through its custom launch template. For Karpenter, apply the tag through spec.tags in the EC2NodeClass. Application status checks monitor the endpoint on the EC2 instance, not a Kubernetes Service or an individual pod.

Manage checks as code

Define the check, its thresholds, and its tag association in the same infrastructure-as-code templates you use for your instances, so you can apply the same definition across environments and use your review process for changes. Roll the same definition out one Auto Scaling group or one Region at a time, and use a CloudWatch dashboard on the StatusCheckFailed_Application metric and the per-check StatusCheckFailed_Application_{application-status-check-id} metric to compare behavior before and after you switch a check to included.

The following template creates the check and its tag association. The template creates the check with Aggregation set to excluded so that it reports without contributing to the instance-level status, and you change it to included when you are ready.

Resources:
  DatabaseHealthCheck:
    Type: AWS::EC2::ApplicationStatusCheck
    Properties:
      Protocol: http
      Port: 8080
      Path: /health
      StatusCodeMatcher: "200"
      FailureThreshold: 2
      SuccessThreshold: 2
      InitializationGracePeriodSeconds: 300
      Aggregation: excluded
      Tags:
        - Key: Name
          Value: database-health

  DatabaseHealthCheckTagAssociation:
    Type: AWS::EC2::ApplicationStatusCheckTagAssociation
    Properties:
      ApplicationStatusCheckId: !GetAtt DatabaseHealthCheck.ApplicationStatusCheckId
      TagKey: app
      TagValue: database

The association takes the check ID, which the check exposes as an Fn::GetAtt attribute. To target named instances instead of a tag, use AWS::EC2::ApplicationStatusCheckInstanceAssociation with ApplicationStatusCheckId and InstanceId. Every ID property on both association resources is create-only, so changing the target replaces the association.

Run more than one check

You can associate more than one check with an instance, for example a liveness path and a readiness path, and include or exclude each from the aggregated instance-level status. Create a new check and exclude it from the aggregated count, confirm it behaves, then include it. The application status appears alongside the instance, system, and Amazon EBS status checks in describe-instance-status, so you can adopt it without changing the queries and alarms you already run.

Perform application maintenance

Planned maintenance, such as a rolling configuration change or a version upgrade, can make an application stop responding on its health path for a short time. Without a pause, the check reports the instance impaired and Auto Scaling can replace an instance that is healthy and only briefly offline. Pause reporting for the duration, then resume it.

The direct control is EnableApplicationStatusCheckSuppression. While suppression is in effect, the check does not mark instances impaired, so Auto Scaling does not act on it. Reporting resumes when you call DisableApplicationStatusCheckSuppression, or at the resume time set for the suppression. The following patterns wire that pause into common maintenance workflows.

EC2 Auto Scaling instance refresh and standby

An instance refresh rolls a new launch template through the group in batches and waits for each new instance to pass its health checks, including the application status check, before it continues. Set the check’s InitializationGracePeriodSeconds, and the group’s instance warmup, to at least the time your application needs to start, so the refresh does not act on an instance that is still initializing. For one-off manual work on a single instance, move it to standby with EnterStandby. The group stops health-checking and replacing it until you call ExitStandby.

AWS CodeDeploy

Suppression is not tied to any one deployment tool. If you deploy with AWS CodeDeploy, a deployment that restarts your application fails its health path until the new version is serving, so suppress the instance in a lifecycle hook before the deployment and resume it after. Suppress in a BeforeInstall hook and resume in an ApplicationStart hook in your appspec.yml:

version: 0.0
os: linux
hooks:
  BeforeInstall:
    - location: scripts/suppress_status_check.sh
      timeout: 60
  ApplicationStart:
    - location: scripts/resume_status_check.sh
      timeout: 60

scripts/suppress_status_check.sh suppresses the instance before the new version installs:

#!/bin/bash
set -euo pipefail
aws ec2 enable-application-status-check-suppression \
  --instance-ids i-0abc123def4567890 \
  --duration-seconds 600

scripts/resume_status_check.sh resumes reporting once the new version is up:

#!/bin/bash
set -euo pipefail
aws ec2 disable-application-status-check-suppression \
  --instance-ids i-0abc123def4567890

The --duration-seconds value is a safety net: If the deployment fails before the resume hook runs, suppression lifts on its own rather than leaving the instance unmonitored. Omit it to suppress until you call disable. Grant the instance role ec2:EnableApplicationStatusCheckSuppression and ec2:DisableApplicationStatusCheckSuppression. After reporting resumes, the check evaluates the application again and returns the instance to healthy once it passes, so a routine deployment does not trigger a replacement.

AWS Systems Manager maintenance windows

For scheduled maintenance such as patching, run the work inside an AWS Systems Manager maintenance window and bracket it with the suppression calls: an automation step that enables suppression before the patch task and disables it after. Reporting stays paused for the window and resumes on its own at the suppression resume time if a step does not complete.

Clean up resources

Application status checks incur charges while they are associated with instances. AWS charges for each managed elastic network interface (ENI) AWS creates in your VPC, per Availability Zone, and standard Amazon CloudWatch rates apply to the metrics the checks publish. AWS creates one endpoint per combination of source subnet and security group, so the count does not scale per instance or per check. Delete the resources you created so that you do not incur further charges. Delete the application status check and the CloudWatch alarm, and delete the Auto Scaling group if you created it only for this walkthrough.

aws ec2 delete-application-status-check --application-status-check-id asc-0123456789abcdef0
aws cloudwatch delete-alarms --alarm-names database-impaired

Quotas

Application status checks are subject to service quotas that cap how many checks you create, how many associations you make, and how many instances you monitor. Review the current defaults before you roll out to a large number of instances, because a tag-based association covers instances that launch later. A growing number of instances can reach a quota without any change to your configuration. Once you pass a quota, the instances beyond it stop being checked and report no status. Use the Service Quotas console to view usage and request increases. For the current quotas and how each one is counted, see Application status checks in the Amazon EC2 User Guide.

Conclusion

In this post, we showed how to monitor application health on Amazon EC2 with application status checks. You created an HTTP check, associated it with your instances by tag, viewed the status alongside your existing status checks, alarmed on it in Amazon CloudWatch, and relied on Amazon EC2 Auto Scaling to replace an impaired instance. You can use EC2 status checks and Auto Scaling to detect and respond to application failures rather than operate a separate monitoring system.

If you use another deployment mechanism, apply the association tag to each EC2 instance and make sure the application exposes the configured health path and port. Contact your AWS account team if you need help adapting this pattern to your deployment process.

To learn more, see Application status checks in the Amazon EC2 User Guide and Health checks for instances in an Auto Scaling group in the Amazon EC2 Auto Scaling User Guide. As a next step, add a second check for a readiness path and exclude it from aggregation to see how per-check status contributes to the instance-level result.


About the author

Caroline Frost

Caroline Frost

Caroline is an Amazon EC2 Senior Product Manager – Technical, focusing on the EC2 instance lifecycle. She is passionate about building capabilities that improve the developer experience and create operational ease and simplicity.

Building a GPU workstation for visual effects with Amazon EC2: Part 5 – Security

Post Syndicated from Andy Hayes original https://aws.amazon.com/blogs/compute/building-a-gpu-workstation-for-visual-effects-with-amazon-ec2-part-5-security/

For many years Amazon Web Services (AWS) has been guiding users in the deployment of powerful NVIDIA GPU backed workstations for graphics intensive workloads. With the recent expansion of our G-series Amazon Elastic Compute Cloud (Amazon EC2) graphics-based instances, we’re excited to introduce new instance families that deliver enhanced performance and capabilities. We’re also refreshing our comprehensive guidance on choosing and configuring these powerful virtual workstations.

This is the fifth post in a five-part series, exploring security practices related to the deployment of visual effects (VFX) workstations: how to secure these workstations by controlling who can reach the desktop, protecting the session in transit, and safeguarding the credentials, images, and storage behind it. The following screen capture shows these GPU-powered workstations in use, in a real production environment.

Rocky Linux-based GPU workstations in use by artists in a studio, each with two monitors

Figure 1: Amazon EC2 GPU-powered workstations, used in a Studio-in-the-Cloud courtesy of Outpost VFX

Before you begin

This post builds upon topics covered earlier in the series, regarding Linux and Windows EC2 instances, configured for the purposes of creating GPU workstations.

If you want to understand more about GPU accelerated Amazon EC2 G graphics instances, go to Part 1 in this series: Build a GPU workstation for visual effects on Amazon EC2: Part 1 – Setup.

For deployment instructions for creating a Rocky Linux graphics workstation, go to Part 2 in this series: Building a GPU workstation for visual effects on Amazon EC2: Part 2 – Linux.

For creating a Windows Server 2025 graphics workstation, go to Part 3 in this series: Building a GPU workstation for visual effects with Amazon EC2: Part 3 – Windows.

Finally, for methods to standardize and optimize instances, for rapid re-use at scale, go to Part 4 in this series: Building a GPU workstation for visual effects with Amazon EC2: Part 4 – Optimizations.

Security considerations

When deploying EC2 instance workloads on Amazon EC2, security hardening isn’t only a best practice but also essential for protecting your infrastructure, data, and applications from evolving threats. AWS provides secure cloud infrastructure, but the responsibility for securing the operating system and applications running on your EC2 instances falls squarely on you as part of the AWS Shared Responsibility Model. While AWS secures the underlying infrastructure (the physical servers, networking equipment, and hypervisor layer), you’re responsible for everything from the guest operating system upward. This includes patching, configuration management, access controls, and monitoring. A misconfigured EC2 instance can become an entry point for unauthorized users, potentially impacting more than that single instance in your AWS environment through lateral movement.

Throughout this post series, we’ve implemented security best practices aligned with the AWS documentation on Best practices for Amazon EC2. As we conclude, let’s revisit the key security principles we’ve applied and explore additional considerations for production environments.

Amazon DCV connection security

Amazon DCV provides immediate out-of-the-box encryption of pixels and end-user inputs, and to do so it creates a self-signed certificate. As previously mentioned, the browser issues a security warning when you connect by default. This is expected because the browser can’t verify the certificate’s authenticity in terms of domain or validity by a Certificate Authority (CA). Amazon DCV doesn’t immediately know your domain requirements for servers or clients. You elect to accept the risk based on your knowledge of the IP in question that you are connecting to.

Amazon DCV itself has further configurations that can mitigate potential security risks. For example, the DCV server can perform administrator-defined regex filtering on origin and host names to protect against WebSocket hijacking, and Host Header attacks. On Linux, add the following to dcv.conf, typically found at /etc/dcv/dcv.conf:

# Under [security] add the following line:
allowed-ws-origin-regex = ^https://(www\.)?example\.com(:443)?$
allowed-http-host-regex = ^(www\.)?example\.com$

On Windows, you add the respective string values for each parameter subkey within the Computer\HKEY_USERS\S-1-5-18\Software\GSettings\com\nicesoftware\dcv\security registry key. The following screen capture shows this registry key open in Registry Editor, with the connectivity-restriction values in place. In this example, two values are defined under the security key (allowed-ws-origin-regex and allowed-http-host-regex) each set to a regular expression that limits connections to a specific domain.

Windows Registry Editor showing the Amazon DCV security key with allowed-ws-origin-regex and allowed-http-host-regex subkeys limiting connectivity to one domain

Figure 2: The Amazon DCV registry security key, with subkeys limiting host and origin connectivity

For more information about security parameters with Amazon DCV, see security parameter reference of the Amazon DCV Administrator Guide.

Amazon DCV clients requesting connections to the Amazon DCV server can be restricted through fundamental network-level controls that allow requests from specific IP addresses and ports:

  • AWS Network Access Control List (ACLs) restrict inbound and outbound traffic at the subnet level on the VPC.
  • AWS Security Groups (as already mentioned and used in this post) apply another layer of restrictions on incoming IP addresses and ports to the server instance.
  • Firewall rules can further restrict incoming IP addresses and ports.

To extend both the functionality and security of Amazon DCV, an Amazon DCV Connection Gateway can also be used as part of a more extensive infrastructure, to act as an intermediary between clients and servers. From a security point of view, it adds a single point of entry, hiding the servers behind the gateway, mitigating load, but also implementing a token-based authentication system to resolve server sessions for clients.

Whilst these steps prevent unauthorized access attempts from unexpected sources, it doesn’t solve the certificate trust warning. To improve both the user experience (to resolve the warning, and the general question of is this secure?) as well as strengthen your security defenses, consider using your own certificate from a trusted CA. This is beyond the scope of this post, but services such as AWS Private Certificate Authority provide the ability to create certificates that encapsulate your domain and can be trusted by the browser as a legitimate CA. Not only does this simplify the user experience but it also provides cryptographic verification of server identity and protection against man-in-the-middle attacks.

Network security

We have repeatedly applied the principle of least privilege, using Security Group rules to restrict access to known IP addresses only. As detailed in Part 1 of this series, the choice of connectivity method significantly impacts your security architecture, and while this post uses internet connectivity for simplicity, production environments should evaluate additional security layers based on their requirements. Network Access Control Lists (NACLs) can also be used for subnet-level traffic filtering as an additional defense layer to security groups, and AWS Network Firewall offers advanced threat protection and intrusion detection.

For enhanced security postures AWS Site-to-Site VPN adds network-layer IPsec encryption on top of the application-layer security of Amazon DCV, protecting against man-in-the-middle attacks, traffic analysis, and DNS hijacking while allowing workstations to reside in private subnets. AWS Direct Connect further strengthens security by bypassing the public internet entirely through dedicated fiber connections, reducing exposure to internet-based DDoS attacks, ISP-level surveillance, and routing attacks.

If you have strict compliance requirements, also consider deploying Amazon DCV servers in private subnets with AWS PrivateLink endpoints for fully private connectivity. For comprehensive guidance on these connectivity options and additional firewall and protection services that enhance protection against exploits such as ransomware and DDoS, see Security, Identity and Compliance on AWS (refer back to Part 1’s detailed comparison of connectivity architectures).

AWS Identity and Access Management (IAM)

IAM securely controls access to AWS. With IAM, you can manage authentication and authorization and grant your identities only the least-privilege permissions required for their tasks, reducing the risk of mistakes or unauthorized behavior. Throughout this post series, we’ve applied this principle of least privilege to IAM roles and policies. For example, we attached IAM roles to EC2 instances rather than using long-lived static credentials, eliminating the risk of exposed access keys.

For example, for the purposes of this post, we used read-only policies for S3. For production environments, we recommend taking this further by prescribing:

  • Access to specific S3 buckets using resource-level permissions.
    • For example, arn:aws:s3:::amzn-s3-demo-bucket/*.
  • Limiting actions to only what’s required.
    • For example, s3:GetObject instead of s3:*.

Credential security

As a best practice, we recommend changing default passwords immediately and aligning them with your organization’s password quality requirements, such as 16 or more characters with mixed case, numbers, and symbols. Any SSH key pairs should be rotated regularly in line with your organizational requirements.

Monitoring and logging

You can use a number of tools and services to monitor activity within an AWS account. For example, use AWS CloudTrail to audit IAM actions and API calls for compliance and security, and implement Amazon CloudWatch alarms to warn about specific security events. AWS Identity and Access Management Access Analyzer can be used to identify resources shared with external entities and validate that your IAM policies grant only intended access, whilst VPC Flow Logs monitor and allow you to audit network traffic patterns within your network. For vulnerability detection, Amazon Inspector can scan EC2 instances for software and network exposure, whilst Amazon GuardDuty can continuously monitor for threat detection across your infrastructure, looking for suspicious or malicious behavior.

Encryption

Encrypting your data at rest, and in transit helps protect against unauthorized access even if storage media is compromised or network traffic is intercepted. In these posts we made sure that Amazon Elastic Block Store (Amazon EBS) volumes for our instances were all encrypted using AWS Key Management Service (KMS) for encryption key management, providing cryptographic verification and centralized key rotation capabilities. We explored Transport Layer Security (TLS) encryption for Amazon DCV, which helps protect your desktop pixels and user inputs during transmission using TLS v1.2 or greater with strong cipher suites.

Patch management

Consider build-time hardening services such as EC2 Image Builder to automate the creation of Amazon Machine Images (AMIs) that apply the latest security patches, remove unnecessary components, and install anti-malware protection.

For lifecycle management, AWS Systems Manager Patch Manager can automate patching across your fleets. It uses patching policies that scan for and install approved updates on a schedule you define (weekly is recommended). Patch Manager is particularly valuable for fleet-wide VFX workstations because it centralises patching control across multiple accounts and AWS Regions. It supports custom patch baselines, so you can define what counts as compliant for your organisation. It also integrates with AWS Security Hub CSPM (Cloud Security Posture Management) and AWS Config for greater visibility, and it maintains audit trails through AWS CloudTrail.

Backup and recovery

Amazon EBS snapshots represent a cost-effective, encrypted, point-in-time backup of your instance data (such as the operating system and applications) residing on EBS volumes. They’re stored in Amazon Simple Storage Service (Amazon S3). Incremental versions only store the deltas in data from previously stored volumes (deletions of snapshots only remove unique data associated with that volume). With snapshots, you can retrieve a prior state (snapshot) of an instance and resume work or even turn a snapshot into an AMI for more permanent use. Whilst many companies using VFX workstations on AWS tend to regularly launch new daily instances for their artists (avoiding ‘stopped’ state charges overnight and ensuring artists are using up-to-date AMIs), long-term use of Amazon EC2 instances can use EBS snapshots to instigate disaster recovery preparation against accidents, corruption, or ransomware. It’s vital when using disaster recovery processes such as EBS snapshots, that testing is done to confirm that recovery procedures work when needed.

Conclusion

This post has covered essential security practices including network controls, IAM policies, encryption, monitoring, and threat detection, which are all foundational elements of a comprehensive security strategy. For production deployments, we strongly recommend consulting the AWS Security Best Practices documentation and the AWS Well-Architected Framework Security Pillar to explore additional security services, compliance frameworks, and industry-specific guidance tailored to your organization’s requirements.

For more information contact us at .


About the authors

Andy Hayes

Andy Hayes

Andy is a Senior Visual Computing Solutions Architect at AWS. With 20 years’ experience in Visual Effects and Animation, Andy has led CG divisions and departments and added supervision to film projects, earning both Annie and Visual Effects Society Awards along the way. At AWS, he partners with studios and creative technology companies across the Media & Entertainment industry, spanning VFX and animation to rendering, virtual production, and games, helping them design and scale the cloud infrastructure and workflows behind their content pipelines. Drawing on his production background, Andy bridges the worlds of artists and engineers, guiding customers as they adopt technologies like high-performance rendering, GPU compute, and increasingly AI and machine learning to solve real creative and technical challenges. He remains passionate about the marriage of art and science that leads to the creation of compelling imagery, and about aligning technology to the evolving needs of the industry.

Alex Waddell

Alex Waddell

Alex is a Principal Security Specialist SA at AWS, specialising in security within the Worldwide Specialist Organisation (WWSO) GTM Specialists team for EMEA. Based in Scotland, he helps enterprise customers design and build secure, scalable cloud architectures, with a focus on security strategy, identity, threat detection and application security at scale, helping organisations move faster without trading away security. Alex is a regular contributor to the security community and speaks on the real-world challenges of securing modern cloud environments. Alex has been with AWS since 2021 and works across the region to bring security best practice into customer engagements.

Mike Owen

Mike Owen

Mike is a Principal Visual Computing Solutions Architect at AWS, where he has spent many years helping studios move their creative work to the cloud. He focuses on the architecture behind high-end content creation: cloud workstations, render farm scaling and storage that spans multiple sites. Mike works with studios and creative technology companies across Media & Entertainment, from VFX and animation to finishing and colour. He has pioneered the concept of “Studio in the Cloud” and helped bring industry tools such as Autodesk Flame to AWS, and has contributed to a range of AWS Thinkbox Deadline improvements. Most recently he has led development of KNFSD File Cache, an open-source NFS caching solution from AWS. It lets studios burst large render workloads into the cloud whilst their data stays on existing on-premises storage. He cares about giving artists the same seamless, colour-accurate experience in the cloud that they expect on-premises, and about removing the cost and complexity that usually come with building a global studio.