Tag Archives: announcements

Long-term Amazon Redshift observability with Datadog and Amazon S3 Tables

Post Syndicated from Raghu Kuppala original https://aws.amazon.com/blogs/big-data/long-term-amazon-redshift-observability-with-datadog-and-amazon-s3-tables/

Building long-term observability for Amazon Redshift starts with a question: what happened in your data warehouse last month, last quarter, or last year? Amazon Redshift captures operational history across more than 25 system views. These views range from query execution details in SYS_QUERY_HISTORY and full query text in SYS_QUERY_TEXT to connection activity, user changes, workload management events, and resource consumption metrics. Together, these views form a detailed record of the operations running inside your Amazon Redshift clusters and Amazon Redshift serverless workgroups. Amazon Redshift retains this data for 7 days. After that window closes, the history is gone. You lose the ability to audit past activity, investigate slow-moving regressions, or satisfy compliance requirements that can span months or years.

The system table integration with Amazon S3 Tables, a capability of Amazon Redshift, changes this. When you enable the integration, Amazon Redshift automatically and continuously delivers system table data as Apache Iceberg tables to Amazon S3 Tables in your account. You own the data, you set the retention policy, and S3 Tables handles compaction and snapshot maintenance. You can query the exported data with Amazon Redshift, Amazon Athena, or any Iceberg-compatible engine. There’s no charge for delivery. You pay only for S3 Tables storage, requests, maintenance, and the engine you use to read the data.

AWS and Datadog collaborated to make this exported data actionable for observability. Datadog, an AWS Specialization Partner and AWS Marketplace Seller, provides an observability and security platform for cloud applications. Datadog Data Observability helps data teams improve the reliability of data for analytics and AI. It combines quality monitoring for warehouses such as Amazon Redshift with jobs monitoring for pipelines that run on AWS Glue, Amazon EMR, Apache Airflow, and dbt. It then connects them with lineage that spans from source pipelines to downstream dashboards. By reading query history directly from S3 Tables, Datadog turns it into column-level lineage, query analysis, and context for quality alerts, without adding load to your warehouses to collect it. For AWS managed monitoring of Amazon Redshift metrics and logs, you can also use Amazon CloudWatch. Datadog Data Observability is billed separately by Datadog.

In this post, we show how to configure Datadog Data Observability to read Amazon Redshift query history from S3 Tables. We walk through granting Datadog read access and using the query history for column-level lineage, query analysis, and data quality monitoring.

Solution overview

Datadog Data Observability uses Amazon Redshift query history to build column-level lineage, analyze query performance, and give context to data quality alerts. Previously, Datadog collected this history by running read-only SQL against each warehouse every hour. With this solution, Datadog reads the same history from S3 Tables instead. The following diagrams show the solution at a high level and compare query history collection before and after the integration.

Datadog Data Observability reads Amazon Redshift query history from Amazon S3 Tables for long-term observability

Figure 1: High-level solution overview

Comparison of query history collection: before the integration Datadog runs hourly read-only SQL on each Amazon Redshift warehouse; after, it reads the same history from Amazon S3 Tables without querying the warehouse

Figure 2: Query history collection before and after the S3 Tables integration

This approach offers the following benefits:

  • Retention beyond 7 days. Query history remains in your account for as long as you choose to retain it. Because history is kept in S3 rather than expiring after 7 days in the cluster, Datadog can backfill any collection gap when it resumes. You don’t lose queries or lineage. Your audit and compliance teams also keep a long-term record of query activity in your own account.
  • No added load on the warehouse. Datadog reads the Iceberg tables through the S3 Tables Iceberg REST endpoint. Collecting query history doesn’t run queries on your clusters or workgroups or consume their compute.
  • One view across warehouses. Datadog combines query history from every connected cluster and workgroup into a single lineage graph, together with other connected tools such as dbt, Apache Airflow, Tableau, Looker, and Power BI.

The following diagram illustrates the solution architecture.

Amazon Redshift delivers system table data to Amazon S3 Tables, and Datadog reads it through the S3 Tables Iceberg REST endpoint

Figure 3: Solution architecture

The workflow consists of the following steps:

  1. Amazon Redshift periodically writes completed query records from SYS_QUERY_HISTORY and SYS_QUERY_TEXT to the AWS managed aws-redshift table bucket in Amazon S3 Tables. An isolated background process handles these writes, separate from your production workloads.
  2. Datadog uses the AWS Identity and Access Management (IAM) role from your Datadog AWS integration to read new rows through the S3 Tables Iceberg REST endpoint. Because data is delivered in batches at a fixed frequency, Datadog tracks the last batch it read, so no batch is skipped or read twice.
  3. Datadog masks sensitive literals in the query text, parses each query into column-level lineage, and groups similar queries into normalized query profiles.
  4. Datadog still connects to Amazon Redshift for table metadata, such as schemas and row counts, and to run the data quality monitors that you configure.

Prerequisites

To implement this solution, you need the following:

  1. An AWS account with one or more Amazon Redshift provisioned clusters (RG or RA3 node types) or Amazon Redshift Serverless Workgroup.
  2. The system table integration with Amazon S3 Tables enabled for each warehouse you want to monitor. At minimum, enable sys_query_history and sys_query_text. Datadog reads per-warehouse exports, so set the granularity to cluster for provisioned clusters or workgroup for Serverless namespaces. To enable the integration, see Enabling system table integration with Amazon S3 Tables.
  3. The Amazon S3 Tables integration with the AWS Glue Data Catalog enabled in your account and Region. This is a one-time setup step. If you already integrated S3 Tables with the AWS Glue Data Catalog, no further action is needed. For instructions, see Integrating Amazon S3 Tables with AWS analytics services.
  4. An IAM principal with the following permissions:
    • redshift:EnableLogging (provisioned) or redshift-serverless:UpdateNamespace (Serverless).
    • s3tables:CreateTableBucket, s3tables:PutTableBucketEncryption, and s3tables:PutTableBucketPolicy.
  5. The AWS Command Line Interface (AWS CLI) installed and configured.
  6. A Datadog account with the Datadog AWS integration configured and your warehouse connected to Datadog Data Observability for Amazon Redshift.
  7. Access to the Datadog Data Observability S3 Tables preview. To request access, contact your Datadog account team.

Note: Plan your encryption strategy before enabling the integration. If you encrypt the tables with a customer managed AWS Key Management Service (AWS KMS) key, you can’t change the key after the tables are created. If you plan to consolidate warehouses later, choose a shared AWS KMS key from the start.

Grant Datadog read access to the system tables

Datadog reads the system tables with the IAM role that your Datadog AWS integration uses. Complete the following steps:

  1. On the IAM console, in the navigation pane, choose Roles, then choose the role used by your Datadog AWS integration.
  2. Choose Add permissions, then choose Create inline policy.
  3. Choose the JSON tab and enter the following policy, replacing <region> and <account-id> with your values:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "DatadogReadRedshiftSystemTableBucket",
            "Effect": "Allow",
            "Action": "s3tables:GetTableBucket",
            "Resource": "arn:aws:s3tables:<region>:<account-id>:bucket/aws-redshift"
        },
        {
            "Sid": "DatadogReadRedshiftSystemTables",
            "Effect": "Allow",
            "Action": [
                "s3tables:GetTableMetadataLocation",
                "s3tables:GetTableData"
            ],
            "Resource": "arn:aws:s3tables:<region>:<account-id>:bucket/aws-redshift/table/*"
        }
    ]
}
  1. Enter a name for the policy, for example DatadogRedshiftSystemTablesRead, and choose Create policy.

Note: If you encrypted the tables with a customer managed AWS KMS key, also grant the role kms:Decrypt permission on that key.

Use S3 Tables as the query history source in Datadog

During the preview, your Datadog account team enables S3 Tables as the query history source for your Datadog organization. Datadog then reads query history for each connected Amazon Redshift warehouse from S3 Tables instead of from the warehouse. Datadog tracks its position in the query history for each warehouse, so switching between sources doesn’t skip or duplicate queries.

Analyze query history in Datadog Data Observability

Query history feeds three parts of Datadog Data Observability:

  • Lineage. Shows how data moves between tables, jobs, and dashboards.
  • Query analysis. Shows who produces and consumes that data, and at what cost.
  • Quality monitoring. Uses both to decide which tables to watch and to explain each alert.

Datadog builds all three from the same query history, so they work the same way whether the history comes from the warehouse or from S3 Tables.

The examples in this section use an Amazon Redshift table named analytics.fct_orders. A nightly job loads it from staging.stg_orders, and a Tableau dashboard reports revenue from it.

Note: The figures use a sample environment, so they show a database named prod and a table named int_orders_enriched instead of analytics.fct_orders.

Column-level lineage

Datadog lineage view anchored on a table, with upstream tables and jobs on the left and downstream tables and dashboards on the right, grouped by column

Figure 4: End-to-end lineage upstream of, through, and downstream of the prod database

Datadog parses each query in the history into column-level lineage. To explore it, complete the following steps:

  1. Choose Data Observability, then Lineage.
  2. Search for prod to anchor the graph on the database. Figure 4 shows the result: source tables such as orders flow through the raw, staging, and intermediate schemas into marts. To focus on a single table such as users, search for that table instead.
  3. Review upstream tables and jobs to the left, and downstream tables and dashboards to the right. An Upstream issue label marks assets affected by a problem further upstream.
  4. To see column-level lineage, expand a table to show its columns and how each one flows into downstream tables. To trace a single column from source to dashboard, change the asset type to Column and search for it.

In addition to Amazon Redshift, the lineage graph supports other sources. When you connect other integrations, upstream jobs from Apache Airflow or dbt and downstream dashboards from Tableau, Looker, or Power BI appear in the same graph. Datadog builds lineage from the query history in the time window you choose, so widen the window to include jobs that run weekly or monthly.

Two common lineage workflows are:

  • Root cause analysis. Anchor on a broken table or dashboard, set the downstream depth to 0, and step upstream. Tables flagged by a quality monitor show their status on the graph, so you can see where a problem starts.
  • Impact analysis. Before you change or drop a column, anchor on it, set the downstream depth to the maximum, and switch to the List view to see every table and dashboard that depends on it.

Query analysis

Query analysis turns your Amazon Redshift query history into trends, so you can catch queries that slow down or scan more data over weeks and months, not just the last 7 days. Figure 5 shows the result for the last question: an INSERT run by the etl_svc user.

Datadog Queries page showing a normalized INSERT pattern run by the etl_svc user, with charts for query count, execution time, average duration, bytes scanned, and bytes spilled over the past week

Figure 5: Query count, execution time, and data scanned for a normalized INSERT pattern

To explore query patterns:

  1. Choose Data Observability, then Queries, and choose Amazon Redshift.
  2. Review normalized query patterns. For each pattern, Datadog shows how often it runs, how long it takes, and how much data it scans.
  3. Group patterns by query, cluster, user, database, or statement type.
  4. Filter by the tables they read or write.

Because Datadog combines the query history from every connected cluster and workgroup, you can answer the following questions across your whole Amazon Redshift footprint:

  • Which query patterns take the longest or read the most data?
  • Which users or service accounts run the most expensive queries?
  • Which queries write to analytics.int_orders_enriched, and how has their runtime changed over time?

Quality monitoring

Quality monitors alert you when an Amazon Redshift table is not updated, changes unexpectedly in volume, or contains values that fall outside its normal range. Lineage then shows the upstream cause and the downstream impact.

Datadog anomaly monitor for orders per hour by traffic source, with two of four series alerting and the current value of 628 below the expected lower bound of 1,027

Figure 6: An anomaly monitor on orders per hour in Datadog

Data Observability monitors track the following metrics:

  • Freshness
  • Row count
  • Column-level metrics such as nullness and uniqueness
  • Custom SQL metrics

Each monitor can use anomaly detection, which learns a metric’s trends and seasonality so that you don’t need to set a threshold for every table. Figure 6 shows an anomaly monitor on orders per hour, grouped by traffic source. When the metric falls outside its expected range, Datadog flags the likely upstream cause and the downstream assets at risk. Schema change monitors (currently in preview) alert when an Amazon Redshift table or column is added, removed, or renamed, or when a column type changes.

Lineage also helps you decide what to monitor. For example, add a relation filter to monitor every table upstream of a specific dashboard.

Quality monitoring runs aggregate queries in Amazon Redshift, such as COUNT(*) and MAX(<timestamp_column>), and sends only the resulting values to Datadog, not rows from your tables. To protect sensitive columns, you can use Amazon Redshift dynamic data masking.

Example: Trace a stale dashboard to its cause

The following steps show how these features work together when the revenue dashboard stops updating:

  1. A freshness monitor on analytics.fct_orders alerts in Slack that the table hasn’t updated since its usual 02:00 load.
  2. On the Lineage page, you anchor on fct_orders. The monitor on the upstream table staging.stg_orders is healthy, so the source data arrived and the problem is in the step that builds fct_orders. The graph also shows that the Tableau revenue dashboard depends on fct_orders.
  3. On the Queries page, you filter to queries that write to analytics.fct_orders. The nightly INSERT pattern run by the etl_svc user shows failed runs starting at 02:00.
  4. You fix the job and, before you rerun it, use impact analysis to list the downstream tables and dashboards whose owners you notify.

Clean up

To stop writing system table data to S3 Tables, for a provisioned cluster, run the following command:

aws redshift disable-logging \
    --cluster-identifier <cluster-identifier> \
    --log-destination-type s3table \
    --log-exports sys_query_history sys_query_text

For an Amazon Redshift Serverless namespace, run the following command:

aws redshift-serverless update-namespace \
    --namespace-name <namespace-name> \
    --log-destination-type s3table \
    --s3-table-action Disable \
    --s3-table-names sys_query_history sys_query_text

Before you run the preceding commands, ask your Datadog account team to switch the query history source back to the warehouse. Datadog then resumes collecting query history from your warehouse where it left off, so lineage and query analysis continue without a gap.

Disabling the integration stops new deliveries but keeps the data that was already written. Amazon Redshift doesn’t deliver system table data to S3 Tables while the integration is disabled, so your long-term record in S3 Tables won’t include that period. Re-enabling the integration doesn’t backfill that period, and after 7 days, Amazon Redshift no longer retains those queries in the warehouse either. To stop incurring storage charges, delete the tables. Deleting the tables permanently removes the retained data, and Amazon Redshift doesn’t recreate them automatically.

Conclusion

In this post, we showed how to configure Datadog Data Observability to read Amazon Redshift query history from Amazon S3 Tables. With this integration, you can:

  • Retain query history beyond the 7-day in-cluster limit for auditing and compliance.
  • Collect query history without adding load to your warehouses.
  • Analyze lineage and query activity across all your clusters and workgroups in one place.

AWS and Datadog built this integration together so you can use Amazon Redshift system table data in your existing observability workflows.

If you’re new to Datadog, you can sign up for a free trial. If you have questions or suggestions, leave them in the comments.

Additional resources


About the authors

Raghu Kuppala

Raghu Kuppala

Raghu is an Analytics Specialist Solutions Architect experienced working in the databases, data warehousing, and analytics space. Outside of work, he enjoys trying different cuisines and spending time with his family and friends.

Raza Hafeez

Raza Hafeez

Raza is a Senior Product Manager, Technical at Amazon Redshift. He has 15+ years of experience building and optimizing enterprise data warehouses and is passionate about making cloud analytics accessible and cost-effective for customers of all sizes.

Kevin Hu

Kevin Hu

Kevin helps lead the Data Observability product at Datadog. He was previously co-founder and CEO of Metaplane, a data observability company acquired by Datadog.

Todd Pollak

Todd Pollak

Todd is a Staff Software Engineer at Datadog, working on the Data Observability product. He was previously Head of Engineering at Metaplane.

Introducing Amazon OpenSearch Memory: Persistent memory for AI agents

Post Syndicated from Ganesh Natarajan original https://aws.amazon.com/blogs/big-data/introducing-amazon-opensearch-memory-persistent-memory-for-ai-agents/

Today, we are announcing the general availability of Amazon OpenSearch Memory, a new capability built on Amazon OpenSearch Serverless for adding persistent memory to AI agents. OpenSearch Memory stores agent interactions as searchable events, derives useful memories, and retrieves relevant context across sessions. You can give agents long-term memory without provisioning infrastructure or building separate extraction, indexing, consolidation, and retrieval systems.

AI agents need memory when an interaction depends on information from an earlier session. A support agent might recall a customer’s open case and product configuration, a coding agent needs repository conventions and prior decisions, and a personal assistant keeps a user’s preferences. An agent that restarts or hands off a conversation also needs the exact turns that came before. Passing the complete conversation history to the model becomes slower and more expensive as that history grows, and the relevant information can be difficult to find.

Building a memory system requires more than storing transcripts. You must capture events, extract facts and summaries, generate embeddings, reconcile new information with existing memories, retrieve the right context, isolate data, and enforce retention and deletion policies. You must also operate the infrastructure and evaluate whether the retrieved memories improve agent responses.

OpenSearch Memory manages these functions as one serverless capability. Your application writes conversation events after each turn and searches for relevant memories and events before generating a response. OpenSearch Memory stores the original events verbatim, makes them searchable within seconds, and asynchronously derives structured memories. It handles extraction, embedding, indexing, consolidation, retrieval, data isolation, and retention.

How OpenSearch Memory works

The architecture has two boundaries: your application and OpenSearch Memory. Your AI agent connects through an AWS SDK, an AWS Model Context Protocol (MCP) server, a hook, or a supported framework integration. The following diagram shows how your application writes events to a space, how OpenSearch Memory derives memories using an Amazon Bedrock model that you choose, and how your application retrieves context. Extraction and embedding costs are included in OpenSearch Memory pricing. For details, see Amazon OpenSearch Service pricing.

Amazon OpenSearch Memory architecture: an application writes events to a space, an Amazon Bedrock model derives memories, and the application retrieves context

Figure 1: How an application writes events to an Amazon OpenSearch Memory space, derives memories with an Amazon Bedrock model, and retrieves context

OpenSearch Memory organizes data in a space, the AWS resource that serves as a memory store. A space contains the following:

  • Events, which are the original interactions written by your application.
  • Memories, which are facts, preferences, and summaries derived from those events.

Every request names an actor, the end user the data belongs to. An optional session ID groups events from one conversation. A condition key on the agent’s AWS Identity and Access Management (IAM) role can limit which actors the agent can act for, and event reads and searches can be limited to one session. Data in a space is encrypted with AWS Key Management Service (AWS KMS), and you can use your own customer managed key. AWS CloudTrail logs API calls to a space, and Amazon CloudWatch reports its metrics.

The write and retrieval paths operate independently:

  1. After each interaction, your application writes the conversation turn to a space as an event. OpenSearch Memory stores the event verbatim (CreateEvent) and indexes it for keyword, semantic, and hybrid search. Events are available to read immediately and become searchable within seconds.
  2. In the background, the memory strategies configured on the space extract memories from these events.
  3. OpenSearch Memory compares each new memory with the existing ones and adds, updates, or skips it, so stored memories stay current.
  4. Before the agent responds, your application retrieves context: memories about the user from past conversations, the exact turns of the current or earlier conversations, or both. Your application adds the retrieved context to the model’s prompt.

Benchmarking OpenSearch Memory with LongMemEval

In this evaluation, the configured OpenSearch Memory workflow gave the answering model about one-twelfth as many input tokens as the full conversation history (about 13,500 compared with 167,000 per question). It preserved most of its answer accuracy: 93.0% compared with 95.2%.

We used LongMemEval-S to evaluate whether a complete memory workflow could help an AI assistant answer questions that depend on earlier conversations. The public benchmark contains 500 questions about information distributed across approximately 50 chat sessions for one user (Wu et al., ICLR 2025). It evaluates the final answers produced using retrieved memories, rather than memory extraction alone.

For this evaluation, we configured the OpenSearch Memory workflow as follows:

  1. We wrote the benchmark conversations to OpenSearch Memory as events.
  2. The space’s default memory strategies, for facts and session summaries, derived and consolidated memories from those events.
  3. For each question, the answering model received the top 30 memories and events from hybrid search.
  4. Claude Opus 5.5 answered each question from those results and, in a separate call, graded each answer against the benchmark’s reference answer.

Claude Haiku 5.5 extracted memories, and Amazon Titan Text Embeddings created the embeddings. Each result comes from one run, with a 95% confidence range of 2 to 3 points either way. To limit grading bias, Opus 5.5 graded each answer in a separate call that saw only the question, the reference answer, and the answer.

We compared the OpenSearch Memory workflow with two baselines: retrieving raw conversation turns with BM25 keyword search, and supplying the complete conversation history to the answering model. Claude Opus 5.5 answered and graded all three.

Context supplied to the answering model What the comparison measures Answer accuracy Context tokens per question
OpenSearch Memory: top 30 results from memories and events The configured extraction, consolidation, and hybrid retrieval workflow 93.0% Approximately 13,500
BM25: top 30 raw conversation turns Keyword retrieval without memory extraction or consolidation 88.6% Approximately 22,700
Full conversation history Answering with all conversation turns 95.2% Approximately 167,000

For agents with long-running conversations, this approach can reduce model input costs and preserve room in the context window without discarding information from earlier sessions. The workflow also scored 4.4 percentage points higher than BM25 retrieval over raw conversation turns. These results reflect the tested setup, including its memory strategies, models, and retrieval settings, and do not represent every possible OpenSearch Memory configuration.

Getting started with Amazon OpenSearch Memory

You can create your first space from the Amazon OpenSearch Service console or the AWS SDK. The following sections walk through both.

Launch OpenSearch Memory from the console

You can create a space and inspect its events and memories in the Amazon OpenSearch Service console. The following video shows the steps.

  1. In the Amazon OpenSearch Service console, under Memory, choose Spaces, and then choose Create Space.
  2. Choose Easy create, enter a space name, and choose Create Space. Easy create adds a Semantic and a Summary strategy and uses service defaults for encryption and expiry. Choose Standard create to set these yourself.
  3. Wait for the status to change from Creating to Active. The Memory strategies tab shows the strategies on the space.
  4. After your agent writes events, open the Events tab and enter an actor ID to see each conversation. The Memories tab shows the memories extracted from those events.

Walkthrough with the AWS SDK

This walkthrough adds memory to a customer support agent. The agent needs to remember account details, prior case history, and user preferences across sessions.

Prerequisites

To follow this walkthrough, you need the following:

  • An AWS account with permissions to create and use OpenSearch Memory spaces.
  • Python 3.10 or later and the AWS SDK for Python (Boto3) 1.44.4 or later.
  • One of the supported AWS Regions: US East (N. Virginia), US West (Oregon), Asia Pacific (Tokyo), or Europe (Frankfurt).

1. Create a space

You start by creating a space for the support agent. This is a one-time setup. The space defines what the service extracts, how long it keeps data, and how it encrypts it.

import boto3

REGION = "us-east-1"
osm = boto3.client("opensearchmemory", region_name=REGION)

space = osm.create_space(
    name="customer-support-agent",
    memoryStrategies=[
        {"type": "SEMANTIC", "name": "facts-and-preferences"},
        {"type": "SUMMARY", "name": "session-summaries"},
    ],
    eventExpiryDays=90,       # keep raw events for 90 days (1-365)
    memoryExpiryDays=365,     # keep memories for 1 year (0 = never expire)
    # extractionModelId="anthropic.claude-opus-5-5",  # optional; Claude Haiku 5.5 by default
    # encryptionConfiguration={"kmsKeyArn": "..."},  # optional customer managed AWS KMS key; can only be set here
)
space_id = space["spaceId"]

# The space starts in CREATING. The waiter returns once it is ACTIVE and raises if it reaches FAILED.
osm.get_waiter("space_active").wait(spaceId=space_id)

2. Write events after each turn

After each agent turn, you write an event. The call returns after the event is stored, and extraction runs in the background.

def conversational(turns):
    """Build a CreateEvent payload from [(role, text), ...]."""
    return {"conversational": {"unified": {"source": {"object": {
        "messages": [{"role": role, "content": {"text": text}} for role, text in turns]
    }}}}}

event = osm.create_event(
    spaceId=space_id,
    actorId="user-42",           # the end user
    sessionId="session-007",     # one stable ID per conversation
    payload=conversational([
        ("USER", "I'm calling again about Case #78234. It's still not resolved."),
        ("ASSISTANT", "I've escalated Case #78234 to billing. Your reference is ESC-5521, and billing will reply within 48 hours."),
    ]),
    metadata={"channel": "phone"},   # optional metadata, copied onto derived memories
)
event_id = event["event"]["eventId"]

Extraction freshness: Memories appear after the service processes the events in the background, so for a brand-new user, a memory search (step 3) can return nothing at first. Events don’t wait. They are readable as soon as the write returns and searchable within seconds. An agent that restarts or hands off the conversation can resume the session from its events right away. Use ListEvents to find the session’s recent events, and BatchGetEvent or GetEvent to read them. By default, ListEvents returns a session’s events newest first, so the following slice reads the most recent turns. Pass the sort parameter to return them oldest first instead.

# Resume the session: read its latest turns
recent = osm.list_events(spaceId=space_id, actorId="user-42", sessionId="session-007")
turns = osm.batch_get_event(
    spaceId=space_id,
    eventIds=[e["eventId"] for e in recent["events"][:10]],   # up to 10 IDs per call
)

Writing memories directly: You can also write a memory directly with CreateMemory. Use it to import what you already know, such as preferences from an existing customer relationship management (CRM) system, or to let the agent save its own findings. The service embeds and stores the memory under the strategy that you name.

# Import a preference from your CRM
osm.create_memory(
    spaceId=space_id,
    name="facts-and-preferences",   # a strategy name declared on the space
    actorId="user-42",
    content="The user prefers to be contacted by email.",
)

# Let the agent save its own finding about this user's case
osm.create_memory(
    spaceId=space_id,
    name="facts-and-preferences",
    actorId="user-42",
    content="Case #78234 is waiting on a manager approval code for the annual-plan refund.",
    metadata={"writtenBy": "support-agent"},   # marks agent-written memories so you can review or correct them later
)

The added metadata here keeps a record of which memories the agent wrote, so you can audit them later. Agent-written memories persist across sessions and feed later prompts, so review or correct them, for example by filtering on the writtenBy metadata, before you rely on them.

3. Search memories before each response

Before generating a response, you search the space for memories about this user and add them to the agent’s system prompt.

results = osm.search_memories(
    spaceId=space_id,
    actorId="user-42",            # every search is scoped to one actor
    query={
        "hybrid": {
            "queries": [
                {"match": {"memory_text": "Case #78234 open cases and account status"}},
                {"neural": {"memory_vector": {
                    "query_text": "open cases and account status", "k": 10}}},
            ]
        }
    },
    maxResults=10,
)

context = "\n".join(m["content"] for m in results["memories"])
# Add `context` to the agent's system prompt

In this support scenario, the keyword half of the query surfaces the exact case number from a prior session. The semantic half retrieves related context, such as the user’s preferred contact method and what the case is waiting on. The user doesn’t need to repeat themselves. Each turn adds two calls to your agent loop: one search before it responds, one write after.

Each result also carries sourceEventIds, the events the memory was derived from, so you can trace any fact back to the conversation that produced it.

Search the conversation itself: Memories capture what a conversation means. Events keep the conversation itself: every turn, verbatim, with who said it. To find an exact phrase, such as a commitment the agent made earlier in the conversation, search the events:

hits = osm.search_events(
    spaceId=space_id,
    actorId="user-42",
    sessionIds=["session-007"],   # optional: search only this conversation
    query={"match_phrase": {"text": "reply within 48 hours"}},
    maxResults=5,
)
snippets = [e["matchedContent"] for e in hits["events"]]   # the exact turns, with who said what

4. Let consolidation keep facts current

Users’ facts change. Consolidation handles the change without extra code.

# Session 1
osm.create_event(spaceId=space_id, actorId="user-42", sessionId="s-001",
    payload=conversational([("USER", "I'm based in New York.")]))

# Session 10, weeks later, after the user moves
osm.create_event(spaceId=space_id, actorId="user-42", sessionId="s-010",
    payload=conversational([("USER", "I just relocated to Seattle last week.")]))

# Once session 10 is processed, SearchMemories returns one updated memory,
# "The user was based in New York and relocated to Seattle ...",
# instead of keeping the old and new facts side by side.

Consolidation is on by default for every strategy. To keep an append-only history instead, set consolidationEnabled to False in the strategy’s configuration:

{"type": "SEMANTIC", "name": "facts-and-preferences", "configuration": {"consolidationEnabled": False}}

Clean up

To avoid incurring future charges, delete the space when you no longer need it. Deletion is permanent.

osm.delete_space(spaceId=space_id)
osm.get_waiter("space_deleted").wait(spaceId=space_id)

Get started today

Amazon OpenSearch Memory is generally available today in four AWS Regions: US East (N. Virginia), US West (Oregon), Asia Pacific (Tokyo), and Europe (Frankfurt). For pricing, including storage, retrieval, and extraction, see Amazon OpenSearch Service pricing. To start building, use the AWS SDK, the MCP server, or the OpenSearch Memory skills for Kiro, Claude Code, and Codex.

With OpenSearch Memory, your agents keep context across sessions without you building or operating a memory system.

To learn more, see OpenSearch Memory in the Amazon OpenSearch Service Developer Guide.

 


About the authors

Ganesh Natarajan

Ganesh Natarajan

Ganesh is a Senior Manager of Product Management for Amazon OpenSearch Service at AWS. He’s obsessed with building AI agents and making them run better.

Rishabh Agrawal

Rishabh Agrawal

Rishabh is a Senior Engineer at AWS, working on Amazon OpenSearch Service with a focus on agentic AI, memory systems, and intelligent retrieval. Previously, he worked on Amazon Bedrock and Amazon Personalize, building scalable AI and machine learning infrastructure. His interests include applied AI research and open source technologies.

Aruna Govindaraju

Aruna Govindaraju

Aruna is an Amazon OpenSearch Specialist Solutions Architect and has worked with many commercial and open source search engines. She is passionate about search, relevancy, and user experience. Her expertise with correlating end-user signals with search engine behavior has helped many customers improve their search experience.

AWS Lambda now supports GPU instances for Event Functions on Lambda Managed Instances

Post Syndicated from Daniel Abib original https://aws.amazon.com/blogs/aws/aws-lambda-now-supports-gpu-instances-for-event-functions-on-lambda-managed-instances/

GPU support is now available for EC2 G-series GPU instances for Event Functions running on AWS Lambda Managed Instances (LMI). You can now run GPU-accelerated workloads, including machine learning inference, media processing, rendering, and scientific computing, on GPU instances with serverless simplicity. GPU-accelerated functions are deployed as container (Open Container Initiative, OCI) images. You build an OCI image, point the function at it, and let Lambda handle provisioning, scaling, and event integration. There are no GPU drivers, CUDA versions, or AMIs to reconcile, and no clusters or device plugins to operate. GPU-accelerated functions run on the same Lambda Managed Instances foundation that already gives you Amazon EC2 pricing and specialized compute without managing servers.

Why customers need this
Customers keep asking to run GPU workloads with the simplicity of serverless. Building on self-managed GPU infrastructure means selecting instances, installing and reconciling GPU drivers and CUDA libraries, planning capacity, writing scaling logic, and hand-building the event integrations that connect the GPU step to the rest of the application. Serverless GPU services that hide that work often sit outside your AWS environment, with no native event sources, identity, or networking.

Cost is the second problem. GPUs are expensive, and utilization is usually low because a single workload rarely saturates a GPU. A small inference task can leave most of a provisioned GPU idle while you pay for the whole thing.

This feature closes both gaps. You bring a function, and Lambda runs it on a GPU in minutes, triggered by the same AWS events as any other Lambda Event Function, billed and secured the same way. It also maximizes utilization of every GPU you pay for, by consolidating functions onto instances and keeping GPUs busy across concurrent requests.

What you can build
You can run both AI/ML inference and non-ML workloads using GPU-accelerated compute on Lambda Managed Instances. This capability is optimized for inference rather than training, and custom models rather than large foundation models already available on services like Amazon Bedrock. Common workloads include:

  • Custom model inference: decision models (such as Strands Decider), computer vision, speech-to-text and text-to-speech, recommendation, document analysis, and small-to-mid-size language models deployed as part of an application.
  • Agentic and event-driven AI: custom inference triggered directly by AWS events, composed with the rest of the Lambda programming model.
  • Media processing and transcoding: video and image pipelines triggered on upload.
  • 3D rendering and generative media: frame and asset rendering, diffusion, and text-to-video generation.
  • Scientific computing and financial modeling: simulations, matrix computation, and risk analysis.

Part of the Lambda programming model
A GPU-accelerated function is one step in a larger application, and it composes with the rest of Lambda. Lambda durable functions orchestrate multi-step, long-running workflows around the GPU step, with checkpointing and automatic recovery. Lambda MicroVMs run untrusted or model-generated code in isolated, stateful sandboxes. In an agentic workload, a MicroVM executes the tool-use logic on CPU, then calls a GPU-accelerated function running on Lambda Managed Instances for inference.

GPU-accelerated functions also support the extended function timeout on Lambda Managed Instances, up to 90 minutes for asynchronous and event source mapping invocations, so you can run batch and other long-running GPU jobs, such as media transcoding or multi-step inference, without re-architecting. GPU-accelerated functions support container images up to 32 GB (10 GB per file), up to 32 GB of ephemeral storage, 2,048 to 32,768 MB of memory, 3 to 48 GB of accelerator memory, up to 48 concurrent requests per execution environment, and up to 15,000 vCPUs per capacity provider.

Let’s try it out
To show what this looks like in practice, I deployed an open-source large language model (LLM) from Hugging Face as a Lambda function and sent it a prompt. With the vLLM base image from Lambda, I only set the Hugging Face model ID in the MODEL_ID environment variable, without writing any inference code. I used Qwen/Qwen2.5-1.5B-Instruct, a small instruction-tuned model that suits in-application tasks such as summarization, classification, and extraction. The flow has four steps: create a capacity provider, build and push the container image, create a function from that image, then publish and invoke. Before you begin, request an increase to your G-series instance quota (listed as Running On-Demand G and VT instances), because new accounts might start with a quota of 0. For more information, see On-Demand Instance quotas.

First, I created a capacity provider, where I specify the GPU instance types Lambda can use and let it auto-scale. Listing several instance types lets Lambda pick the most cost-effective one that is available and fall back across generations when capacity is tight.

{
    "CapacityProviderName": "lmi-gpu-cp",
    "VpcConfig": {
        "SubnetIds": ["subnet-aaaa", "subnet-bbbb", "subnet-cccc"],
        "SecurityGroupIds": ["sg-aaaa"]
    },
    "PermissionsConfig": {
        "CapacityProviderOperatorRoleArn": "arn:aws:iam::111122223333:role/lmi-operator-role"
    },
    "InstanceRequirements": {
        "AllowedInstanceTypes": [
            "g5.2xlarge", "g6.2xlarge", "g6e.2xlarge"
        ]
    },
    "CapacityProviderScalingConfig": {
        "ScalingMode": "Auto",
        "MaxVCpuCount": 96
    }
}
aws --region us-east-2 \
  lambda create-capacity-provider \
  --cli-input-json file://cli-skeletons/create-capacity-provider_gpu.json

The Lambda console shows the new capacity provider, lmi-gpu-cp, in the Active state. Note the VPC configuration with its subnets and security group.
Lambda console showing the GPU capacity provider lmi-gpu-cp in the Active state with its VPC configuration

Figure 1: The capacity provider is Active, with its VPC configuration.

Next, I built the container image. Lambda provides a curated vLLM base image that includes the vLLM inference server, PyTorch, Transformers, and the CUDA toolkit, along with a runtime interface client that supports concurrent invocations. The image serves the model for me, so I don’t write a handler or any inference server code. My entire Dockerfile is one line:

FROM public.ecr.aws/lambda/deep-learning-containers/vllm:cuda-v1

After pushing the image to Amazon ECR, I created the function. I chose the model with the MODEL_ID environment variable, which accepts a Hugging Face or ModelScope repository, an Amazon S3 location, or a local path. Lambda downloads the model, manages GPU memory, and serves requests. Qwen2.5-1.5B-Instruct is a public model, so I didn’t need a Hugging Face token. For private or gated models, or to get higher download rate limits, you can also set HF_TOKEN.

GPU-accelerated functions use AcceleratorConfig to request accelerator memory. AcceleratorMemorySize is the minimum GPU memory the function needs, and Lambda places the execution environment on the smallest available GPU that meets it, so the GPU you get can have more memory than you requested. I set PerExecutionEnvironmentMaxConcurrency to 4, the default. The vLLM server batches concurrent requests on the GPU, so invocations share one copy of the model and the GPU stays busy. I also set ExecutionEnvironmentMemoryGiBPerVCpu to 4, which gives the function the 16,384 MB of memory and 4 vCPUs it needs while leaving capacity on the 2xlarge instance for Lambda’s management components.

{
    "FunctionName": "lmi-gpu-inference",
    "PackageType": "Image",
    "Code": { "ImageUri": "111122223333.dkr.ecr.us-east-2.amazonaws.com/lmi-gpu-inference:latest" },
    "Role": "arn:aws:iam::111122223333:role/lmi-gpu-inference-execution-role",
    "Timeout": 900,
    "MemorySize": 16384,
    "EphemeralStorage": { "Size": 32768 },
    "Environment": { "Variables": { "MODEL_ID": "Qwen/Qwen2.5-1.5B-Instruct" } },
    "CapacityProviderConfig": {
        "LambdaManagedInstancesCapacityProviderConfig": {
            "CapacityProviderArn": "arn:aws:lambda:us-east-2:111122223333:capacity-provider:lmi-gpu-cp",
            "ExecutionEnvironmentMemoryGiBPerVCpu": 4,
            "PerExecutionEnvironmentMaxConcurrency": 4
        }
    },
    "AcceleratorConfig": { "AcceleratorMemorySize": 16 }
}
aws --region us-east-2 \
  lambda create-function \
  --cli-input-json file://cli-skeletons/create-gpu-llm-function.json

The function overview shows what makes this a GPU-accelerated function: the attached capacity provider that supplies the GPU instances and the vLLM container image deployed from Amazon ECR, all wired into the same function model you already use.
Lambda console function overview for lmi-gpu-inference showing the attached capacity provider lmi-gpu-cp, the container image from Amazon ECR, and the x86_64 architecture

Figure 2: The lmi-gpu-inference function overview, showing the attached capacity provider and the vLLM container image deployed from Amazon ECR.

Functions on Lambda Managed Instances run from a published version, so I published one. Publishing provisions the execution environments, and each one downloads the model weights and warms up the engine before the version becomes active. The cold start happens during the publish step, so the first caller doesn’t wait for it.

aws --region us-east-2 \
  lambda publish-version \
  --function-name lmi-gpu-inference \
  --publish-to LATEST_PUBLISHED

Then I sent the model a prompt. The payload is a standard OpenAI request body: a messages array routes to chat completions, and a prompt field routes to text completions.

aws --region us-east-2 \
  lambda invoke \
  --function-name 'lmi-gpu-inference:$LATEST.PUBLISHED' \
  --cli-binary-format raw-in-base64-out \
  --payload '{"messages": [{"role": "user", "content": "Explain serverless GPU inference in one sentence."}], "max_tokens": 128}' \
  /dev/stdout

The model answered from a GPU inside the Lambda execution environment, and the response is a standard OpenAI completion object, so any OpenAI-compatible client works with it.

{
  "model": "Qwen/Qwen2.5-1.5B-Instruct",
  "choices": [
    {
      "message": {
        "role": "assistant",
        "content": "Serverless GPU inference is a cloud-based service that allows for efficient execution of machine learning models on NVIDIA GPUs without the need for infrastructure management or maintenance."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": { "prompt_tokens": 39, "completion_tokens": 31, "total_tokens": 70 }
}

Four concurrent invocations finished in about the same time as a single one, on one execution environment that shares one copy of the model in GPU memory. From a Hugging Face model ID to a live, OpenAI-compatible GPU endpoint took about 10 minutes, most of it unattended while Lambda provisioned capacity and warmed up the model.

That’s a working LLM endpoint with no inference server code, no GPU drivers, and no cluster to manage. To try a different model, I update MODEL_ID and publish a new version, with no image rebuild. Each version is an immutable snapshot, so different models can run side by side as separate versions. It is also a Lambda Event Function, so I can trigger it from an Amazon SQS queue to process documents in batches, put Amazon API Gateway in front of it, or call it as the inference step in a Lambda durable functions workflow.

For production, copy the model weights to an S3 bucket in the same Region, point MODEL_ID at that bucket, and set VLLM_LOAD_FORMAT=runai_streamer so the weights stream straight into memory. This gives faster starts and removes the dependency on the Hugging Face Hub. For more guidance, see the best practices for running inference workloads. Beyond LLM inference, you can also run custom ML inference, media processing, and other GPU workloads. See the Lambda documentation for best practices.

The configuration tab shows the settings that matter for a GPU-accelerated function: 16,384 MB of memory, the 15-minute timeout, and 32 GB of ephemeral storage for the downloaded weights, alongside the function-level capacity provider settings: per-environment concurrency of 4, the 4:1 memory-to-vCPU ratio, and 16 GB of accelerator memory.

Lambda console configuration tab for lmi-gpu-inference showing 16,384 MB of memory, the 15-minute timeout, 32 GB of ephemeral storage, and the function-level capacity provider settings including per-environment concurrency, the memory-to-vCPU ratio, and accelerator memory

Figure 3: The function’s configuration, including memory, timeout, and 32 GB of ephemeral storage, and the function-level capacity provider settings: per-environment concurrency, the memory-to-vCPU ratio, and accelerator memory.

When you finish testing, delete the function and then the capacity provider so that Lambda stops the GPU instances and you stop paying for them.

How it works
The capabilities below are what you get out of the box, each one removing GPU work you would otherwise own.

Skip the GPU software setup. Curated base images ship with the frameworks and tools handled for you, so you do not install or reconcile them: base:cuda (CUDA toolkit and runtime), cupy:cuda (CuPy, NumPy, SciPy, Pandas, Numba), pytorch:cuda (PyTorch, torchvision, torchaudio, transformers, FFmpeg), and serving images vllm:cuda and sglang:cuda. Use them directly, extend them, or bring a fully custom image.

No GPU infrastructure to operate. Lambda handles driver compatibility, provisioning, routing, and load balancing, so you ship functions instead of running GPU fleets. Deploy with the same Console, CLI, AWS CloudFormation, AWS CDK, AWS SAM, and Terraform workflow as any Lambda Event Function.

Trigger GPU work from any AWS event. The same 200+ event sources that trigger Event Functions, including Amazon S3, Amazon SQS, Amazon API Gateway, and Amazon EventBridge, trigger GPU-accelerated functions directly, with the same scaling, error handling, and retries. No custom integration code.

Serve concurrent requests on each GPU. Each execution environment can process multiple concurrent invocations on the same GPU, which you control with the per-environment concurrency setting. Raising it packs more requests onto each GPU instance to drive utilization up, so you get more throughput from the capacity you already pay for.

Multiple instance types. Specify multiple instance types or generations, and Lambda selects the most cost-effective available option and falls back across your list to reduce Insufficient Capacity Errors.

Capacity options. GPU instances run as Amazon EC2 On-Demand instances, and your existing Savings Plans and Reserved Instances apply. For predictable GPU availability, create an EC2 On-Demand Capacity Reservation (ODCR) that matches your capacity provider configuration, and Lambda uses that reserved capacity automatically.

Large container images and storage. Container images up to 32 GB are supported, along with up to 32 GB of NVMe ephemeral storage in /tmp. Seekable OCI (SOCI) lazy loading lets your function begin executing before the full image is downloaded, which reduces execution environment startup time by up to 70%.

See GPU usage without extra setup. GPU utilization, GPU memory utilization, GPU memory used, and GPU power utilization appear alongside standard function metrics in Amazon CloudWatch and in the AWS Lambda console.

After invoking the function, the console surfaces the GPU-specific metrics next to the standard ones. Track GPU utilization, GPU memory utilization, GPU memory used, and GPU power utilization to see how much of the accelerator each invocation actually uses, which is the signal that drives both auto-scaling and cost.

Lambda console Monitor tab showing GPU utilization, GPU memory utilization, GPU memory used, and GPU power utilization charts for a GPU inference function under load

Figure 4: GPU utilization, GPU memory utilization, GPU memory used, and GPU power utilization for the vLLM function under concurrent load.

Pricing and availability
This feature is generally available today, supporting the Amazon EC2 G-series (G4dn, G5, G6, G6f, Gr6, Gr6f, G6e) at launch, with more instance families to come. You pay the underlying EC2 instance fee (eligible for Savings Plans and Reserved Instances), plus a 9.75 percent management fee for GPU instances, and the standard Lambda request fee of $0.20 per million requests. For pricing and Region availability, see AWS Lambda pricing.

You can also build with your AI coding assistants and agents: explore the Builder Center and connect your tools with the Agent Toolkit for AWS, which bundles the AWS MCP Server and curated agent skills.

To get started, visit the AWS Lambda console and see the GPU-accelerated functions documentation.

Control your AWS Lambda runtimes with customer-managed runtimes

Post Syndicated from Jonathan Tuliani original https://aws.amazon.com/blogs/compute/control-your-aws-lambda-runtimes-with-customer-managed-runtimes/

With AWS Lambda customer-managed runtimes for Lambda Event Functions (formerly called Lambda functions), you get full control over Lambda runtime contents, updates, access, and lifecycle. You package your runtime once, share it across your organization, and when you update it, Event Functions pick up the change automatically. You can test, schedule, stagger, and monitor the runtime update rollout. If necessary, you can roll back.

In this post, we will explain why you might use a customer-managed runtime, and the core concepts of Lambda runtime management. This includes the runtime publisher and consumer roles, resource model, and update process. We will also cover cross-organization runtime sharing, deletion guardrails, and pricing.

Lambda managed runtimes

Until now, AWS Lambda Event Functions (formerly Lambda functions) ran only on runtimes that Lambda manages. You choose a language, deploy your code, and Lambda takes care of the runtime, including patching and lifecycle management. This model works well, and remains the right choice for many Lambda customers, especially those who are new to serverless.

However, for more advanced customers managing thousands of Event Functions, the Lambda managed runtime can be restrictive. For example, suppose your organization has a standardized security or monitoring extension, enterprise certificates, or even wants to use Lambda with an additional language such as PHP. These components need to be included in each Event Function in an application or organization, in addition to the function code.

With Lambda managed runtimes, you have two options. You can use Lambda layers to distribute shared libraries. These must be deployed with every function, as shown in the diagram:

Boxes-and-arrows diagram showing each Lambda function repeating three components (function code, PHP runtime, and monitoring extension), all connected to a single Lambda runtime that contains only the OS libraries

Figure 1: Using PHP and a monitoring extension with a Lambda managed runtime

Layers follow a pull model, so when you update a layer, you must redeploy every Event Function that uses it to pick up the change. Alternatively, you can use container image packaging to get full control over the runtime contents. But this shifts complexity to every developer on every team. Developers need to understand Dockerfiles, image registries, and container builds, and need to rebuild and redeploy every function to roll out a shared component update. You also lose the simplicity of .zip-based deployment and automatic runtime updates.

How customer-managed runtimes solve this

With customer-managed runtimes you can package your language runtime, certificates, security tools, and monitoring agents into a centrally managed runtime resource, shared by any number of functions.

Boxes-and-arrows diagram showing each Lambda function with a single component, the function code, all connected to one customer-managed runtime that contains the PHP runtime, monitoring extension, and OS libraries

Figure 2: Using PHP and a monitoring extension with a customer-managed runtime

Application developers reference your runtime in their Event Function configuration, the same way they would reference a Lambda-managed runtime like python3.14. They deploy their code as .zip files, use the same AWS Command Line Interface (AWS CLI) and tools, and receive runtime updates automatically.

When you update the runtime, you update it once. Event Functions pick up the new version at their next cold start, with no per-function redeployments. You can stage the rollout across environments, roll out Region by Region, monitor function invocation success rates, and roll back if something goes wrong.

This model supports a range of scenarios:

  • Standardize shared components at scale – Give teams in your organization a runtime with your approved security and monitoring tools built in. Update those tools centrally.
  • Use languages Lambda doesn’t support – Package languages or runtimes such as PHP, Bun, R, or any other language into a customer-managed runtime. Developers use it with the same .zip deployment experience as Python or Node.js.
  • Control your patching cadence – Apply runtime patches on your schedule, immediately for critical issues or during planned maintenance windows for routine updates. You can also stage the updates, for example across development, test, and production environments.
  • Extend runtime lifetime – If Lambda deprecates a managed runtime before your organization is ready to migrate, fork it into a customer-managed runtime. Now you can apply your own security patches and deprecate on your own timeline.

Publishers and consumers

Customer-managed runtimes introduce two roles: runtime publisher and runtime consumer.

The runtime publisher owns the runtime. That includes its contents, updates, access control, and lifecycle. The publisher builds runtime images, publishes versions, rolls out updates, and decides who can use the runtime. In an enterprise, this could be a central cloud platform team. Alternatively, an application team could operate an application-specific runtime built on base images from their platform team, or from Lambda.

The runtime consumer is the function developer. Consumers reference the runtime in their Event Function configuration, deploy their code as .zip files, and receive updates automatically. They don’t use or manage the underlying container images. They only write application code.

This separation creates a clean boundary. The runtime publisher focuses on runtime management: patching, security tooling, and compliance. Developers consume the runtime and focus on their business logic.

Resource model

Customer-managed runtimes use three resource types that work together.

Runtime: The top-level resource representing the runtime as a whole, for example, a PHP 8 runtime for your organization. A runtime has a name, an Amazon Resource Name (ARN), and a description. You control access at the runtime level using a resource-based policy. To create a runtime:

aws lambda-core create-runtime \
    --name my-runtime \
    --description "Describe or link to runtime description" \
    --license-info "None"

Runtime version: Represents the contents of the runtime at a point in time. Each version is backed by a container image in Amazon Elastic Container Registry (Amazon ECR) and is immutable, so once created it can’t be changed. To update the runtime, you create a new version. To create a runtime version, reference the ECR image that defines the runtime contents:

aws lambda-core create-runtime-version \
    --runtime-name my-runtime \
    --name v1 \
    --image-uri 111122223333.dkr.ecr.us-east-1.amazonaws.com/my-runtime:v1

Runtime images contain the operating system libraries, language support, a bootstrap script, and the runtime interface client (code that retrieves invoke requests from the Lambda service and calls your function handler). You must grant the Lambda service principal read access to your ECR repository. For details, refer to the runtime image building documentation.

Runtime alias: A named pointer to a runtime version. Event Functions consume the runtime through an alias. When you update an alias to point to a new version, functions using that alias pick up the change at their next cold start. To create a runtime alias:

aws lambda-core create-runtime-alias \
    --runtime-name my-runtime \
    --name production \
    --runtime-version v1

How you structure your aliases depends on your release process, for example, separate aliases per environment (dev, test, prod), per release track (latest, stable), or semantic version (php8.3, php8.4). Refer to alias strategies in the documentation for common patterns.

Runtimes are Regional resources. You must create a runtime, its versions, and its aliases in each AWS Region where you need them. We recommend using consistent names across Regions so that ARNs differ only in the Region component. Use ECR cross-Region replication to distribute your images, and roll out alias updates one Region at a time to limit the impact of a faulty version.

Consuming a runtime

For function developers, the only change is how you specify the runtime source. In the Lambda console, specify whether the runtime is in the function’s account or shared from a different account, and provide the runtime alias ARN:

AWS Lambda console Create Event Function page with a red box highlighting the runtime selection, where the ‘Your runtimes’ option is chosen instead of ‘AWS-managed runtimes’ and a customer-managed runtime alias ARN is entered

Figure 3: The Lambda console Create Event Function page with customer-managed runtime selection

In the AWS CLI (and similarly in AWS CloudFormation), instead of specifying a Lambda runtime identifier like python3.14, you set the runtime to custom and provide the runtime ARN and alias name:

aws lambda create-function \
    --function-name my-function \
    --runtime custom \
    --runtime-config RuntimeArn=arn:aws:lambda:us-east-1:111122223333:runtime/my-runtime,RuntimeAlias=production \
    --handler index.handler \
    --zip-file fileb://function.zip \
    --role arn:aws:iam::111122223333:role/my-lambda-role

Everything else works the same, including function configuration, invocation, logging, monitoring, layers, and infrastructure-as-code tools. Developers deploy .zip files, use the same CLI, and don’t need to learn containers or new tooling.

Runtime updates and monitoring

As a runtime publisher, you own the update process. Lambda doesn’t patch customer-managed runtimes for you. If you build your runtime from a Lambda base image, you get the operating system, language runtime, and Lambda runtime interface client as a starting point. AWS regularly updates the base images with security patches. You can also build your runtime image from scratch for maximum control.

To patch your runtime, first rebuild your runtime image from the updated base image. You then publish a new runtime version referencing the new image, test it, and roll out the new version by updating your runtime aliases. To create a new runtime version and update an alias:

aws lambda-core create-runtime-version \
    --runtime-name my-runtime \
    --name v2 \
    --image-uri 111122223333.dkr.ecr.us-east-1.amazonaws.com/my-runtime:v2

aws lambda-core update-runtime-alias \
    --runtime-name my-runtime \
    --name production \
    --runtime-version v2

Lambda publishes two Amazon CloudWatch metrics in the runtime publisher’s account: RuntimeInvocations (total invocations of functions using the runtime) and RuntimeInvocationErrors (invocations that result in errors). You can view these by runtime, runtime version, or runtime alias.

Your runtime updates need to be backward-compatible with existing functions. Lambda strives to provide backward-compatible updates to its base images, which you can use as your starting point. However, as with any change, there’s always the possibility of an unexpected compatibility issue. During a rollout, you can compare the error rate of the new runtime version against the previous version. If the new version shows a higher error rate under similar traffic, it’s a signal to pause or roll back by re-pointing the alias to the previous runtime version. You can also track rollout progress as Lambda replaces execution environments, shifting invocations from the old version to the new one. We recommend creating a CloudWatch alarm on the error rate of each alias and configuring your deployment pipeline to halt when an alarm fires.

Cross-account sharing and trust

For customer-managed runtimes, we expect most usage to be cross-account: the runtime publisher shares a runtime with runtime consumer accounts by applying a resource-based policy on the runtime. You can share with individual AWS accounts, an AWS Organizations organization or organizational unit, or publicly. Consumers in shared accounts also need an identity-based policy granting lambda:AssociateRuntimeAlias permission. Both the resource-based and identity-based policies must allow the action for cross-account access to work. To allow consumers to use runtime management controls to roll back a function to a specific runtime version, they also need lambda:AssociateRuntimeVersion permission. For details and example policies, refer to Sharing and controlling access to customer-managed runtimes.

A runtime publisher can push code into the execution environments of every function that uses their runtime. This is by design. It’s how runtime updates work. The runtime publisher can also ship updates that break your functions, or delete the runtime causing your functions to fail. This means you must trust the runtime publisher the same way you would trust anyone managing your application or running code with your permissions.

Organization administrators can use service control policies (SCPs) to govern which runtimes are allowed in their organization. For example, allowing only runtimes from specific trusted accounts, or blocking all external runtimes entirely. To consume a third-party runtime, you may wish to retain control by using their container images to build a customer-managed runtime that you manage. The image-centric model means you can use standard container tooling for vulnerability scanning, compliance checks, and supply chain security. These are the same tools you already use for your other container workloads.

Deletion guardrails

Deleting a runtime resource can break many functions, including functions in other accounts. Because of this, Lambda enforces built-in guardrails to help prevent and recover from accidental deletion:

  • Deletion isn’t immediate. Lambda schedules the runtime, version, or alias for deletion with a waiting period you choose, from 7–30 days (default 30). During this period, you can restore the resource.
  • You can’t delete a runtime version while an alias points to it.
  • You can’t delete a runtime while it has versions or aliases that aren’t scheduled for deletion. You must delete aliases first, then versions, then the runtime.

When a runtime alias or version is deleted (or scheduled for deletion), functions that use it enter the Inactive state and invocations fail on cold start. If you restore the resource during the waiting period, functions recover automatically, with no redeployment needed.

Before deleting any runtime resource, check the RuntimeInvocations metric to verify usage. You can monitor runtime metrics during the scheduled for deletion window to check whether the pending deletion is causing function invocations to fail.

To manage the runtime lifecycle, you can set a release lifecycle stage (Preview, GenerallyAvailable, or Deprecated) and optionally block new function creation or function updates after a specified date. Refer to runtime lifecycle management in the documentation for details.

Pricing

There’s no additional charge for customer-managed runtimes. Event Functions that use a customer-managed runtime cost the same as functions that use a Lambda-managed runtime. There’s no charge for creating runtime versions or aliases. However, runtime publishers must keep the container image for each runtime version in Amazon ECR for as long as the version exists. Standard Amazon ECR storage pricing applies to these images.

Conclusion

With customer-managed runtimes, platform teams have central control over the Lambda runtimes used across their organization. As runtime publishers, they control the runtime contents, updates, access, and lifecycle. Alternatively, they can publish base images that application teams use to build and manage their own runtimes. Developers keep the .zip deployment experience they’re familiar with and receive runtime updates automatically.

To get started, visit the customer-managed runtimes documentation and the step-by-step tutorial. Customer-managed runtimes are available today across commercial AWS Regions through the Lambda console, AWS Command Line Interface, and AWS CloudFormation.

We would love to hear how you use customer-managed runtimes. Share your feedback in the comments, in the Lambda public roadmap, or reach out through AWS re:Post.


About the author

Jonathan Tuliani

Jonathan Tuliani

Jonathan is a Principal Product Manager for AWS Lambda in Amazon Web Services, where he leads product strategy for runtimes and programming models. He is passionate about serverless computing, having previously delivered systems on cloud, virtualized, and bare-metal infrastructure.

Block DNS threats with Infoblox rules in Amazon Route 53 Resolver DNS Firewall

Post Syndicated from Rajendra Kulkarni original https://aws.amazon.com/blogs/architecture/block-dns-threats-with-infoblox-rules-in-amazon-route-53-resolver-dns-firewall/

Blocking DNS threats at the lookup stage helps you interrupt malware delivery, command-and-control channels, and data exfiltration. Attackers use domain names to reach your network and to move data out of it. With Amazon Route 53 Resolver DNS Firewall (DNS Firewall), you can already filter outbound DNS queries from your Amazon Virtual Private Cloud (Amazon VPC) resources, but keeping domain lists current takes ongoing effort.

Infoblox Threat Defense is now available in preview in DNS Firewall, providing partner-managed DNS threat intelligence directly in your rule groups. You subscribe in AWS Marketplace from the DNS Firewall rule workflow, and Infoblox maintains the threat data for you.

In this post, we show you how to add an Infoblox managed rule to a DNS Firewall rule group, test it in alert mode, and then move to blocking. We also cover how to monitor matches and how to clean up resources if you are evaluating the solution.

Solution overview

Figure 1 shows the architecture of the solution. Workloads, such as Amazon Elastic Compute Cloud (Amazon EC2) instances, in your VPC send DNS queries to Amazon Route 53 Resolver. Route 53 Resolver passes each outbound query to DNS Firewall for inspection. DNS Firewall evaluates the query against your rule group, which includes the Infoblox managed rule. DNS Firewall matches are recorded in the Resolver query logs, which you deliver to Amazon CloudWatch Logs. Outside your VPC, Infoblox supplies threat intelligence to the managed rule, and AWS Marketplace supplies the managed rules to the rule group.

Architecture diagram. Inside an Amazon VPC, Amazon EC2 workloads send DNS queries to Amazon Route 53 Resolver. Route 53 Resolver sends each query for inspection to Route 53 DNS Firewall. DNS Firewall evaluates the query against a DNS Firewall rule group that contains the Infoblox managed rule, which is set to ALERT and later BLOCK. DNS Firewall matches are recorded in query logs that are delivered to Amazon CloudWatch Logs, which sits outside the VPC. Also outside the VPC, Infoblox sends threat intelligence to the Infoblox managed rule, and AWS Marketplace supplies the managed rules to the rule group.

Figure 1: Architecture of the solution

The solution has six components:

  • Workloads in your Amazon VPC send DNS queries to Route 53 Resolver.
  • Route 53 Resolver passes each outbound query to DNS Firewall.
  • A DNS Firewall rule group that you associate with your VPC holds your rules, including the Infoblox managed rule.
  • Infoblox threat intelligence supplies the domain categories that the managed rule matches against. Infoblox updates this data automatically, so you do not maintain feeds or domain lists.
  • AWS Marketplace handles your subscription. DNS Firewall generates metering records for the rule groups you subscribe to, and the charges appear on your AWS bill.
  • CloudWatch Logs stores the Route 53 Resolver query logs that you use to review matches.

Subscription and billing through AWS Marketplace

You discover, subscribe to, and manage the Infoblox protections in the same DNS Firewall workflow you already use. You can manage rule groups with the AWS Management Console, the AWS Command Line Interface (AWS CLI), or the AWS SDKs. Because metering is built in, you do not need a separate billing system with Infoblox. Usage appears alongside your other AWS costs, so cloud, security, procurement, and finance teams can work from one purchasing and reporting model.

Solution walkthrough

Prerequisites

For this walkthrough, you need the following:

  • An AWS account with AWS Identity and Access Management (IAM) permissions for the actions listed in the next section.
  • An Amazon VPC with workloads that use Route 53 Resolver.
  • A DNS Firewall rule group, or permission to create one.

The Infoblox managed rule requires the DNS Firewall Advanced pricing option and a subscription through AWS Marketplace. For details, see Cost considerations later in this post.

Required IAM permissions

Your IAM role or user needs the following actions. Use least-privilege permissions in production and scope resources where the service supports it. For the full list of actions, see Actions, resources, and condition keys for Amazon Route 53 Resolver in the Service Authorization Reference.

  • DNS Firewall rule groups and rules: route53resolver:CreateFirewallRuleGroup, route53resolver:GetFirewallRuleGroup, route53resolver:ListFirewallRuleGroups, route53resolver:DeleteFirewallRuleGroup, route53resolver:CreateFirewallRule, route53resolver:UpdateFirewallRule, route53resolver:ListFirewallRules, route53resolver:DeleteFirewallRule.
  • Domain lists for the allow list: route53resolver:CreateFirewallDomainList, route53resolver:UpdateFirewallDomains, route53resolver:ListFirewallDomains, route53resolver:GetFirewallDomainList, route53resolver:ListFirewallDomainLists, route53resolver:DeleteFirewallDomainList.
  • VPC association and fail-open setting: route53resolver:AssociateFirewallRuleGroup, route53resolver:DisassociateFirewallRuleGroup, route53resolver:GetFirewallRuleGroupAssociation, route53resolver:ListFirewallRuleGroupAssociations, route53resolver:GetFirewallConfig, route53resolver:ListFirewallConfigs, route53resolver:UpdateFirewallConfig, ec2:DescribeVpcs.
  • Query logging configuration: route53resolver:CreateResolverQueryLogConfig, route53resolver:GetResolverQueryLogConfig, route53resolver:ListResolverQueryLogConfigs, route53resolver:AssociateResolverQueryLogConfig, route53resolver:GetResolverQueryLogConfigAssociation, route53resolver:ListResolverQueryLogConfigAssociations, route53resolver:DisassociateResolverQueryLogConfig, route53resolver:DeleteResolverQueryLogConfig.
  • CloudWatch Logs log delivery (if you choose a log group as the destination): logs:CreateLogGroup, logs:DescribeLogGroups, logs:CreateLogDelivery, logs:GetLogDelivery, logs:UpdateLogDelivery, logs:DeleteLogDelivery, logs:ListLogDeliveries, logs:PutResourcePolicy, logs:DescribeResourcePolicies.
  • AWS Marketplace subscription: aws-marketplace:ViewSubscriptions, aws-marketplace:Subscribe, aws-marketplace:Unsubscribe.

If you send query logs to an Amazon Simple Storage Service (Amazon S3) bucket or an Amazon Data Firehose delivery stream instead, you need the corresponding permissions for that destination.

Cost considerations

This solution has three cost components. For current rates, see Amazon Route 53 pricing.

  • DNS Firewall Advanced: You pay an hourly charge for each rule group that contains Advanced rules, for each VPC that the rule group is associated with. If you also add a custom domain list for exceptions, DNS Firewall charges for the queries it inspects against that list and for each domain it stores.
  • AWS Marketplace fee: The Infoblox subscription in AWS Marketplace is available at no cost during preview. The offer on the Infoblox listing in AWS Marketplace shows the pricing and terms, and the charge appears on your AWS bill.
  • Query logging: Route 53 does not charge for Resolver query logs. You pay for the destination that you choose, which is Amazon CloudWatch Logs, Amazon S3, or Amazon Data Firehose.

Add the Infoblox managed rule

To add the managed rule, complete the following steps:

  1. Open the Amazon VPC console. In the navigation pane, under DNS Firewall, choose Rule groups.
  2. Choose your rule group, then choose Add rule.
  3. Under Rule details, enter a Name and select the Advanced pricing option.
  4. Under Rule configurations, for Rule type, choose Partner managed DNS threat protection. For Vendor, choose Infoblox.
  5. If you are not yet subscribed, choose View subscription options, review the pricing and terms, and choose Subscribe. When you subscribe, you authorize AWS to share DNS query metadata with Infoblox, as described after these steps. The form updates when the subscription is active.
  6. For DNS security categories, choose the threat feeds for this rule. Infoblox organizes protections into risk-based domain lists (Critical, High, Medium, Low, and Informational). You can start in detect-only mode and later move to blocking, beginning with the Critical and High risk categories.
  7. For the action, choose ALERT so you can review matches before you block anything.
  8. Choose Add rule.

Figure 2 shows the Add rule page with the Advanced tier and the Partner managed DNS rule type selected. Infoblox is selected as the vendor, and a banner confirms that the subscription succeeded. The DNS security categories list shows five Infoblox categories: Informational, Low Risk, Medium Risk, High Risk, and Critical Risk.

Screenshot of the Add rule page in the Amazon VPC console. The Advanced tier is selected. Under Rule type, Partner managed DNS is selected. Under Vendor, Infoblox is selected. A banner reads Successfully subscribed to Infoblox. The DNS security categories drop-down list is open and shows five unselected options: Infoblox Informational, Low Risk, Medium Risk, High Risk, and Critical Risk.

Figure 2: The Add rule page with the Infoblox rule type and DNS security categories

Data shared with Infoblox. When you subscribe, you authorize AWS to share DNS query metadata with Infoblox. This metadata is the domain names that an Infoblox rule checks, and it is anonymized, as it is with the Palo Alto Networks partner managed rule. For the terms that apply, see the Infoblox listing in AWS Marketplace and review them before you subscribe.

Associate the rule group with VPCs

A rule group only takes effect on VPCs you associate with it. To associate the rule group, complete the following steps:

  1. On the Rule groups page, choose your rule group, then choose View details.
  2. On the Associated VPCs tab, choose Associate VPC.
  3. Select one or more VPCs, then choose Associate.
  4. Wait for the association Status to change from Updating to Complete.

You can expand protection later by associating additional VPCs with the same rule group.

Fail-open and fail-closed behavior. By default, the firewall configuration for a VPC fails closed. If DNS Firewall does not respond, Route 53 Resolver blocks the query and returns a SERVFAIL response, so a DNS Firewall issue can interrupt name resolution for your workloads. To favor availability over security, enable FirewallFailOpen for the VPC by editing its DNS Firewall configuration in the Route 53 Resolver console or by calling UpdateFirewallConfig. For more information, see DNS Firewall VPC configuration in the Amazon Route 53 Developer Guide.

Turn on query logging

Monitoring depends on Route 53 Resolver query logs, so turn on query logging for your VPC before you test in alert mode. To configure query logging, complete the following steps:

  1. Open the Route 53 console. In the navigation pane, under Resolver, choose Query logging.
  2. Choose the AWS Region of your VPC, then choose Configure query logging.
  3. Enter a Query logging configuration name. For Query logs destination, choose a CloudWatch Logs log group, an Amazon S3 bucket, or an Amazon Data Firehose delivery stream. Create a new destination or choose an existing one in the same Region.
  4. Under VPCs to log queries for, select the VPCs that you associated with the rule group.
  5. Choose Configure query logging.

Query logs usually start to appear within a few minutes. Route 53 Resolver logs only unique queries, so queries that it answers from its cache do not create new entries. The firewall fields in each log entry, such as firewall_rule_action and firewall_rule_group_id, are populated only when a query matches a rule whose action is ALERT or BLOCK. For the full list of fields, see Values that appear in VPC Resolver query logs. For more information about configuring logging, see Managing Resolver query logging configurations.

Monitor matches and start blocking

Route 53 Resolver sends query logs to the destination that you chose: a CloudWatch Logs log group, an Amazon S3 bucket, or an Amazon Data Firehose delivery stream. From there, you can route the logs to your security information and event management (SIEM) or security orchestration, automation, and response (SOAR) tools.

Review the alerts for a period that matches your workload patterns. Investigate each match. For domains that you approve, add an exception by following the steps in this section.

DNS Firewall does not support the ALLOW action on Advanced rules. Instead, create a custom domain list that contains the approved domains, and add a rule with the ALLOW action at a lower priority number than the Infoblox rule. DNS Firewall evaluates rules from the lowest priority number to the highest and stops at the first match, so the ALLOW rule takes effect before the Infoblox rule. For more information, see Rule actions in DNS Firewall.

To add an exception for an approved domain, complete the following steps:

  1. In the Amazon VPC console, under DNS Firewall, choose Domain lists, then choose Add domain list.
  2. Enter a name, add the domains that you approve, and choose Add domain list.
  3. Under Rule groups, choose the rule group that contains the Infoblox rule, then choose Add rule.
  4. Enter a Name and select the Foundational pricing option. The ALLOW action is not available with the Advanced option.
  5. For Rule type, choose Custom domain list, and then choose the domain list that you created.
  6. For the action, choose ALLOW.
  7. Set the rule priority to a number lower than the priority of the Infoblox rule. For example, if the Infoblox rule has priority 100, use 10.
  8. Choose Add rule.

When the results look right, edit the Infoblox rule and change the action to BLOCK.

Clean up resources

If you are running an evaluation, remove the resources when you finish testing to avoid incurring future costs:

  1. Disassociate the VPCs from the rule group.
  2. Delete the Infoblox rule, and delete the rule group if you created it for this test.
  3. Delete the ALLOW rule and the custom domain list if you created them for this test.
  4. Delete the query logging configuration and the log destination if you created them for this test.
  5. Cancel your subscription in AWS Marketplace.

Conclusion

With Infoblox managed rules in DNS Firewall, you add curated DNS threat intelligence to the controls you already run, and you manage it with the same tools, access controls, and AWS bill. In this post, we showed you how to subscribe, add the managed rule, test in alert mode, and move to blocking.

To get started, open the Amazon VPC console and add a partner managed rule to a DNS Firewall rule group. To learn more, see the Amazon Route 53 Resolver DNS Firewall detail page and How Resolver DNS Firewall works in the Amazon Route 53 Developer Guide. For details about the Infoblox offer, see the Infoblox listing in AWS Marketplace. For Infoblox-specific configuration details, see Infoblox managed DNS threat protection in DNS Firewall.

If you want help applying a similar approach in your environment, contact an AWS representative.

 


About the authors

Rajendra Kulkarni

Rajendra Kulkarni

Rajendra is a Senior Partner Solutions Architect for Security at AWS, with more than 20 years of experience in information security. That experience spans cloud security, data security, and generative AI security, including Amazon Bedrock, Amazon Q, Model Context Protocol (MCP), and agentic AI. Rajendra also has a background in compliance, including SOC 2, FedRAMP, and risk assessments and audits based on ISO 27001, SOX, and PCI DSS.

Bryan Moffatt

Bryan Moffatt

Bryan is a Senior Product Manager-Technical with Amazon Route 53 at AWS. He works with engineering and AWS partners to help customers secure and manage DNS across their AWS environments. Bryan leads Route 53 Profiles, Private DNS, and DNS Firewall.

Manish Patel

Manish Patel

Manish has more than 20 years of experience shaping the cybersecurity, cloud, and AI landscapes. Having driven product strategy, security integrations, and global alliances at industry leaders like Infoblox, CrowdStrike, Trend Micro, and Zscaler, he brings technical expertise and go-to-market execution spanning endpoint security, network defense, Zero Trust architecture, and hybrid and public cloud environments. He is particularly focused on bridging the gap between security and emerging technologies, including pioneering early enterprise co-builds through partnerships.

Larry Im

Larry Im

Larry is a Senior Solutions Architect enabling hyper-growth SaaS ISVs to innovate, design, secure, and scale their platforms on AWS. He partners with customers to build highly scalable and resilient cloud architectures and is an active builder in the generative AI space, developing agentic AI tools and workflows that help customers and field teams move faster.

Introducing the Apache Spark optimization agent for Amazon EMR Serverless and AWS Glue ETL

Post Syndicated from Neil Mukerje original https://aws.amazon.com/blogs/big-data/introducing-the-apache-spark-optimization-agent-for-amazon-emr-serverless-and-aws-glue-etl/

With Amazon EMR Serverless and AWS Glue ETL, you can run Apache Spark applications without provisioning or managing clusters. You submit jobs, the service allocates the compute, scales it during execution, and releases it when the job finishes. Both services deliver a balanced performance profile by default. However, because of different datasets and transformations, customers who want to push further on cost or performance still need to tune Spark settings. Investigating why a specific job is slow or expensive often requires deep Spark expertise: analyzing Spark History Server timelines, shuffle metrics, executor sizes, and task distributions. That work falls to the few Spark experts on the team, and their time is often the bottleneck.

Today we are announcing the general availability of the Apache Spark optimization agent for Amazon EMR Serverless and AWS Glue ETL. The agent analyzes completed Spark job runs and delivers optimization recommendations in minutes, replacing hours of manual analysis by Spark experts. Any engineer can select a cost or performance goal and receive specific configuration changes grounded in evidence from the job’s own Spark telemetry. The agent supports single job-run analysis as well as comparison against a known-good baseline job run.

The Apache Spark optimization agent is available at no additional charge.

In this post, we explain what the agent does, how it works, and how to use it.

What the Apache Spark optimization agent does

The optimization agent analyzes Spark jobs and recommends changes that reduce cost, improve performance, or both. You can access the agent from the EMR Studio UI, AWS Glue Studio UI, or through the Amazon SageMaker Unified Studio MCP Server using any MCP-compatible client such as Kiro. You point it at a completed job run, choose either cost or performance as the intent, and receive recommendations that cite the specific metrics from that run. Often tuning for faster performance also lowers resource usage and cost, but in some cases a faster job requires more resources, which increases cost. The agent optimizes for the goal you choose, cost or performance, and makes sure the one you did not pick does not get noticeably worse. For example, a cost recommendation can make a job run slightly longer, but no more than the normal variation between runs. For larger and more expensive jobs, the agent tightens the threshold further.

There are two ways to analyze a Spark job:

  1. Single job-run analysis. The agent examines one completed run and identifies common sources of inefficiency: data skew, memory pressure, excessive shuffle and disk spill, undersized or oversized workers, suboptimal join strategies, and input layout issues such as small files. Each recommendation shows the Spark properties to change, the current and proposed values, and the telemetry evidence behind the suggestion.
  2. Baseline comparison. When a job that used to meet its targets starts running longer or costing more, compare it against a run that performed well. Provide the current run and the earlier baseline, and the agent compares their configuration, metrics, and stage behavior to pinpoint what changed.

The agent also evaluates a best practices checklist from Top 10 best practices for EMR Serverless, Best practices for performance tuning AWS Glue, and Improving AWS Glue performance. It recommends known platform-level improvements such as upgrading to a newer Spark version, using AWS Graviton processors, and applying best practices for data formats like Apache Iceberg.

The agent is read-only. It does not change your code or job settings. You decide which recommendations to apply.

How the Apache Spark optimization agent works

The following diagram shows how a request flows from the AWS console or your MCP-compatible client to the remote MCP server, through feature extraction and the recommendation engine, and back to you as recommendations.

Request flow from the AWS console or MCP client through the remote MCP server, feature extraction, and the recommendation engine, returning recommendations

Figure 1: How a request flows from the console or MCP client through the recommendation engine and back as recommendations

The workflow consists of the following steps:

  1. State your intent in plain language, such as performance or cost for a completed job run.
  2. Your MCP client or the AWS console sends the job run to the remote MCP server.
  3. The agent reads the run’s Spark History Server telemetry, configuration, logs, and cost through existing APIs, over TLS-encrypted connections, and uses them for feature extraction and context building.
  4. A recommendation engine combines rule-based investigations, intent-based deterministic models, and a knowledge base to find the bottleneck and determine the fix.
  5. You get back labeled recommendations, each with the evidence behind it.

The agent approaches each request with the objective to optimize either performance or cost. It then uses read-only access through AWS APIs and the Persistent Spark History Server or AWS Glue Apache Spark Web UI to gather the Spark configuration and telemetry. Additionally, the configuration inspector collects the job’s settings and compares them against a baseline run when one is provided.

The investigation and recommendation engine looks at these artifacts together to find what is driving runtime and cost. A slow stage may stem from too little parallelism, a skewed join key, memory pressure that forces spill, or a slow upstream read. High cost might come from idle executors or capacity well beyond what the job uses.

Rule-based investigations and an intent-based deterministic model calculate the recommended values. An AI model combines the findings with a knowledge base of the settings most often tuned across millions of Spark jobs on AWS. The agent only recommends changing a setting when the evidence supports it. When cost and runtime trade off against each other, the agent optimizes for the metric you choose and keeps any impact on the other within defined limits.

Note: The agent does not use customer data to train or build the knowledge base.

The Spark optimization agent includes built-in guardrails for personally identifiable information (PII), sensitive data, security, and cost thresholds to make sure recommendations are safe.

Each recommendation is labeled with what it changes:

  • [infra]: the compute resources your job runs on, such as the EMR Serverless application’s pre-initialized and maximum capacity, the worker vCPU and memory size, or the AWS Glue worker type and number of workers.
  • [config]: Spark configuration, such as spark.sql.shuffle.partitions, spark.executor.memory, or an Adaptive Query Execution (AQE) setting.
  • [data]: a change to the underlying data’s physical layout, such as repartitioning a table on a different key or compacting small files.

Each category needs a different level of review. A [config] change can typically be validated in the next run without any code change. A [data] change modifies the job’s actual behavior, or the data it depends on, and should go through the same review and testing discipline as any other production change before it ships.

How to use the Apache Spark optimization agent

You can run the optimization agent from the AWS console or from any MCP-compatible client, such as Kiro, Claude Code, or Codex, through the analyze_spark_workload tool on the Amazon SageMaker Unified Studio remote MCP server. From an MCP client, ask in plain language, and words like “faster” or “cheaper” set the goal. For setup steps, see Use Spark Optimization Agent.

The following steps show how to use the agent in the AWS console.

EMR Serverless

  1. In EMR Studio, select your Application, and choose the Batch job that you want to optimize.
  2. Choose Analyze with AI.
EMR Studio batch job details page with the Analyze with AI option

Figure 2: Choosing Analyze with AI for a batch job in EMR Studio

  1. You can select to optimize for Performance or Cost. If you have a previous job run that was faster, you can also choose to Compare with a baseline job. Then, choose View Recommendations.
  2. Review the recommendations in the AI Analysis tab and apply them to the next run.
AI Analysis tab in EMR Studio showing the agent’s recommendations for the selected job run

Figure 3: AI Analysis tab in EMR Studio showing the agent’s recommendations

AWS Glue

  1. Go to the AWS Glue console.
  2. Under ETL jobs, choose the AWS Glue ETL job that you want to optimize.
  3. Choose the Runs tab, select the succeeded job run and choose Analyze with AI.
AWS Glue console Runs tab with a succeeded job run selected and the Analyze with AI option

Figure 4: Selecting a succeeded run on the AWS Glue console Runs tab and choosing Analyze with AI

  1. You can select to optimize for Performance or Cost. If you have a previous job run that was faster, you can also choose to Compare with a baseline job.
  2. Once the AI Analysis has completed, you can view the recommendations, apply the changes, and perform the next run.
AI Analysis tab in the AWS Glue console showing the agent’s recommendations

Figure 5: Reviewing the agent’s recommendations in the AI Analysis tab on the AWS Glue console

Use cases

The agent works across many situations. The following table shows sample prompts for each goal. In an MCP-compatible client, include the job run ID, and for a comparison, the baseline run ID.

Goal Sample prompts
Performance “My job is slow. How do I make this job faster?”
Cost “My bill is too high.” / “Reduce spend without impacting reliability.”
Baseline comparison “Why is my job running slowly today?” / “My job used to finish in 10 minutes but now it takes an hour.”

The following three use cases are common situations that data teams run into. Each one describes a scenario, the Spark issues that the agent looks for, and what you get back. They apply to both Amazon EMR Serverless and AWS Glue ETL.

My job is missing its SLA. How do I make it finish sooner?

A nightly orders pipeline that feeds an 8 AM dashboard takes longer as time goes on, and adding more compute power is not always a good practice. You ask the agent to optimize the run for performance. It identifies the bottleneck and then recommends the exact settings to change for that stage so the job finishes sooner.

How can I make this job cheaper?

The bill keeps rising, but every job finishes on time, so the jobs rarely get reviewed for optimization. You ask the agent to optimize the run for cost without significantly affecting the runtime. It compares the executors a job held with what its stages kept busy, exposing over-provisioning, such as a minimum executor count set too high or dynamic allocation left uncapped. It then sizes capacity to actual use. Before you apply these changes, it shows the runtime trade-off between cost and performance. For example, reducing the number of executors can improve resource utilization and lower cost but can also increase the job’s runtime.

Why is this run slower than my baseline run?

A job now takes several times as long on the same datasets compared to previous runs. This is a baseline comparison scenario. You give the agent the slow run and an earlier run that finished on time. Instead of tuning the slow run in isolation, the agent compares the two runs side by side, covering their configuration, metrics, and stage behavior. It isolates the differences that explain the regression, and tells you which settings to restore to get back to baseline performance.

Optimization results

The agent tunes every recommendation to the specified goal and checks to confirm it does not regress the other dimension beyond tolerance.

We tested the Apache Spark optimization agent across hundreds of workloads on Amazon EMR Serverless and AWS Glue ETL. The tests included industry benchmarks (derived from TPC-DS and TPC-H) at various scale factors, along with customer-representative workloads shared by enterprise AWS Glue and Amazon EMR customers.

The evaluation set is made up of Spark workloads that follow common patterns from multiple different industries such as ecommerce, industrial telemetry, manufacturing, and more. Each workload copies the structure of a typical production job, including its join strategies, shuffle sizes, and skew, so the agent’s recommendations can be checked against realistic performance. Together, the workloads cover most production ETL patterns: ingestion, multi-way joins, upserts, slowly changing dimensions, rollups, and full query benchmarks. They run on several open table formats and on standard columnar storage.

The following table shows the ranges of cost improvement observed when invoking the agent with the cost intent and the performance improvement observed with the performance intent. Across hundreds of workloads, the agent reduced cost by 24-31% with the cost intent and improved performance by 23-49% with the performance intent.

Workload Cost improvement Performance improvement
Aggregate (across 100+ workloads) 24–31% 23–49%
TPC-DS 3 TB 30–78% 32–44%
TPC-H 3 TB 10–64% 19–33%

The ranges in the table reflect testing across different versions of Amazon EMR Serverless and AWS Glue ETL.

Note: The cost or performance improvement you see depends on your workload, its current configuration, and the version of Amazon EMR Serverless or AWS Glue ETL you are running.

Conclusion

In this post, we introduced the Apache Spark optimization agent for Amazon EMR Serverless and AWS Glue ETL. We showed how the agent analyzes successful Spark runs and recommends changes that reduce cost and improve runtime, how it explains why a run regressed against earlier faster runs, and how each recommendation points back to the measurement behind it. We also walked through how the agent works and different ways to use it.

If a job run fails, the Apache Spark troubleshooting agent under the same MCP endpoint analyzes the run’s logs and Spark event data, identifies the root cause, and explains it in plain language.

To get started, pick a job that you run often or that you want to optimize, and ask the agent how to optimize it for cost or performance. Validate the recommendations in a test run before you apply them in production. If you already use the Apache Spark troubleshooting agent, you can start right away because both agents use the same MCP server.


About the authors

Neil Mukerje

Neil Mukerje

Neil is a Principal Product Manager at Amazon Web Services. He is driven to build experiences that let customers achieve their goals efficiently. In his spare time, he enjoys reading, hiking, and tinkering with technology.

David Zhang

David Zhang

David is a Senior Specialist Solutions Architect specializing in Data & AI at AWS. He focuses on designing and implementing open lakehouse architectures and agentic AI solutions. He is an active speaker at AWS events and contributes to technical publications and open-source initiatives.

Vishal Kajjam

Vishal Kajjam

Vishal is a Senior Software Development Engineer at AWS Analytics. He is passionate about distributed computing and using ML/AI for designing and building end-to-end solutions to address customers’ data integration needs. In his spare time, he enjoys spending time with family and friends.

Layth Yassin

Layth Yassin

Layth is a Software Development Engineer at AWS Analytics. He’s passionate about building distributed systems and generative AI solutions for data integration problems. Outside of work, he enjoys playing/watching basketball, and spending time with friends and family.

Jake Gordon

Jake Gordon

Jake is a Software Development Engineer in AWS Analytics. He is passionate about solving hard, customer-facing problems where distributed systems meet agentic AI. Outside of work, he enjoys playing guitar, running, and spending time with family and friends.

Martin Ma

Martin Ma

Martin is a Software Development Engineer at AWS Analytics. He is passionate about agentic AI, especially building agents that customers can trust: grounded in real data, rigorously evaluated, and reliable at scale. In his free time, he enjoys singing and playing guitar.

Pranjal Srivastava

Pranjal Srivastava

Pranjal is a Software Development Engineer at AWS Analytics. He enjoys working at the intersection of AI, machine learning, and distributed systems to turn open-ended problems into practical, scalable solutions. Beyond work, he enjoys playing chess and is an avid reader and cinephile.

Vidyashankar Sivakumar

Vidyashankar Sivakumar

Vidyashankar is an Applied Scientist at Amazon Web Services (AWS), where he works on machine learning for systems, agentic AI, and their applications to solutions within AWS. In his spare time, he enjoys reading, listening to podcasts on current affairs, AI/ML and following cricket.

Jeremy Samuel

Jeremy Samuel

Jeremy is a Software Development Engineer at AWS Analytics. He has a strong interest in creating distributed systems and generative AI. In his spare time, he enjoys playing video games and listening to music.

Andrew Kim

Andrew Kim

Andrew is a Software Development Engineer at AWS Analytics, with a deep passion for distributed systems architecture and AI-driven solutions, specializing in intelligent data integration workflows and cutting-edge feature development on Apache Spark. Andrew focuses on re-inventing and simplifying solutions to complex technical problems, and he enjoys creating side projects and producing music in his free time.

Mukul Prasad

Mukul Prasad

Mukul is a Senior Applied Science Manager in AWS Analytics. He leads the Data Processing Agents Science team developing DevOps agents to simplify and optimize the customer journey in using AWS Big Data processing services including Amazon EMR, AWS Glue, Amazon Athena, and Amazon SageMaker Unified Studio.

Kartik Panjabi

Kartik Panjabi

Kartik is a Software Engineering Leader at AWS within the Analytics, where he supports engineering teams building AWS Glue and AI-powered developer tools for AWS Glue and Amazon EMR, including the Apache Spark troubleshooting and optimization agent. He focuses on distributed data processing engines, serverless analytics, and using agentic AI to simplify large-scale data engineering workflows.

Mohit Saxena

Mohit Saxena

Mohit leads AWS Glue, AWS’s native serverless Apache Spark data integration service, and the Agentic AI applications and platform across broader AWS Data Analytics — AWS Glue, Amazon EMR, and Amazon Athena. His teams build systems that simplify how customers build, modernize, troubleshoot and optimize data processing workloads at scale.

Reduce the complexity and cost of real-time processing with queues in Amazon Kinesis Data Streams

Post Syndicated from Dirk Fröhner original https://aws.amazon.com/blogs/big-data/reduce-the-complexity-and-cost-of-real-time-processing-with-queues-in-amazon-kinesis-data-streams/

Teams use Amazon Kinesis Data Streams to ingest data once and make it available to every application that needs to consume it in real time. Some of those applications process related records in sequence, building each result on the records before it. Others process each record independently.

Consider an online store that writes every order event to a stream. One application processes the orders in sequence to catch possible fraud. Its state is a count of each customer’s recent orders. It updates that count with every order and flags any customer who places an unusual number in a short time (stateful processing). The fulfillment application processes each order independently, reserving inventory and starting the shipment. It treats every record as a self-contained unit of work that it can process and retry by itself (stateless processing).

Kinesis Data Streams and the Amazon Kinesis Client Library (KCL) are built for the first job. The KCL assigns each shard to one consumer instance at a time, using a lease table in Amazon DynamoDB. The records for a customer reach the same instance in the order they were written. The application saves its progress as a checkpoint, a position in the shard, so after a restart it resumes from where it left off instead of starting over. Applications that read the stream directly this way are called stream consumers in this post. For the fraud check described earlier, each of these mechanics is what keeps its counts accurate.

The fulfillment application doesn’t need orders in sequence, but because it reads shards, it still gets one consumer instance per shard. An on-demand stream sizes its shards for throughput, not for processing time. With 10 shards, at most 10 instances process orders, no matter how far the application falls behind. A checkpoint is a single position in the shard, so the application can’t mark one order as failed and the next one as done. Teams build that per-record tracking, retries, and failure handling themselves. An order that keeps failing either holds up every order behind it in the shard or is skipped, unless their code sets it aside. They still run the lease table and per-shard custom metrics in Amazon CloudWatch to coordinate and monitor their instances. Other teams copy the records into an Amazon Simple Queue Service (Amazon SQS) queue to get per-record tracking without building it. This means ingesting the same data twice and running a relay in between.

Today, AWS introduced queues in Amazon Kinesis Data Streams. A queue delivers the records of an on-demand data stream to your application and tracks the delivery state of each record. The application acknowledges each record when it’s done instead of checkpointing a position. Consumer instances don’t lease shards, so you add instances to process more records in parallel. The queue redelivers any record that isn’t acknowledged in time, and sets aside records that keep failing as dead-letter records. A record that repeatedly fails stops wasting consumer resources and can be inspected and triaged separately. Because the queue does this tracking and publishes its own metrics, your consumer no longer needs a lease table or per-shard custom metrics. This also lowers what it costs to run. You ingest your data once, and the same stream feeds stream consumers, queues, and managed delivery to streaming tables or Amazon Simple Storage Service (Amazon S3) for batch processing. There’s no relay or second copy of the data. Figure 1 illustrates these three consumption and delivery options.

Architecture diagram. Producers write records with PutRecord, PutRecords, or the KPL to one Amazon Kinesis Data Streams on-demand stream with shards. The stream serves three kinds of work at the same time. Process related records in sequence: a stream consumer processes each record in the context of earlier records. Process each record independently, highlighted as the new capability: a queue delivers the stream’s records and tracks the state of each record, and a queue consumer runs as several consumer instances that you add as needed, independent of shards. Deliver for batch processing: managed data delivery writes the records to streaming tables or Amazon S3.

Figure 1: One stream, three ways to consume and deliver its records

Receiving records through a queue is priced at the same rate as data retrieval from the stream. The cost difference comes from the DynamoDB and CloudWatch charges you no longer pay and from compute you use more efficiently. Each consumer instance can run as many parallel threads as it needs to use its CPU fully. Kinesis Data Streams consumers can reduce the cost of processing data by up to 43 percent by using queues instead of the Kinesis Client Library. Actual savings depend on your workload and configuration.

In this post, we walk through how queues work, explain when to use a queue and when to read the stream directly, show where the saving comes from and how AWS measured it, and introduce a sample repository with working code for the main scenarios.

How queues work

A queue is a Kinesis resource that you create for an existing on-demand stream with CreateQueue. Your consumer application, called a queue consumer in this post, then reads records from the queue instead of from shards. Each running copy of the application is a consumer instance. A queue consumer works in three steps:

  1. Receive – Your application polls the queue with ReceiveQueueRecords and gets a batch of up to 10 records. Each record it receives is hidden from other consumer instances for a period called the visibility timeout, so two consumer instances don’t process the same record at the same time.
  2. Process – Your application does the work that the record represents, such as reserving inventory for one order.
  3. Acknowledge – When it finishes, your application calls AcknowledgeQueueRecords, and the queue doesn’t deliver the record again. If the consumer instance fails before it acknowledges, the visibility timeout expires and any consumer instance can receive the record again.

Consumer instances compete for records: each receives the next available records, so you add instances when the backlog grows. Delivery is at least once, and ordering is best effort.

Where a queue starts and what it tracks

You can create several queues for a stream, one for each consuming application. Queues count toward the stream’s limit on registered consumers, which they share with enhanced fan-out consumers: 50 for an On-demand Advantage stream and 20 for an On-demand Standard stream. A queue’s receive throughput is virtually unlimited, and adding a queue doesn’t change anything for your producers or your existing stream consumers. Each queue also tracks its own delivery state: acknowledging a record in one queue doesn’t affect other queues or the record in the stream.

When you create a queue, you choose where in the stream it starts delivering records:

Starting position The queue delivers
LATEST (default) Records that arrive after the queue is created
TRIM_HORIZON All records still in the stream, starting with the oldest
AT_TIMESTAMP Records from a point in time that you choose

With TRIM_HORIZON or AT_TIMESTAMP, a new application starts with data that’s already in the stream.

The lifecycle of a record

Figure 2 shows the states of a record in a queue and the operations that move it between them.

State diagram of a record in a queue with four states: visible, in flight, dead-letter, and acknowledged. ReceiveQueueRecords moves a visible record to in flight and increases its receive count by one. AcknowledgeQueueRecords or AcknowledgeDeadLetterQueueRecords moves an in-flight record to acknowledged, and it is never delivered again. When the visibility timeout expires, an in-flight record returns to visible, or moves to dead-letter if it has reached MaxReceiveCount receives or was already a dead-letter record. ReceiveDeadLetterQueueRecords moves a dead-letter record to in flight, and RestoreDeadLetterQueueRecords returns it to visible in the same queue with a reset receive count. Dead-letter handling is enabled by default.

Figure 2: The lifecycle of a record in a queue

A record that a consumer instance receives is in flight and hidden from other consumer instances until its visibility timeout expires. The timeout defaults to 30 seconds and can be set up to 12 hours. A consumer instance can extend it with UpdateQueueRecordsVisibility, or set it to 0 to release the record immediately. If the timeout expires before an acknowledgment, the record becomes visible again and its receive count goes up by one.

Handle records that keep failing

A record can keep failing because of its content, for example a malformed payload or an order for a product that no longer exists. It can also fail because of a problem on your side, such as an unavailable downstream service or a bug in your consumer. Dead-letter handling, enabled by default, moves a record to the dead-letter state after MaxReceiveCount receives without an acknowledgment (six by default), so that it stops taking capacity from your consumer instances. You can change the count or disable dead-letter handling with CreateQueue or UpdateQueue, or by using the console. With dead-letter handling disabled, failing records keep returning until their retention period in the stream ends.

You work with dead-letter records through a separate set of operations: ReceiveDeadLetterQueueRecords to receive them, RestoreDeadLetterQueueRecords to return them to the normal receive path with a reset receive count, and AcknowledgeDeadLetterQueueRecords to discard them. These operations have their own AWS Identity and Access Management (IAM) actions, so an operator role can handle dead-letter records without changing your consumer’s permissions. The queue also publishes dead-letter metrics such as VisibleDeadLetterQueueRecords, so you can alarm on them. Acknowledge records that can never succeed to discard them. For records that failed because of a broken dependency or a consumer bug, fix the cause first, then restore them. Like any other record, a dead-letter record expires when its retention period in the stream ends.

Design consumers for at-least-once delivery

A consumer instance can receive a record more than once: after a visibility timeout expires, after a restore, or on rare occasions even after an acknowledgment. Because delivery is at least once, make your processing idempotent. Each record carries a RecordId that stays the same across redeliveries and across queues on the stream. A producer retry, however, writes the same data to the stream a second time, and the duplicate arrives as a new record with a different RecordId. Key your side effects on a business ID, such as the order ID, for example with a conditional write. Where records carry no business ID or you don’t control the producers, fall back to RecordId. Size the visibility timeout to your processing time, and extend it for the occasional long-running record. AcknowledgeQueueRecords returns HTTP 200 with separate Successful and Failed lists, so check the Failed list on every call.

Monitoring a queue

Each queue publishes its own metrics to CloudWatch, including VisibleQueueRecords for records ready to be received, InFlightQueueRecords for records that are received but not yet acknowledged, and matching metrics for dead-letter records. Scale your consumer instances on VisibleQueueRecords, and alarm on VisibleDeadLetterQueueRecords so that you notice failing records early.

Choosing between a queue and a stream consumer

With the addition of queues, Kinesis Data Streams now offers two ways to process a stream’s records in real time, and each application can use the one that fits its work:

  • Read the stream directly with a stream consumer when handling a record depends on the records before it, as the fraud check’s running counts do.
  • Receive records through a queue with a queue consumer when each record can be handled on its own, without strict ordering requirements, as reserving inventory for one order can.

The following table compares the two:

Stream consumer Queue consumer
Typical work Aggregations, windowed analytics, fraud and anomaly detection Order fulfillment, per-record inference, record enrichment, search indexing
Ordering In order for each partition key Best effort
Parallelism Each shard is read by one sticky consumer instance of an application at a time Add consumer instances as needed, independently of the shard count
Progress tracking The application stores its read position, for example in the KCL lease table The queue tracks the delivery state of every record
Failed records Retried in place, which holds up the shard, or skipped and tracked by your code Redelivered individually, then set aside as dead-letter records
Tooling KCL, Amazon Managed Service for Apache Flink AWS SDK

What consuming with a queue costs

Besides the DynamoDB and CloudWatch charges, the saving comes from compute. A KCL consumer instance processes each shard’s records one batch after another, so with I/O-bound processing it spends much of its time waiting. The load also depends on partition keys: if most records share one partition key, that shard is processed in sequence while the instances that lease other shards sit idle. A queue consumer instance can run as many parallel threads as it needs to use its CPU fully, so fewer instances handle the same throughput.

An AWS benchmark measured the saving with a synthetic workload, not a real-world customer workload, for which AWS specified the record size, rate, partition-key distribution, and handler cost. A KCL 3.5.3 fleet and a queue fleet consumed the same On-demand Advantage stream at the same time, at a sustained throughput of 25 MB/s with a warm throughput of 100 MB/s. Each fleet was sized to process 99 percent of records within 10 seconds. The comparison covers data retrieval or queue consumption, DynamoDB, CloudWatch, and Amazon Elastic Compute Cloud (Amazon EC2) at US East (Ohio) prices. It excludes ingestion, which costs the same for both. The benchmark tested one handler profile, with 1 ms of CPU and 10 ms of wait per record. This I/O-bound profile is the most favorable condition for the compute part of the saving, and a CPU-bound handler narrows it. Of the $15.09 saving per TiB, $11.55 comes from DynamoDB and CloudWatch, which don’t depend on the handler. Even with no compute advantage, the saving would still be 33 percent. The KCL fleet ran with its default configuration, including detailed metrics with the shard dimension, which produced 1,580 metric series at 190 shards. If you reduce KCL metrics to the summary level without the shard dimension, this part of the saving shrinks, at the cost of per-shard observability.

How queues in Kinesis Data Streams relate to Amazon SQS

Queues in Kinesis Data Streams are powered by Amazon SQS. Built on that foundation, they use familiar queue concepts such as visibility timeouts, acknowledgments, and dead-letter handling. They’re a capability of Kinesis Data Streams, and you work with them through the Kinesis Data Streams APIs.

Amazon SQS continues to be the place to start for point-to-point messaging between application components, such as buffering requests, decoupling services, and background jobs, where no other application needs the same data.

Choose queues in Kinesis Data Streams when the same records are needed by more than one application. There’s no dual ingest and no relay to operate. Applications that process each record independently receive and acknowledge each record through the AWS SDK, with no KCL, lease table, or shards to manage.

Explore the sample repository

The GitHub repo contains working code for six scenarios, written in TypeScript, with Java for the KCL consumers, and deployed with the AWS Cloud Development Kit (AWS CDK). Each scenario builds on a quickstart with an on-demand stream, an order producer, and a KCL consumer on AWS Fargate, and the README lists the prerequisites and the cleanup steps. The scenarios are the following:

  • Build your first queue consumer – A receive, process, and acknowledge loop on the AWS SDK alone, with long polling. Shown in TypeScript, and it works the same in any language with an AWS SDK.
  • Process records safely – An idempotent handler keyed on the order ID, which any at-least-once consumer needs, KCL applications included.
  • Scale out independently of shards – More consumer instances on Amazon Elastic Container Service (Amazon ECS) than the stream has shards, scaled on the backlog metric.
  • Handle failures and dead-letter records – A transient error that succeeds on redelivery, and a malformed record that an operator restores or discards.
  • Consume one stream in more than one way – The fraud check and a fulfillment queue on the same stream, plus a second queue that starts at AT_TIMESTAMP.
  • Migrate an existing consumer – From a stateless KCL application, and from a relay into an SQS queue.

In the KCL migration, a receive and acknowledge loop replaces the KCL, its lease table, and custom metrics, and the processing logic stays. When the SQS queue behind a relay carries only records from the stream, a queue in Kinesis Data Streams replaces both the relay and the SQS queue. If other applications also send messages to that SQS queue, keep it. The consumer’s API calls map as follows:

Amazon SQS Kinesis queue
ReceiveMessage ReceiveQueueRecords
DeleteMessage, DeleteMessageBatch AcknowledgeQueueRecords
ChangeMessageVisibility, ChangeMessageVisibilityBatch UpdateQueueRecordsVisibility
Dead-letter queue with a redrive policy Dead-letter state in the same queue, restored with RestoreDeadLetterQueueRecords

Both migrations pick a starting position that skips no records, and tolerate duplicates while old and new consumers overlap.

Conclusion

Queues in Kinesis Data Streams are built for work where each record stands on its own. They scale with your backlog instead of your shard count, track every record for you, and set failing records aside so that they don’t hold up the rest. Stream consumers remain the right choice for work that depends on the order of records. Kinesis queues are powered by Amazon SQS and use familiar queue concepts such as visibility timeouts, acknowledgments, and dead-letter handling. You ingest your data once, and stream consumers, queues, and delivery to Amazon S3 all read from the same stream. If you run stateless KCL consumers, moving them to a queue can also lower your processing cost.

For Regional availability, see Supported AWS Regions. For pricing, see Amazon Kinesis Data Streams pricing. To get started, create a queue for an on-demand stream on the Kinesis console or with CreateQueue, and run the scenarios in the GitHub repo. For more information, refer to Consume records from a stream with queues in the Amazon Kinesis Data Streams Developer Guide. For help with your use case, contact your AWS representative.


About the authors

Dirk Fröhner

Dirk Fröhner

Dirk is a Principal Solutions Architect at AWS, where he works with software companies on their multi-dimensional transformation. Topics include technology and software architecture evolution, organizational change, and innovation culture. Dirk brings professional experience and knowledge of human nature gained from 25+ years in the business.

Marco Jahn

Marco Jahn

Marco is a Senior Solutions Architect at AWS, where he helps organizations build scalable, resilient cloud-native architectures and adopt agentic development practices. With more than 25 years in software engineering and architecture, he focuses on serverless, event-driven design and the AI-Driven Development Life Cycle (AI-DLC).

Sabarish Sekar

Sabarish Sekar

Sabarish is a Senior Solutions Architect at AWS, where he works with software companies on application modernization, AI transformation, and scalable SaaS. He has more than 13 years of experience across software development and architecture roles, so he brings a builder’s view to helping customers turn new technology into business results.

Stephan Schiller

Stephan Schiller

Stephan is a Solutions Architect at AWS, where he helps organizations build event-driven architectures, modern data platforms, and reliable agentic AI solutions on top of them. He brings more than 10 years of experience in the cloud industry, including technical roles at other hyperscalers before joining AWS.

Introducing simplified onboarding for AWS WAF Bot Control at the targeted inspection level

Post Syndicated from Pengfei Shao original https://aws.amazon.com/blogs/security/introducing-simplified-onboarding-for-aws-waf-bot-control-at-the-targeted-inspection-level/

Today, we’re announcing simplified onboarding and bot confidence levels for AWS WAF Bot Control at the targeted inspection level, which we refer to as Targeted bot control in this post, matching the console. Bot confidence levels and the new LATEST rule group version are available for the resource types that AWS WAF protects: you act on advanced bot detections by confidence level instead of writing label rules, and you stay on the newest detections without manual upgrades, helping you respond to automated traffic, including traffic from AI-powered bots. For the websites and applications that you deliver through Amazon CloudFront, simplified onboarding goes further: you turn on Targeted bot control from a single console setting, and automatic SDK integration, which launched last month, removes the need for application code changes in many cases.

In this post, we explain what the simplified onboarding experience looks like and how to get started when protecting CloudFront-delivered applications.

Granular control takes effort to configure

Targeted bot control uses advanced behavioral analysis designed to help identify sophisticated bots that attempt to evade traditional detection mechanisms. It uses machine learning and client-side signals to help detect sophisticated AI-based bots. It’s also deliberately granular: it surfaces each detection as its own label, so you can build rules around specific behaviors. The number of choices (which labels, which combinations, and which order) is a lot to evaluate and implement when your immediate goal is to implement the first round of protections.

To get the full value of Targeted bot control, and to help reduce false positives by grouping its signals into confidence levels, you typically do the following:

  1. Add the AWS WAF Bot Control managed rule group to your protection pack, set the inspection level to Targeted, and choose a rule group version.
  2. Integrate the AWS WAF JavaScript SDK into your application. This is an application code change, often owned by a different team at your company and tied to a different release cycle.
  3. Learn which AWS WAF labels the rules emit and what they mean, and decide which combinations indicate a bot with high confidence.
  4. Write label-match rules that group those labels into bot confidence levels, place them in the right order, and keep them current as new rule group versions add labels.

We’ve published guidance on grouping targeted bot labels into confidence tiers. For teams without dedicated security engineers, the path to implement the solution can be long. Completing every step can take time, especially when the SDK integration depends on another team’s release cycle, so rules can remain in Count mode longer than intended.

What’s new

You can now turn on Targeted bot control with a single toggle. AWS WAF sets up the recommended configuration for you and keeps it on the latest detections, and you don’t need to change your application code to integrate AWS WAF JavaScript SDK for CloudFront-delivered applications in many cases. When you use this toggle, AWS WAF configures the following for you:

  • Targeted inspection level – The AWS WAF Bot Control rule group is added (or configured) with the inspection level set to Targeted and machine learning turned on.
  • Actions for each bot confidence level – Each confidence level (High, Medium, or Low) gets an AWS-recommended action, which you can change.
  • Rule group version – The rule group is set to the LATEST version, which points to the most recent AWS WAF Bot Control release, so you get new detections without upgrading manually.
  • Rule order – A newly added AWS WAF Bot Control rule group is placed after the existing rules.
  • Automatic SDK integration – This option is available for protection packs with the CloudFront scope and is turned on by default, so the targeted detections receive browser signals from the start. If you want, you can use this feature stand-alone.

Bot confidence

With bot confidence, AWS WAF Bot Control now adds a High, Medium, or Low bot confidence level to each request that it evaluates at the targeted inspection level. The confidence level reflects how likely it is that the request comes from an automated client that exhibits behaviors that you might not want.

Several AWS WAF Bot Control rules already report their own confidence levels with AWS WAF labels, for example TGT_ML_CoordinatedActivityLow/Medium/High and TGT_TokenReuseIpLow/Medium/High rules, and the TGT_VolumetricSession rule emits labels ending in volumetric:session:low, volumetric:session:medium, and volumetric:session:high. Each of those describes the strength of one detection. Bot confidence combines the targeted detections into one High, Medium, or Low level for each request, so you choose one action per level instead of writing rules across many labels. Bot confidence also emits three labels ending in targeted:signal:bot_signal:low, targeted:signal:bot_signal:medium and targeted:signal:bot_signal:high.

The confidence levels and their default actions reflect AWS recommendations to AWS WAF Bot Control customers.

Confidence level What it indicates Default action
High A signal that by itself strongly indicates automation, or two or more signals that corroborate each other CAPTCHA
Medium A signal that indicates automation, but no other signal corroborates it; the request might still come from a person CAPTCHA
Low Only weak signals of automation Challenge

The defaults are chosen to help keep false positives low. High-confidence and Medium-confidence bot traffic receives a CAPTCHA puzzle rather than a block, so a misclassified user can still get through. Low-confidence bot traffic receives a silent Challenge, which is designed to complete in the browser without requiring user interaction. You can change any of these actions to Allow, Block, CAPTCHA, Challenge, Count, or Monetize.

The confidence levels are added alongside the existing AWS WAF Bot Control labels. The existing detection labels that AWS WAF Bot Control emits are still attached to the request, so you can inspect any request and see which signals contributed to its confidence level.

Automatic SDK integration for CloudFront

The AWS WAF JavaScript SDK runs in the viewer’s browser, where it can see signals the server doesn’t normally receive, such as mouse movements, key presses, form interactions, and device characteristics. These client-side signals help improve the accuracy of the targeted detections in distinguishing between a person and an automated client. The SDK silently acquires and refreshes an AWS WAF token as the page loads, without the extra charges or interruptions of Challenge and CAPTCHA rule actions.

That token travels with each request and is used by AWS WAF Bot Control at the targeted inspection level, AWS WAF Fraud Control account takeover prevention, and AWS WAF Fraud Control account creation fraud prevention. Until now, integrating the SDK meant adding a script tag to your pages yourself.

With automatic SDK integration for CloudFront, you don’t add the script tag yourself. When the setting is on, CloudFront inserts the same script tag that a manual integration uses, pointing to your protection pack’s integration URL. AWS WAF evaluation, token acquisition, and token refresh work the same way as they do with a manual integration.

Automatic SDK integration is available for any protection pack with the CloudFront scope that contains one of the following managed rule groups:

  • AWS WAF Bot Control with targeted inspection level
  • AWS WAF Fraud Control account takeover prevention
  • AWS WAF Fraud Control account creation fraud prevention

For the up-to-date list of managed rule groups supporting this feature, see Automatic SDK integration for CloudFront distributions.

A rule group also qualifies when its actions are overridden to Count, so you can add the SDK while you evaluate the rule group. When you create a new protection pack with the CloudFront scope in the console, automatic SDK integration is turned on by default. Protection packs created before the feature launched aren’t changed. You can also turn the setting off with a single toggle if you prefer to integrate the SDK yourself. The SDK collects client-side signals and stores the AWS WAF token in a cookie named aws-waf-token. The token contains information collected from your visitors’ browsers. As described in AWS WAF token characteristics, the information gathered is non-unique and can’t be mapped to an individual human being. Before you turn on automatic SDK integration, review your privacy notice and any cookie consent obligations that apply to your sites, for example under GDPR and the ePrivacy Directive.

Walkthrough

In this section, we show you how to enable Targeted bot control with bot confidence and automatic SDK integration for CloudFront.

Prerequisites

To follow this walkthrough, you need the following:

  • A CloudFront distribution that serves HTML pages.
  • The CloudFront distribution uses pay-as-you-go pricing, because distributions on a CloudFront flat-rate pricing plan don’t support AWS WAF Bot Control at the targeted inspection level.

Enable Targeted bot control on a new protection pack

When you create a new protection pack, you can turn on Targeted bot control together with automatic SDK integration.

  1. Open the AWS Management Console for AWS WAF & Shield and choose Protection packs (web ACLs), then Create protection pack (web ACL).
  2. Under App category, select the category that describes your application. Under Add resources, select your CloudFront distribution.
  3. Select one of the predefined protection pack options. The Targeted bot control section isn’t available when you choose Build your own.
  4. In the Targeted bot control section, choose Enable Targeted bot control.
    Figure 1: The Targeted bot control section during protection pack creation

    Figure 1: The Targeted bot control section during protection pack creation

  5. Review the action for each confidence level. The defaults are CAPTCHA for High, CAPTCHA for Medium, and Challenge for Low. To observe the effect before you enforce, select Set all actions to Count.
  6. Confirm that Enable automatic SDK integration is selected.
  7. Choose Create protection pack (web ACL).

Enable Targeted bot control on an existing protection pack

These steps work whether your protection pack doesn’t yet have AWS WAF Bot Control, uses AWS WAF Bot Control at the common level, or uses an older AWS WAF Bot Control version.

  1. In the AWS WAF & Shield console, open Protection packs (web ACLs) and select a protection pack with the CloudFront scope.
    Figure 2: Choosing an existing protection pack

    Figure 2: Choosing an existing protection pack

  2. In the side pane, choose Configure Targeted bot control.
  3. Choose Enable Targeted bot control.
    Figure 3: The Configure Targeted bot control page

    Figure 3: The Configure Targeted bot control page

  4. Review the actions for each confidence level and the automatic SDK integration setting.
  5. Choose Save. If the change upgrades the AWS WAF Bot Control rule group to LATEST, a confirmation dialog shows the current and target versions. Review it and confirm.

Configuring through the API

If you manage AWS WAF as code, you can configure the same pieces directly. For automatic SDK integration, add the ChallengeJavascriptSdkInjection setting to the AssociationConfig of the web ACL in a CreateWebACL or UpdateWebACL request, using the CLOUDFRONT key with an empty configuration object:

"AssociationConfig": {
  "ChallengeJavascriptSdkInjection": {
    "CLOUDFRONT": {}
  }
}

Through the API, the setting is off by default. An UpdateWebACL request that omits the setting turns it off, even if you turned it on in the console. For the rule group, set the inspection level to TARGETED with machine learning enabled in the AWSManagedRulesBotControlRuleSet configuration, and use RuleActionOverrides to set the actions for TGT_SignalBotHigh, TGT_SignalBotMedium, and TGT_SignalBotLow.

For the API specifications, see AssociationConfig and ManagedRuleGroupStatement in the AWS WAF API Reference.

Considerations

Considerations when using bot confidence and automatic SDK integration for CloudFront:

Bot confidence

Review the following when you use bot confidence.

  • Exclude known automation from bot inspection. If you find known clients that are being flagged, add a scope-down statement to the AWS WAF Bot Control rule group that excludes them, for example by path, header, or IP set. This also keeps you from paying to inspect traffic you already trust.
  • Stay on the LATEST version. Bot confidence requires version 8.0 or later. LATEST keeps you on the newest release automatically; if you pin a static version for change control, choose 8.0 or later and review new versions as they’re released.

For the full list of considerations about bot confidence, see Bot confidence levels in the AWS WAF Developer Guide.

Automatic SDK integration for CloudFront

Review the following before you turn on automatic SDK integration.

  • Confirm that the SDK reaches the pages that matter. After you turn the setting on, view the source of your key pages, such as the home page, sign-in, checkout, and search, to confirm the script tag is present. If your distribution caches HTML, invalidate the cached HTML paths so viewers get the updated pages right away. Do the same when you turn the setting off.
  • Update your content security policy. If your pages set a content security policy, allowlist https://*.awswaf.com in the directives shown in Using the JavaScript API with content security policies.
  • Use Cache-Control: no-transform to keep the tag off specific pages. The setting applies to the whole protection pack, and scope-down statements don’t limit where the tag is inserted.
  • Keep your existing integration where your application relies on the SDK directly. Single-page applications that attach tokens to their own API calls, and applications that use the CAPTCHA JavaScript API or the mobile SDKs, should continue to integrate the SDK as they do today.

For the full list of considerations and edge cases, see Considerations and limitations and When pages don’t receive the tag in the AWS WAF Developer Guide.

Availability and pricing

Simplified onboarding to Targeted bot control is available for protection packs with the CloudFront scope. Bot confidence levels and the new LATEST rule group version are available for the resource types that AWS WAF protects, in the AWS Regions where AWS WAF Bot Control is available. Automatic SDK integration is available for protection packs with the CloudFront scope. This post focuses on CloudFront because you get both features there.

Standard AWS WAF Bot Control charges for the targeted inspection level apply. Automatic SDK integration for CloudFront is available at no additional cost. For details, see AWS WAF pricing.

Conclusion

Simplified onboarding for Targeted bot control takes care of most of the configuration work. You enable Targeted bot control and choose one action for each of three bot confidence levels, or keep the defaults, and enable automatic SDK integration for CloudFront. Your protection pack starts with the configuration we recommend, stays on the latest detections, and doesn’t require you to integrate the JavaScript SDK manually with your CloudFront-delivered applications.

If you have questions about this post, contact AWS Support or start a new thread on AWS re:Post.


Pengfei Shao

Pengfei Shao

Pengfei is a Senior Technical Account Manager at AWS based in Stockholm, and has more than 20 years of experience in Telecom and IT industry. His main focus is to help AWS Enterprise Support customers remain operationally healthy, secure, and cost efficient in AWS. He is also focused on AWS Edge Services and loves to work with customers to solve their technical challenges.

Amitai Rottem

Amitai Rottem

Amitai is a Principal Product Manager at AWS on the AWS WAF team, focused on bot detection and threat intelligence. He brings over 20 years of experience in enterprise security across product management, software development, and startups, including prior roles at large technology companies.

Amazon MSK Express brokers available on AWS Graviton4-based M8g instances

Post Syndicated from Charishma Makineni original https://aws.amazon.com/blogs/big-data/amazon-msk-express-brokers-available-on-aws-graviton4-based-m8g-instances/

Teams running Apache Kafka for real-time streaming often face a tradeoff: better performance or lower costs. Now, you can have both. Get faster throughput and lower tail latency from the same cluster, with no increase in infrastructure costs. Amazon Managed Streaming for Apache Kafka (Amazon MSK) Express brokers are now available on AWS Graviton4-based M8g instances. Compared with Express brokers on M7g, Express brokers on M8g have 15 percent lower broker-hour pricing. You also no longer pay the broker-side cost when moving data across Availability Zones for client traffic, which reduces total cross-AZ data transfer costs by 50 percent. With M8g, Express brokers now support a 24xlarge instance size, giving you more headroom to scale. In our testing at the same broker size and load, P99 produce latency was 21–54 percent lower on M8g, and broker CPU was 9–11 percentage points lower. Consumers that fell behind cleared up to 3x more backlog in 30 minutes. P99 produce latency is the time to acknowledge a produced record for the slowest 1 percent of requests, a common measure of tail latency.

In this post, we cover what changes with Express brokers on M8g and how it affects cost. We share benchmark results comparing M8g to M7g, and we show you how to move your cluster to M8g.

Express brokers on M8g

Express brokers give you up to 3x more throughput per broker, up to 20x faster scaling, and up to 90% faster recovery than Standard brokers. Express brokers manage storage and broker tuning for you, so your team spends time on streaming applications instead of cluster maintenance.

Express brokers on M8g keep what Express brokers support on M7g: the same Kafka versions, authentication methods, custom configurations, Amazon CloudWatch metrics, and Open Monitoring with Prometheus. For sizes available on both generations, storage and network throughput per broker are the same as Express brokers on M7g, so you can move to M8g at the size you run today and keep the same per-broker throughput.

The following table compares Express brokers on M7g and M8g.

Express on M7g Express on M8g
Broker-hour price Baseline 15% lower
Amazon MSK broker-side cross-AZ charge for client traffic Charged Not charged
Amazon MSK EC2-side cross-AZ charge for client traffic Baseline Same
Largest broker size 16xlarge 24xlarge
Throughput per broker at each size Baseline Same
Connection limit per broker Baseline Same
Data-in and storage pricing Baseline Same

AWS offers Express brokers on M8g in the following sizes. Use the recommended throughput and partition limits when you size a cluster.

Broker size vCPUs Memory (GiB) Recommended ingress per broker (MBps) Recommended egress per broker (MBps) Recommended partitions per broker Max partitions per broker
express.m8g.large 2 8 15.6 31.2 1,000 1,500
express.m8g.xlarge 4 16 31.2 62.5 1,000 2,000
express.m8g.2xlarge 8 32 62.5 125 2,500 4,000
express.m8g.4xlarge 16 64 124.9 249.8 6,000 8,000
express.m8g.8xlarge 32 128 250 500 12,000 16,000
express.m8g.12xlarge 48 192 375 750 16,000 24,000
express.m8g.16xlarge 64 256 500 1,000 20,000 32,000
express.m8g.24xlarge 96 384 667 1,334 20,000 32,000

What this means for your workloads

  • Latency-sensitive and bursty workloads – Lower P99 produce latency means fewer slow acknowledgments during traffic spikes, which is where tail latency affects your end users.
  • Workloads that have outgrown 16xlarge – With the 24xlarge size, you can run more throughput on each broker. An express.m8g.24xlarge broker supports 667 MBps of recommended ingress, compared with 500 MBps on express.m8g.16xlarge. If you have a throughput-bound workload and run many 16xlarge brokers today, you can run fewer 24xlarge brokers.
  • Multi-AZ pipelines – Lower broker-hour pricing and no broker-side cross-AZ charge lower the cost of running a cluster across three Availability Zones, with no change to your application code.
  • Workloads that replay data or recover from lag – Consumers that fall behind after an outage, a deployment, or a reprocessing job catch up faster on M8g. In our test, consumers on M8g cleared up to 3x more backlog in 30 minutes than on M7g, so you recover sooner without adding brokers.

Benchmark: Express on M8g compared with Express on M7g

We wanted to see how M8g behaves under the same load as M7g, so we changed only the broker generation and kept everything else the same.

Test setup

  • Two Express clusters, one on express.m8g.large and one on express.m7g.large, each with three brokers across three Availability Zones in US East (N. Virginia).
  • Kafka version 3.9.x (KRaft mode) on both clusters.
  • Transport Layer Security (TLS) encryption in transit and AWS Identity and Access Management (IAM) access control.
  • Six topics with 64 partitions each, replication factor 3, and min.insync.replicas=2.
  • Producer settings: acks=all, linger.ms=5, batch.size=65536 (64 KiB), compression.type=none.
  • One consumer group per topic.
  • Fixed message size of 512 bytes.
  • Three c7i.2xlarge client instances, one in each Availability Zone, running kafka-producer-perf-test and kafka-consumer-perf-test from Apache Kafka 3.9.1 with the Amazon MSK IAM authentication library. Each client drove both clusters at the same time, so both clusters saw the same client and network conditions. Client CPU stayed below 20% and network throughput below 10% of instance capacity at every step, so clients were never the bottleneck.

Express brokers manage server-side settings such as network and I/O threads, so there was nothing to tune on the broker side.

We stepped ingress from 2–16 MBps per broker in 2 MBps increments. We held each step for about 10 minutes and recorded values only after the cluster reached steady state.

P99 produce latency

P99 produce latency was lower on M8g at every step. At 6 MBps per broker, P99 was 34 ms on M8g and 48 ms on M7g, 29 percent lower. At 12 MBps per broker, P99 was 54 ms on M8g and 96 ms on M7g, 44 percent lower. The difference was largest at 14 MBps per broker, where P99 was 54 ms on M8g and 117 ms on M7g, 54 percent lower.

Ingress per broker (MBps) M8g P99 (ms) M7g P99 (ms) Reduction
2 26 33 21%
4 30 40 25%
6 34 48 29%
8 41 54 24%
10 40 58 31%
12 54 96 44%
14 54 117 54%
16 82 138 41%
Line chart of P99 produce latency by ingress per broker, lower for express.m8g.large than express.m7g.large at every step

Figure 1: Client P99 produce latency by ingress per broker for express.m8g.large and express.m7g.large

Broker CPU

At the same load, M8g brokers used less CPU. Broker CPU (user plus system, averaged across the three brokers) was 9–11 percentage points lower on M8g at each step. At 6 MBps per broker, M8g ran at 45 percent and M7g at 56 percent. M7g brokers ran at 60 percent or higher from 8 MBps per broker. M8g brokers stayed below 60 percent through 14 MBps per broker. That gives you more room on each broker for traffic spikes and broker maintenance.

Ingress per broker (MBps) M8g CPU (%) M7g CPU (%)
2 39 49
4 41 52
6 45 56
8 51 61
10 51 60
12 56 66
14 58 68
16 62 72
Line chart of average broker CPU by ingress per broker, 9 to 11 points lower on express.m8g.large than express.m7g.large

Figure 2: Average broker CPU (user plus system) at each load step for express.m8g.large and express.m7g.large

Consumer catch-up

When consumers fall behind, for example after an outage or a deployment, they must read the backlog while producers keep writing. We ran a separate test to measure how fast consumers catch up on each generation. This test used a new pair of express.m8g.large and express.m7g.large clusters, with the same Kafka version, authentication, and encryption as the latency test, and the following differences:

  • Three topics with 440 partitions each and replication factor 3, for 1,320 partition replicas per broker.
  • 1 KiB records, acks=all, batch.size=65536 (64 KiB), linger.ms=10, and compression.type=none.
  • Producers wrote about 5.7 MBps per broker (35 percent of the recommended ingress for large brokers) for 3 hours, with 2 hours of retention.
  • One consumer group read new records as they arrived. Every 30 minutes, two more groups of 30 consumers each restarted with a new group ID and read from the earliest offset. Each cycle then read the whole retained backlog.
  • Four c5.4xlarge client instances for each cluster (two for producers and two for consumers). Client CPU stayed below 35 percent, so the clients were never the bottleneck.

With a backlog of about 30 million records (about 30 GB), consumers on M8g caught up in 13–18 minutes. On M7g, consumers had not caught up after 30 minutes and still had 2–9 million records to read. At the largest backlog, about 120 million records, consumers on M8g cleared about 91 million records in 30 minutes, compared with 30–32 million on M7g. That is about 3x more backlog cleared in 30 minutes.

Line chart of consumer lag over 30 minutes for express.m8g.large and express.m7g.large, starting from about 120 million records. After 30 minutes, M8g lag is down to about 29 million records. M7g lag is still about 91 million records.

Figure 3: Consumer lag after a catch-up group starts from the earliest offset of a 120-million-record backlog, for express.m8g.large and express.m7g.large

Your results depend on load, message size, batch settings, consumer group count, and broker size. We ran this test on the large size only. To estimate your results, create an Express cluster on M8g and run your own workload against it. When you finish testing, delete the cluster to avoid ongoing charges.

Cost

Express brokers on M8g lower your costs in two ways: lower broker-hour pricing, and no broker-side charge for cross-AZ client traffic.

Broker-hour pricing

Broker-hour pricing for Express brokers on M8g is 15 percent lower than Express brokers on M7g at each size. In US East (N. Virginia), express.m8g.large costs $0.347 per hour and express.m7g.large costs $0.408 per hour. Data-in and storage pricing don’t change.

Cross-AZ data transfer

Many production Kafka clusters run across three Availability Zones. When a client connects to a broker in a different Availability Zone, the traffic between them is cross-AZ traffic. With clients spread evenly across three Availability Zones, about two-thirds of client traffic is cross-AZ. Each request goes to the partition leader, which can be in any Availability Zone.

Standard AWS data transfer charges for cross-AZ traffic in US East (N. Virginia) are $0.01 per GB on the sending side and $0.01 per GB on the receiving side, or $0.02 per GB in total. With Express brokers on M8g, AWS doesn’t charge the broker side, so cross-AZ traffic between your clients and brokers costs $0.01 per GB in total. That’s 50 percent lower than on M7g.

The following table shows the cross-AZ data transfer charge per GB of client traffic for each generation.

Express on M7g Express on M8g
Client side $0.01 per GB $0.01 per GB
Broker side $0.01 per GB Not charged
Total per GB of cross-AZ client traffic $0.02 $0.01

You can reduce consumer cross-AZ traffic with rack awareness. Producers must write to the partition leader, which can be in any Availability Zone. Consumers can read from a replica in their own Availability Zone instead. To turn this on, set replica.selector.class to org.apache.kafka.common.replica.RackAwareReplicaSelector in your cluster configuration. Set client.rack on each consumer to the Availability Zone ID it runs in (for example, use1-az1). Consumers that read from a local replica don’t incur cross-AZ traffic, so you pay cross-AZ charges only on the produce side. On Express brokers on M8g, that produce-side cross-AZ traffic costs $0.01 per GB. If you don’t use rack awareness, your consumer cross-AZ traffic also costs 50 percent less on M8g, because AWS doesn’t charge the broker side.

For example, consider a cluster of three large brokers in US East (N. Virginia) with 30 MBps of ingress and two consumer groups (60 MBps of egress). Over a 30-day month, about 155,520 GB of client traffic crosses Availability Zones.

Monthly cost Express on M7g Express on M8g Express on M8g with rack awareness
Broker hours (3 brokers × 720 hours) $881.28 $749.52 $749.52
Cross-AZ produce traffic (51,840 GB) $1,036.80 $518.40 $518.40
Cross-AZ consume traffic (103,680 GB) $2,073.60 $1,036.80 $0
Total $3,991.68 $2,304.72 $1,267.92

With rack awareness, the cross-AZ charge in this example drops from $1,555.20 to $518.40 per month. Reading from a follower replica can add a small amount of end-to-end latency, so test with your workload. For setup steps, see Reduce network traffic costs of your Amazon MSK consumers with rack awareness.

Data-in and storage charges are the same on both generations, so they aren’t included.

To estimate your own cross-AZ traffic, add the BytesInPerSec and BytesOutPerSec CloudWatch metrics across your brokers. Each 1 MBps sustained over a 30-day month is about 2,592 GB. Multiply the total by two-thirds if your clients are spread evenly across three Availability Zones. If your consumers use rack awareness, count only BytesInPerSec.

This applies only to traffic between your clients and brokers. Replication traffic between brokers, and between metadata nodes and brokers, isn’t charged on either generation. For details, see Amazon MSK pricing.

Move to Express brokers on M8g

You have three options, depending on where your workload runs today.

Create a cluster on M8g

In the Amazon MSK console, choose Create cluster, choose Express as the broker type, and choose an M8g size. You can also use the CreateClusterV2 API.

Update an Express cluster on M7g

You can change the broker type of a cluster from M7g to M8g in place. Amazon MSK updates brokers one at a time, so clients keep producing and consuming during the update.

aws kafka update-broker-type \
    --cluster-arn <your-cluster-arn> \
    --current-version <current-cluster-version> \
    --target-instance-type express.m8g.large

Before you update, check that your partition count per broker and your throughput fit within the limits for the target size.

Move from Standard brokers or a self-managed Kafka cluster

Create a new Express cluster on M8g, and then use Amazon MSK Replicator to copy your topics, data, and consumer group offsets to it. For steps, see Migrate from Standard brokers to Express brokers or Migrate from non-MSK Apache Kafka clusters.

Considerations

  • Connection limits per broker don’t change.
  • The pricing and performance changes in this post apply to Express brokers. M8g is also available for Standard brokers. For Standard broker pricing, see the Amazon MSK pricing page.

Conclusion

Express brokers on Graviton4-based M8g instances lower the cost of running Kafka on Amazon MSK and lower tail latency for the same load. You get 15 percent lower broker-hour pricing, no Amazon MSK broker-side charge for cross-AZ client traffic, and a 24xlarge size for workloads that need more capacity per broker. In our benchmark at the large size, P99 produce latency was 21–54 percent lower, broker CPU was 9–11 percentage points lower, and consumers that fell behind cleared up to 3x more backlog in 30 minutes than on M7g.

To get started, create an Express cluster on M8g or update your Express cluster on M7g. Amazon MSK supports M8g sizes in every AWS Region that supports Express brokers. For pricing, see Amazon MSK pricing. For setup steps, see the Amazon MSK Developer Guide.

If you have questions or feedback, leave a comment on this post or start a thread on AWS re:Post.

 


About the authors

Charishma Makineni

Charishma Makineni

Charishma is a Senior Specialist Solutions Architect for streaming at AWS. She helps customers build real-time streaming architectures using services like Amazon Kinesis Data Streams and Amazon Managed Streaming for Apache Kafka (Amazon MSK). Outside of work, Charishma enjoys being outdoors, gardening, and reading.

Swapna Bandla

Swapna Bandla

Swapna is a Senior Streaming Solutions Architect on the AWS Streaming Specialist SA Team. She has a passion for understanding customers’ data and analytics needs, and empowering them to develop cloud-based, well-architected solutions. Outside of work, she enjoys spending time with her family.

Huyam Hasan

Huyam Hasan

Huyam is a Solutions Architect II at AWS, based in Austin, TX. She works with enterprise customers in travel, hospitality, and gaming to design real-time data and streaming architectures, and helps them bring generative and agentic AI into production. She is passionate about turning data into business outcomes for her customers.

Securing REST APIs with JWT authorizers in Amazon API Gateway

Post Syndicated from Giedrius Praspaliauskas original https://aws.amazon.com/blogs/compute/securing-rest-apis-with-jwt-authorizers-in-amazon-api-gateway/

Many teams already run an OpenID Connect (OIDC) identity provider and want their Amazon API Gateway REST APIs to accept its security tokens. Until now, the built-in authorizer for API Gateway REST APIs accepted only Amazon Cognito tokens. For other identity providers, you wrote an AWS Lambda authorizer that downloaded the provider’s signing keys, verified each token, and returned an AWS Identity and Access Management (IAM) policy.

Today, AWS announced JSON Web Token (JWT) authorizers for API Gateway REST APIs, which validate tokens in API Gateway itself. You declare the issuers you trust, the audiences you accept from each, the signing algorithms you permit, and any additional claims you require the token to carry. JWT authorizers work on Regional, edge-optimized, and private REST APIs.

In this post, you learn how JWT authorizers work. You then build a REST API that accepts machine-to-machine tokens from your own identity provider and enforces different scopes on read and write operations. Finally, you add an Amazon Cognito user pool as a second trusted issuer on the same authorizer.

Solution overview

Lambda authorizers remain the right choice when authorization needs custom logic, token introspection, or credentials that are not JWTs. For token validation alone, a JWT authorizer validates the token in API Gateway itself, with no function to maintain and no invocation in the request path, as the following diagram shows.

A client calls API Gateway, which validates the token and passes only authorized requests to the backend integration.

Figure 1: New architecture. API Gateway validates the token inline and forwards only authorized requests to the integration

Each request goes through the following steps:

  1. The client sends a security token as a bearer token in the header that the identity source names, typically Authorization.
  2. API Gateway matches the token’s iss claim to a configured issuer and rejects a token from an unknown issuer before any network call.
  3. API Gateway checks that the token’s signing algorithm is one you configured, then validates the signature against the issuer’s public keys, which it locates through OIDC discovery and caches.
  4. API Gateway checks the audience and the expiry and not-before times.
  5. If the method requires authorization scopes, you must use an access token that carries at least one of them in its scope or scp claim.
  6. API Gateway checks any additional claim rules you configured for that issuer.
  7. API Gateway passes the validated claims to the integration, and the request proceeds.

API Gateway stops processing the request at the first failed check. API Gateway returns 401 Unauthorized for a missing, malformed, expired, or untrusted token. It returns 403 Forbidden for a valid token that lacks a required scope or fails a claim rule. If API Gateway cannot reach an issuer’s key endpoint and has no cached keys, it returns a 5xx response rather than letting the request through.

Walkthrough

In this walkthrough, you create an orders REST API in which GET /orders requires the orders:read scope and POST /orders requires orders:write.

Prerequisites

To follow this walkthrough, you need:

  • An AWS account and an IAM principal with permissions to manage API Gateway resources, and Amazon Cognito resources for step 7. Follow the principle of least privilege.
  • An OIDC-compatible identity provider that supports the OAuth 2.0 client credentials flow and publishes a discovery document at /.well-known/openid-configuration.
  • The latest version of the AWS Command Line Interface (AWS CLI).
  • curl and jq.

Step 1: Prepare your identity provider

In your identity provider, create an API (or resource server) for the orders service with two scopes, orders:read and orders:write. Then create two machine-to-machine applications: a reporting application with only orders:read and a fulfillment application with both scopes.

Then collect the following values, shown here for three common providers.

Value Okta Auth0 Microsoft Entra ID
ISSUER https://{yourOktaDomain}/oauth2/default for the default custom authorization server https://{yourTenant}.auth0.com/, including the trailing slash. Note that URL might include country code. https://login.microsoftonline.com/{tenantId}/v2.0
AUDIENCE The authorization server’s Audience, for example api://default The API Identifier The application ID URI or client ID of the API app registration
TOKEN_URL {ISSUER}/v1/token https://{yourTenant}.auth0.com/oauth/token Note that URL might include country code. https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token
Scopes Custom scopes on the authorization server Permissions on the API, granted to each application See Considerations. Client credentials tokens carry app roles, not scopes.

For the example walkthrough, set the values as environment variables (production clients can load client secrets from AWS Secrets Manager or an equivalent store).

REGION=<your AWS Region, for example us-east-1>
ISSUER=<issuer URL, exactly as it appears in the token's iss claim>
AUDIENCE=<audience value>
TOKEN_URL=<token endpoint>
READER_ID=<reporting application client ID>
READER_SECRET=<reporting application client secret>
WRITER_ID=<fulfillment application client ID>
WRITER_SECRET=<fulfillment application client secret>

The issuer must match the token’s iss claim exactly, including any trailing slash, so copy it from a decoded token.

Step 2: Create the JWT authorizer

Create a REST API, then describe the authorizer in a file that lists the trusted issuers, the audiences accepted from each, and the signing algorithms you configure on your issuer:

API_ID=$(aws apigateway create-rest-api \
  --name orders \
  --region "$REGION" \
  --query 'id' --output text)

cat > jwt-config.json <<EOF
{
  "issuers": [
    {
      "issuer": "${ISSUER}",
      "audiences": ["${AUDIENCE}"]
    }
  ],
  "defaultAlgorithms": ["RS256"]
}
EOF

AUTHORIZER_ID=$(aws apigateway create-authorizer \
  --rest-api-id "$API_ID" \
  --name orders-jwt \
  --type JWT \
  --identity-source method.request.header.Authorization \
  --jwt-configuration file://jwt-config.json \
  --region "$REGION" \
  --query 'id' --output text)

When you create or update the authorizer, API Gateway reads each issuer’s discovery document and checks that its issuer value matches. If your provider signs with an elliptic curve key, add ES256 or another supported algorithm to defaultAlgorithms. Keep jwt-config.json for step 7.

Step 3: Attach the authorizer to methods with different scopes

Create the /orders resource and two methods that share the authorizer but require different scopes. A mock integration returns the issuer and subject from the validated token:

ROOT_ID=$(aws apigateway get-resources --rest-api-id "$API_ID" \
  --region "$REGION" --query 'items[?path==`/`].id' --output text)

RESOURCE_ID=$(aws apigateway create-resource --rest-api-id "$API_ID" \
  --parent-id "$ROOT_ID" --path-part orders \
  --region "$REGION" --query 'id' --output text)

add_method () {
  aws apigateway put-method --rest-api-id "$API_ID" --resource-id "$RESOURCE_ID" \
    --http-method "$1" \
    --authorization-type JWT \
    --authorizer-id "$AUTHORIZER_ID" \
    --authorization-scopes "$2" \
    --region "$REGION"

  aws apigateway put-integration --rest-api-id "$API_ID" --resource-id "$RESOURCE_ID" \
    --http-method "$1" --type MOCK \
    --request-templates '{"application/json":"{\"statusCode\": 200}"}' \
    --region "$REGION"

  aws apigateway put-method-response --rest-api-id "$API_ID" --resource-id "$RESOURCE_ID" \
    --http-method "$1" --status-code 200 --region "$REGION"

  aws apigateway put-integration-response --rest-api-id "$API_ID" --resource-id "$RESOURCE_ID" \
    --http-method "$1" --status-code 200 \
    --response-templates '{"application/json":"{\"issuer\":\"$context.authorizer.claims.iss\",\"subject\":\"$context.authorizer.claims.sub\"}"}' \
    --region "$REGION"
}

add_method GET  orders:read
add_method POST orders:write

Step 4: Deploy the API

Deploy the API to a stage named test and record the invoke URL:

aws apigateway create-deployment --rest-api-id "$API_ID" \
  --stage-name test --region "$REGION"

API_URL="https://${API_ID}.execute-api.${REGION}.amazonaws.com/test/orders"

Step 5: Test the failure cases first

Call the API without a token:

curl -s -o /dev/null -w "%{http_code}\n" "$API_URL"

The request returns 401, because API Gateway rejects it before the integration runs.

Next, use a token for the reporting application, which has only orders:read, to create an order. The get_token helper sends an OAuth 2.0 client credentials request:

get_token () {
   local url="$1" client_id="$2" client_secret="$3" scope="$4" audience="$5"
   local args=(
      -sS -X POST "$url"
      -u "$client_id:$client_secret"
      -H "Content-Type: application/x-www-form-urlencoded"
      --data-urlencode "grant_type=client_credentials"
    )
   [[ -n "$scope"    ]] && args+=(--data-urlencode "scope=$scope")
   [[ -n "$audience" ]] && args+=(--data-urlencode "audience=$audience")

   curl "${args[@]}" | jq -r .access_token
}

# Auth0 requires the audience parameter. Okta ignores it.
READER_TOKEN=$(get_token "$TOKEN_URL" "$READER_ID" "$READER_SECRET" "orders:read" "$AUDIENCE")

curl -s -o /dev/null -w "%{http_code}\n" -X POST \
  -H "Authorization: Bearer $READER_TOKEN" "$API_URL"

The request returns 403. The token is valid, but POST /orders requires orders:write.

Step 6: Test the successful cases

Read orders with the reporting token, then request a token for the fulfillment application and create an order:

curl -s -H "Authorization: Bearer $READER_TOKEN" "$API_URL"

WRITER_TOKEN=$(get_token "$TOKEN_URL" "$WRITER_ID" "$WRITER_SECRET" "orders:write" "$AUDIENCE")
curl -s -X POST -H "Authorization: Bearer $WRITER_TOKEN" "$API_URL"

Both calls return 200 with the issuer and subject that the integration received:

{"issuer":"https://example.us.auth0.com/","subject":"0oa1b2c3d4EXAMPLE"}

Step 7: Add Amazon Cognito as a second issuer

An authorizer can trust up to 10 issuers, for example while you migrate between identity providers. In this step, you add a Cognito user pool to the same authorizer.

Create a user pool, a domain for its token endpoint, a resource server with the two scopes, and one machine-to-machine client:

DOMAIN_PREFIX=<a globally unique prefix, for example orders-demo-1234>

POOL_ID=$(aws cognito-idp create-user-pool --pool-name orders-demo \
  --region "$REGION" --query 'UserPool.Id' --output text)

aws cognito-idp create-user-pool-domain --user-pool-id "$POOL_ID" \
  --domain "$DOMAIN_PREFIX" --region "$REGION"

aws cognito-idp create-resource-server --user-pool-id "$POOL_ID" \
  --identifier orders --name orders \
  --scopes ScopeName=orders:read,ScopeDescription="Read orders" \
           ScopeName=orders:write,ScopeDescription="Create orders" \
  --region "$REGION"

read -r COGNITO_ID COGNITO_SECRET <<< "$(aws cognito-idp create-user-pool-client \
  --user-pool-id "$POOL_ID" --client-name legacy-reporting --generate-secret \
  --allowed-o-auth-flows client_credentials --allowed-o-auth-flows-user-pool-client \
  --allowed-o-auth-scopes orders/orders:read \
  --region "$REGION" \
  --query 'UserPoolClient.[ClientId,ClientSecret]' --output text)"

COGNITO_ISSUER="https://cognito-idp.${REGION}.amazonaws.com/${POOL_ID}"

Add the user pool to jwt-config.json and send the full file back, because an update replaces the whole configuration. Cognito access tokens carry the app client ID in client_id rather than aud, so use the client ID as the audience:

jq --arg iss "$COGNITO_ISSUER" --arg aud "$COGNITO_ID" \
  '.issuers += [{issuer: $iss, audiences: [$aud]}]' \
  jwt-config.json > jwt-config.tmp && mv jwt-config.tmp jwt-config.json

aws apigateway update-authorizer \
  --rest-api-id "$API_ID" \
  --authorizer-id "$AUTHORIZER_ID" \
  --patch-operations "$(jq -n --rawfile v jwt-config.json \
      '[{op:"replace",path:"/jwtConfiguration",value:$v}]')" \
  --region "$REGION"

The following screenshot shows the updated authorizer in the API Gateway console, with the key set that API Gateway resolved for each issuer.

API Gateway console authorizer page listing two trusted issuers with the key set resolved for each.

Figure 2: JWT authorizer with two trusted issuers

If you no longer have the jwt-config.json file, rebuild it from get-authorizer and remove the jwksUri fields, because API Gateway rejects an update that includes them:

aws apigateway get-authorizer --rest-api-id "$API_ID" --authorizer-id "$AUTHORIZER_ID" \
  --query jwtConfiguration --output json --region "$REGION" \
  | jq 'del(.issuers[].jwksUri)' > jwt-config.json

Cognito names scopes {resource server}/{scope}, so its token carries orders/orders:read rather than orders:read. Add that form to GET /orders, then redeploy, because authorizer and method changes take effect only in a new deployment:

aws apigateway update-method --rest-api-id "$API_ID" --resource-id "$RESOURCE_ID" \
  --http-method GET \
  --patch-operations op=add,path=/authorizationScopes,value=orders/orders:read \
  --region "$REGION"

aws apigateway create-deployment --rest-api-id "$API_ID" \
  --stage-name test --region "$REGION"

COGNITO_TOKEN=$(get_token "https://${DOMAIN_PREFIX}.auth.${REGION}.amazoncognito.com/oauth2/token" \
  "$COGNITO_ID" "$COGNITO_SECRET" "orders/orders:read")

curl -s -H "Authorization: Bearer $COGNITO_TOKEN" "$API_URL"

The request returns 200 with the Cognito issuer, and tokens from your original provider keep working. For Cognito issuers, a method with scopes accepts only access tokens and a method without scopes accepts only ID tokens. Give each method that client credentials callers use at least one scope.

To finish a migration, remove the retired issuer from jwt-config.json, send the same replace operation (using aws apigateway update-authorizer --patch-operations command), and redeploy.

Optional: Require an additional claim

To accept only tokens whose department claim equals eng, add a claim rule to the issuer entry. Matching is exact and case-sensitive, and API Gateway returns a 403 for other tokens:

{
  "issuer": "https://example.auth0.com/",
  "audiences": ["api://default"],
  "additionalClaims": [
    { "claimName": "department", "format": "SINGLE_STRING", "required": true, "expectedValues": ["eng"] }
  ]
}

Defining JWT authorizers as infrastructure as code

In AWS CloudFormation, the AWS::ApiGateway::Authorizer resource has a JwtConfiguration property that mirrors the API, and methods set AuthorizationType: JWT and AuthorizationScopes:

Parameters:
  IdpIssuer:
    Type: String
    Description: Issuer URL exactly as it appears in the token's iss claim
  IdpAudience:
    Type: String

Resources:
  OrdersAuthorizer:
    Type: AWS::ApiGateway::Authorizer
    Properties:
      RestApiId: !Ref OrdersApi
      Name: orders-jwt
      Type: JWT
      IdentitySource: method.request.header.Authorization
      JwtConfiguration:
        DefaultAlgorithms: [RS256]
        Issuers:
          - Issuer: !Ref IdpIssuer
            Audiences: [!Ref IdpAudience]

  GetOrders:
    Type: AWS::ApiGateway::Method
    Properties:
      RestApiId: !Ref OrdersApi
      ResourceId: !Ref OrdersResource
      HttpMethod: GET
      AuthorizationType: JWT
      AuthorizerId: !GetAtt OrdersAuthorizer.AuthorizerId
      AuthorizationScopes: [orders:read]
      Integration:
        Type: MOCK
        RequestTemplates:
          application/json: '{"statusCode": 200}'

In OpenAPI 3.0 and Swagger 2.0 definitions, use the x-amazon-apigateway-authorizer extension with type: jwt:

components:
  securitySchemes:
    orders-jwt:
      type: apiKey
      name: Authorization
      in: header
      x-amazon-apigateway-authtype: jwt
      x-amazon-apigateway-authorizer:
        type: jwt
        jwtConfiguration:
          issuers:
            - issuer: https://example.auth0.com/
              audiences: [ "api://default" ]
            - issuer: https://login.microsoftonline.com/{tenantId}/v2.0
              audiences: [ "00000000-0000-0000-0000-000000000000" ]
          defaultAlgorithms: [ "RS256", "ES256" ]
paths:
  /orders:
    get:
      security:
        - orders-jwt: [ "orders:read" ]

You can also convert an existing Lambda or Cognito authorizer in place with one update-authorizer command that changes /type, replaces /jwtConfiguration, and clears the old type’s fields. Clear Lambda fields with a replace that has no value, and remove each Cognito provider ARN with remove. Then switch each method that uses the authorizer to authorizationType: JWT, add its scopes, and redeploy.

Using claims in your integration

API Gateway passes every JWT claim to your backend as JSON as it appeared in the token. Strings stay quoted and escaped, numbers stay numbers, and arrays and objects stay intact, so your backend never has to guess what was sent. Mapping templates read validated claims as $context.authorizer.claims.name, as with Cognito authorizers, and Lambda proxy integrations receive them in event.requestContext.authorizer.claims.

HTTP proxy integrations don’t forward claims automatically, so map the ones you need to headers, for example integration.request.header.x-caller to context.authorizer.claims.sub.

Observability and troubleshooting

When API Gateway rejects a request, the response body is Unauthorized or The incoming token has expired for a 401, and Access Denied for a 403. A WWW-Authenticate header that follows RFC 6750 carries the details, such as the failed check or, for a missing scope, the scopes the method accepts.

With execution logging on, API Gateway logs a claims summary for each request, without the raw token. Data trace logging masks the Authorization header but not custom headers, so if your identity source is a header such as X-Token, keep data trace logging off for that stage.

To test an authorizer before you deploy, choose Test authorizer on the authorizer page or run test-invoke-authorizer. The test skips method scopes and accepts Cognito identity tokens, so call the deployed method to test scopes.

Considerations

Before you add a JWT authorizer, consider the following:

  • An authorizer trusts 1–10 issuers. Each issuer accepts 1–100 audiences and up to 10 additional claim rules, each with at most one expected value.
  • Supported signing algorithms are RS256, RS384, RS512, ES256, ES384, and ES512, and API Gateway rejects HMAC and alg: none tokens. The token header must carry a kid, which some providers omit by default.
  • API Gateway allows 60 seconds of clock skew when it checks exp, nbf, and iat.
  • API Gateway caches each issuer’s signing keys for about 60 minutes, so a key your provider removes can still verify tokens for that long. If the key endpoint is unavailable, API Gateway keeps using the last key set for up to 1 hour.
  • A token passes a method’s scope check when its scope or scp claim carries one of the method’s scopes. Microsoft Entra ID client credentials tokens carry permissions in roles instead, so use a dedicated audience per caller or a Lambda authorizer for role checks.
  • An authorizer reads the token from a single request header.
  • JWT authorizers don’t check revocation, so a token stays valid until it expires. Use short token lifetimes for sensitive operations.
  • The issuer URL must be publicly accessible.

Clean up

To avoid incurring future charges, delete the resources you created:

aws apigateway delete-rest-api --rest-api-id "$API_ID" --region "$REGION"

aws cognito-idp delete-user-pool-domain --user-pool-id "$POOL_ID" \
  --domain "$DOMAIN_PREFIX" --region "$REGION"

aws cognito-idp delete-user-pool --user-pool-id "$POOL_ID" --region "$REGION"

rm -f jwt-config.json

In your identity provider, delete the two applications and the orders API or resource server if you no longer need them.

Conclusion

With JWT authorizers, you can validate tokens from OIDC-compatible identity providers in API Gateway REST APIs without a function in the request path. In this post, you built an API that accepted machine-to-machine tokens from your own provider, enforced separate read and write scopes, and added a Cognito user pool as a second issuer. Lambda authorizers remain the right tool for custom authorization logic. For token validation alone, we recommend the JWT authorizer.

JWT authorizers for REST APIs are available in all commercial AWS Regions, the AWS GovCloud (US) Regions, and the China Regions. To get started, refer to Controlling access to a REST API using JWT authorizers in the Amazon API Gateway Developer Guide. To learn more about serverless architectures, visit Serverless Land.

 


About the authors

Giedrius Praspaliauskas

Giedrius Praspaliauskas

Giedrius is a Specialist Solutions Architect at Amazon Web Services, focusing on helping customers modernize their infrastructure and adopt cloud-native architectures. He has extensive experience with API management, microservices, serverless, developer experience, and application modernization.

Srijan Bhattacharya

Srijan Bhattacharya

Srijan Bhattacharya is a Senior Product Manager – Technical at AWS on the Amazon API Gateway team, based in Toronto. He works with customers to shape features across API security, observability, traffic management, integrations, and extensibility.

Using the AWS RMiT workbook and ISO Compliance Guides to support your BNM submissions

Post Syndicated from Jonathan Jenkyn original https://aws.amazon.com/blogs/security/using-the-aws-rmit-workbook-and-iso-compliance-guides-to-support-your-bnm-submissions/

Your next Bank Negara Malaysia (BNM) notification submission needs auditable evidence of how Amazon Web Services (AWS) controls align with Risk Management in Technology (RMiT) requirements. Two resources now exist to support that work: the AWS Workbook for BNM RMiT and the compliance guides published by AWS Security Assurance Services (AWS SAS).

The AWS Workbook for BNM RMiT, available through AWS Artifact, maps each RMiT provision to AWS Control Objectives (AWS responsibilities under the AWS Shared Responsibility Model) and AWS Well-Architected Framework best practices (your responsibilities). It tells you, for every RMiT requirement, what AWS is responsible for and what you implement.

The compliance guides published by AWS SAS over the past year provide implementation guidance for International Organization for Standardization (ISO) and International Electrotechnical Commission (IEC) standards that complements the workbook. These guides show how to implement controls that meet the requirements of specific standards and frameworks using AWS services, giving your technical and compliance teams a clear path from regulatory expectation to deployed architecture.

Malaysian financial institutions can now trace from BNM regulatory requirement, through AWS control implementation, to the evidence that demonstrates it: AWS third-party attestations for AWS-side controls, and your own workload evidence for customer-side controls. BNM expects this specificity in notification documentation.

AWS Workbook for BNM RMiT

The workbook is a structured Excel document available through AWS Artifact. For each of the 394 RMiT provisions, it identifies:

  • Whether the requirement is an AWS responsibility or a customer responsibility under the Shared Responsibility Model
  • The specific AWS Control Objective that addresses the requirement (where AWS is responsible)
  • The relevant AWS Well-Architected Framework best practice for customer implementation (where the customer is responsible)
  • Supporting information and references for each mapping

The following is a sample entry from the workbook:

RMiT Requirement Responsibility Source AWS supporting information
10.49: A financial institution should ensure network resilience… AWS AWS Control Objectives AWS Control Section: Network Security. AWS maintains redundant network connectivity with multiple tier-1 transit providers across each Availability Zone.
10.49: (Customer responsibility) Customer Well-Architected REL 2: How do you plan your network topology? Implement multi-AZ deployments. Configure VPC flow logs and use AWS Network Firewall.

The workbook currently includes 394 rows across all RMiT appendix requirements, with 208 mapped to AWS responsibilities and 186 to customer responsibilities.

Why this matters now

BNM revised RMiT guidelines effective 28 November 2025, and updated them on 25 September 2026 to add requirements for National Critical Information Infrastructure (NCII) entities. Financial institutions operating under both BNM Outsourcing and BNM RMiT must demonstrate that their cloud service providers maintain controls aligned with regulatory expectations. Institutions preparing notification submissions for material cloud workloads need auditable evidence of this alignment.

The revised guidelines set higher expectations for evidence quality. Institutions submitting notifications without clear, structured control mapping evidence might face extended review cycles and requests for additional information from BNM. Workloads that could be deployed in weeks remain in governance queues for months when supporting documentation lacks the specificity regulators expect.

Compliance guides from AWS Security Assurance Services

Start with the RMiT workbook to identify which provisions AWS addresses and which you implement. Then use the following compliance guides to design and implement your customer-side controls. The guides are implementation guidance for your teams. Audit evidence comes from two places. For AWS-side controls, use AWS third-party attestations, such as ISO certificates and System and Organization Controls (SOC) reports, available in AWS Artifact. For your workload, use evidence from your own environment, including configurations, logs, and AWS Config conformance pack results. Auditors can also use the guides as a reference for how a control is typically implemented on AWS.

AWS SAS has published five compliance guides over the past year. Each guide provides control-level implementation guidance on the customer side of the Shared Responsibility Model, showing how AWS services can be configured to meet the requirements of specific standards and frameworks. These guides were written by AWS SAS practicing security assessors and auditors holding Payment Card Industry Qualified Security Assessor (PCI QSA), Certified Information Systems Security Professional (CISSP), Certified Information Security Manager (CISM), ISO 27001 Lead Auditor, and Certified Cloud Security Professional (CCSP) certifications, drawing on experience from hundreds of cloud security assessments across financial services globally.

The following is the list of guides AWS SAS practicing auditors have published, which include control mapping information relevant to BNM RMiT:

How these resources work together

A Malaysian financial institution preparing a BNM notification can use these resources together:

  • The RMiT workbook identifies which RMiT provisions are AWS responsibilities and which are customer responsibilities.
  • For AWS responsibilities, the workbook references the specific AWS Control Objective.
  • AWS third-party reports in AWS Artifact, such as the AWS ISO/IEC 27001 certificate and SOC reports, attest to those AWS Control Objectives. For customer responsibilities, the ISO compliance guides show how to implement the corresponding controls using AWS services.
  • The ISO 31000 guide can inform the risk management methodology you apply to your cloud workloads.
  • AWS Config Conformance Packs for BNM RMiT provide automated, continuous monitoring of deployed controls.

Resources also supporting this approach:

Compliance teams across Association of Southeast Asian Nations (ASEAN) financial services have already begun referencing the AWS Guide to BNM RMiT and associated resources in their cloud risk assessment processes and BNM notification documentation.

Looking ahead: AI governance

For institutions deploying generative AI and machine learning, ISO/IEC 42001:2023 (Artificial Intelligence Management Systems) is relevant to BNM technology governance expectations. In November 2024, AWS became the first major cloud provider to announce ISO/IEC 42001 certification for AI services. AWS passed its first surveillance audit in November 2025 with zero findings. The ISO 42001 compliance guide published in May 2026 supports institutions building their own responsible AI systems on their side of the AWS Shared Responsibility Model.

How to get started

  • Access the RMiT workbook through AWS Artifact and review with your compliance lead to identify which provisions apply to your material cloud workloads.
  • Download the relevant ISO compliance guides to plan how you implement your customer-side controls. Download AWS ISO certificates and SOC reports from AWS Artifact for AWS-side evidence.
  • Map your workload-specific controls using the workbook as the RMiT baseline and the ISO guides as implementation guidance.
  • Implement automated compliance monitoring using the BNM RMiT conformance pack for AWS Config to maintain continuous visibility over your control posture.
  • Engage your AWS account team or AWS SAS for additional guidance on implementing customer-side controls referenced in the workbook.

As BNM updates its regulatory expectations, AWS will update these resources to reflect revised requirements. Subscribe to the AWS Security Blog for update notifications.

Additional resources

If you have questions about this post, contact AWS Support or start a new thread on AWS re:Post.


Jonathan-Jenkyn

Jonathan Jenkyn

Jonathan (JJ) is a Senior Security and Compliance Solutions Architect with AWS Security Assurance Services and a published cybersecurity author. He has over 30 years of experience across penetration testing, incident response, cyber resilience, and security governance. He helps customers build practical security programs. He champions disability inclusion and neurodiversity at Amazon. Outside work, he runs, cycles, swims, and enjoys family time.

Matthew Nixon

Matthew Nixon

Matt is a Principal in the AWS Asia Financial Services Security and Compliance team. He has 20 years of experience in technology risk, audit, and information security, including leading a cloud risk team in financial services. Matt co-founded an award-winning AI/ML startup, authored books on IT and cloud risk, and won the Singapore ISACA 2024 IT Risk Leader Award.

Four Continents, Four New AWS Heroes: Closing Out 2026

Post Syndicated from Taylor Jacobsen original https://aws.amazon.com/blogs/aws/four-continents-four-new-aws-heroes-closing-out-2026/

As AWS re:Invent is around the corner, we’re proud to recognize a new group of AWS Heroes. Every Hero finds their own way to give back, whether through sharing what they know, bringing people together, or building tools that help others succeed. What they have in common is a genuine commitment to supporting the builders around them learn, grow, and lead.

Let us take a moment to meet them!

Andres Moreno – El Paso, United States

Serverless Hero Andres Moreno leads the Cloud del Norte AWS User Group and is a former AWS Community Builder. On his blog, And More Dev, and at conferences and community events, he explains serverless, cloud native architectures, generative AI, and agentic systems in ways that make new technology easier to try. Andres puts special energy into supporting builders across Latin America and helping them explore what’s possible on AWS.

Geethika Guruge – Auckland, New Zealand

Community Hero Geethika Guruge is a Principal Consultant at Mantel Group whose work spans serverless, DevOps, cloud infrastructure, and agentic AI. Geethika has shared real lessons from building agentic applications and leading large migration and modernization programs at AWS re:Invent, AWS Summits, and AWS Community Days. At home in Auckland, Geethika organizes local AWS meetups that encourage grassroots innovation and mentors the next generation of cloud architects and leaders.

Jéssica Cristina Coelho – Belo Horizonte, Brazil

Data Hero Jéssica Cristina Coelho is a Database Reliability Engineer and a former AWS Community Builder with more than 15 years of experience in databases, cloud, and data engineering. She leads the AWS User Group in Minas Gerais, hosts DataTalks Brasil, teaches MBA courses, and supports Women in Cloud, DevOpsDays, and AWS Community Day events. She speaks at events such as AWS Summit São Paulo and Web Summit Rio on database modernization and generative AI. At AWS re:Invent 2025, she was recognized as a LATAM Diversity & Inclusion Champion.

Kazuho Cryer Shinozuka – Tokyo, Japan

DevTools Hero Kazuho Cryer Shinozuka is an AWS CDK Top Contributor and Trusted CDK Community Reviewer. With 200 merged pull requests, he ranks 18th among more than 1,700 contributors. He has reviewed more than 120 pull requests, has been involved in about 2% of all CDK commits, and has published 10 construct libraries, along with tools such as cfn idle cost. Through talks at JAWS DAYS and CDK Conference Japan and through hands on contribution workshops, he helps more developers in Japan start contributing to open source.

Learn More

To connect with these Heroes or find one in your region, explore the AWS Heroes webpage, and join the conversation on AWS Builder Center.

— Taylor

Deliver petabytes of Apache Kafka data to Amazon S3 at up to 60% lower cost with Amazon MSK Express brokers

Post Syndicated from Diksha Dubey original https://aws.amazon.com/blogs/big-data/deliver-petabytes-of-apache-kafka-data-to-amazon-s3-at-up-to-60-lower-cost-with-amazon-msk-express-brokers/

Amazon Managed Streaming for Apache Kafka (Amazon MSK) Express brokers deliver Apache Kafka topic data to general purpose Amazon Simple Storage Service (Amazon S3) buckets at lower cost and without the operational overhead of running Kafka Connect. Because Express brokers handle both ingestion and delivery, you can reduce your ingestion and delivery costs by up to 60% compared to self-managed alternatives. There is no connector or infrastructure to manage, you pay only for the data delivered, and delivery doesn’t consume broker throughput.

Many Kafka workloads need a durable copy at rest in Amazon S3 for backup and archive. Compliance rules often require you to keep raw events for years for audits. You require a replayable copy that outlives topic retention, raw training data for artificial intelligence and machine learning (AI/ML) models, and a staging area for scheduled extract, transform, and load (ETL) jobs. For analytics, Express brokers also deliver to streaming tables, which continuously materialize your Kafka topics as Apache Iceberg tables on Amazon S3 Tables, a capability of Amazon S3, with no Kafka connectors, Apache Flink jobs, or custom consumers to run. The tables are registered automatically in AWS Glue Data Catalog, so you can query them with Amazon Athena, Amazon Redshift, and Apache Spark, and inline compaction reduces downstream query costs by up to 30%. Because delivery doesn’t add broker load, one topic can feed both an S3 bucket and a streaming table. For more information, see Deliver Apache Kafka data to streaming tables for Apache Iceberg with Amazon MSK Express brokers.

In this post, we look at the two challenges of delivering Kafka data to Amazon S3 today, managing Kafka brokers and managing the delivery pipeline, and how Express brokers and data delivery to Amazon S3 address each one. We then walk through the architecture and show how to get started on the console and with Agent Skills.

Challenges with delivering streaming data to Amazon S3 on self-managed Kafka

To deliver Kafka data to Amazon S3 today, you typically run an S3 sink connector on Kafka Connect next to your Kafka cluster. That leaves you with two systems to run:

Managing Kafka brokers: You size and provision broker storage upfront, monitor its utilization to avoid disruptions, and keep paying for it even if your workload scales down. You recover failed brokers, manage Kafka configurations for availability and performance, and patch brokers during maintenance windows. Adding capacity means provisioning brokers and rebalancing partitions, which can take hours or days, so you size the cluster for peak traffic and plan scaling well ahead.

Managing the delivery pipeline: Running Kafka Connect typically causes the following three challenges:

  • Operational complexity: You find or build a connector, take it through security approval, deploy it, and apply security updates across your Kafka Connect workers. When delivery fails, you troubleshoot across brokers, workers, and Amazon S3.
  • Cost: You size Kafka Connect workers for peak demand and keep paying for it when traffic is low, and a pipeline assembled from several services adds a charge at every hop.
  • Contention with real-time consumers: A connector reading from a Kafka topic consumes broker egress throughput, so feeding the archive competes with your real-time applications. Cluster scaling and version upgrades can also interrupt delivery.

How Express brokers and data delivery to Amazon S3 address these challenges

Managing Kafka brokers: Express brokers include pay-as-you-go storage that scales automatically, so there’s no storage to size, provision, or monitor. When your workload scales down, the cluster uses less storage and your storage charges go down automatically. MSK recovers failed brokers for you, manages critical cluster and topic configurations for availability and performance on your behalf, and updates cluster hardware on an ongoing basis with no maintenance windows. To add capacity, you add brokers, and Express rebalances partitions onto them in minutes, so you don’t need to over-provision for traffic spikes or plan scaling far ahead. For details, see Simplifying Kafka operations with Amazon MSK Express brokers. To move from self-managed or third-party Kafka, Amazon MSK Replicator copies your data and consumer group offsets into an Express cluster, and the migrate-to-msk Agent Skill recommends a right-sized Express cluster before you start. For more information, see Migrate Kafka workloads to an Amazon MSK cluster.

Managing the delivery pipeline: Data delivery to Amazon S3 is built into Express brokers, so there’s no Kafka Connect to run. You create a channel on a topic, and MSK runs the delivery. This addresses each of the three challenges:

  • Operational complexity: There’s no connector to find, build, or take through security approval, nothing to deploy beyond the channel, and no workers to patch. MSK handles retries and backpressure. When a record can’t be processed, the channel writes its identifiers and error context to a dead-letter queue (DLQ) bucket and delivery continues, and you troubleshoot in one place, through the channel’s Amazon CloudWatch metrics and logs.
  • Cost: There’s no capacity to size for peak, because MSK scales delivery with your workload. You pay only for the data delivered, billed per byte, so you pay less when traffic is low. Delivery adds one charge on top of standard Amazon S3 charges, with no connector or worker fees, no charge for the broker egress that delivery uses, and no charge for records routed to the DLQ.
  • Contention with real-time consumers: The channel reads the topic without consuming broker throughput, so archiving doesn’t compete with your real-time applications, and you can add channels to a topic without adding broker load. Capacity scaling and version upgrades happen without delivery gaps.

MSK data delivery to Amazon S3 architecture

Producers write to a Kafka topic exactly as they do today. The channel reads records from the topic, batches them, and writes them as objects to your S3 bucket. You choose the compression (NONE, GZIP, or ZSTD), the storage class (S3 Standard, S3 Intelligent-Tiering, or S3 Glacier Instant Retrieval), and an output key template that defines the object key layout, such as date-based prefixes with the partition and offset in each object name. Records keep the format the producer wrote them in, whether JSON, UTF-8 strings, or raw bytes, and no schema registry is required.

For JSON and String records, the channel validates each record. If a record fails validation, the channel writes the record’s identifiers and the error context to the DLQ bucket in Amazon S3, and delivery continues. You can also send delivery logs to Amazon CloudWatch Logs, Amazon S3, or Amazon Data Firehose.

The following diagram illustrates this architecture.

Architecture diagram of Amazon MSK Express brokers delivering a Kafka topic to a general purpose S3 bucket and to Apache Iceberg streaming tables on Amazon S3 Tables

Figure 1: Producers publish to a Kafka topic on Amazon MSK Express brokers. Data delivery writes the topic to a general purpose S3 bucket as objects in their source format, which you can use for backup and archival, compliance retention, replay beyond topic retention, AI/ML model training, and scheduled ETL jobs. Streaming tables write the same topic to Apache Iceberg tables on Amazon S3 Tables, registered in AWS Glue Data Catalog, so you can bring your own engine for query and analytics, such as Amazon Athena, Amazon Redshift, Apache Spark on Amazon EMR, or AI agents built with Amazon Bedrock. No connector runs between the cluster and Amazon S3

Before you plan your deployment, review Requirements and supported configurations in the Amazon MSK Developer Guide for supported Regions, accounts, and configurations.

Getting started

To get started, open the Amazon MSK console, choose your Express broker cluster, and create a channel on the Channel tab with data delivery to general purpose S3 as the destination type. For step-by-step instructions, see Create your first Channel. Before you deploy to production, review the prerequisites, supported configurations, service execution role, output key template, and recommended alarms in the Amazon MSK Developer Guide.

If you’re moving from an existing connector, create the channel before you retire the connector, and keep both running until you confirm that the delivered data overlaps.

You can also manage channels with the Amazon MSK APIs and the AWS Command Line Interface (AWS CLI) (for example, aws kafka create-channel) through infrastructure as code or automation across many clusters and topics, or let an AI agent do it for you, as the next section shows.

Getting started with Agent Skills

AWS publishes open source Agent Skills, available through the Agent Toolkit for AWS, that give AI coding agents guidance for configuring delivery on services. The managing-amazon-msk skill covers data delivery to Amazon S3 on an Express broker cluster. The skills guide your agent through the setup steps that are easy to get wrong: the IAM role and trust policy, output key template rules, DLQ setup, and verifying delivery after the channel is running.

Installing as an Agent Skill

Skills are discovered automatically by compatible tools through the SKILL.md file. Follow the Agent Toolkit installation guide, then add the skill for the service you are working with:

aws configure agent-toolkit
aws agent-toolkit add-skill --skill-name managing-amazon-msk

We also recommend installing the AWS MCP Server, which gives your agent tools for searching AWS documentation, blogs, and Skills dynamically at runtime. This makes both discovery and installation more flexible, and the agent itself more accurate. To verify the installation, interact with the skill in your preferred tool.

To begin delivery, prompt your agent of choice. For Amazon MSK, “Set up data delivery from my orders topic to my archive bucket”:

Screenshot of an agent chat with a prompt to set up data delivery from a topic to an archive bucket

Figure 2: Issuing the delivery prompt in an agent chat

The agent first dynamically loads the relevant skill, inventories the clusters, topics, and buckets available in your account. It then confirms the resources to use or create before creating the delivery configuration. After creation, the agent summarizes the status and can help with the data operations that follow, such as setting up an AWS Glue crawler so the delivered objects are queryable as partitioned tables in Amazon Athena, or configuring CloudWatch alarms on delivery freshness and dead-letter queue activity.

Screenshot of the agent reporting that it created the delivery channel

Figure 3: The agent creates the channel

Clean up

To avoid ongoing charges, delete the resources you created for this walkthrough. An active channel keeps delivering records and incurring delivery charges until you delete it. On Amazon MSK, open your cluster in the Amazon MSK console, choose the Channel tab, and delete the channel. Objects already written to Amazon S3 keep incurring storage charges after the channel is deleted, so delete the delivered objects, and the destination and DLQ buckets if you no longer need them. Finally, delete the IAM service execution role and any CloudWatch log groups created for the channel, including any that your agent created.

Conclusion

With data delivery to Amazon S3 on Amazon MSK, you can keep a durable copy of your streaming data in Amazon S3 without running a connector. You pay only for data that is delivered, and delivery doesn’t compete with your real-time consumers for throughput.

To learn more, see Amazon MSK data delivery to Amazon S3 in the Amazon MSK Developer Guide. For pricing, see Amazon MSK pricing. If you want to query your streaming data as Apache Iceberg tables instead of raw objects, see Deliver Apache Kafka data to streaming tables for Apache Iceberg with Amazon MSK Express brokers.


About the authors

Diksha Dubey

Diksha Dubey

Diksha is a Senior Product Manager for Amazon MSK. She works with customers to run Apache Kafka at scale and turn their real-time data into files and tables that analytics engines and AI agents can use. Working backwards from their needs, she shapes how Amazon MSK gets streaming data to where customers use it, starting with Amazon S3 and Apache Iceberg tables. Her focus is on making Kafka data easy to store, query, and share across teams, without pipelines to build or run.

Subham Rakshit

Subham Rakshit

Subham is a Streaming Solutions Architect for Analytics at AWS based in the UK. He works with customers to design and build search and streaming data platforms that help them achieve their business objective. Outside of work, he enjoys spending time solving jigsaw puzzles with his daughters.

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

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

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

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

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

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

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

Solution overview

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

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

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

Prerequisites

Before starting, verify that you have the following:

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

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

Install the Migration Assistant CLI

Run the following command in your terminal:

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

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

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

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

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

migration-assistant

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

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

Select your preferred option to proceed with the migration.

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

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

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

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

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

Assessing a migration

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

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

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

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

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

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

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

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

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

Deploying the Migration Assistant infrastructure

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

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

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

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

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

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

Backfilling Solr data

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

“Run the backfill into my OpenSearch Serverless collection at”

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

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

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

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

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

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

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

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

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

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

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

Grant the target collection a data access policy

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

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

Secure the snapshot and capture bucket

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Validation and testing

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

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

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

Four lines worth reading carefully:

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

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

Running a query against your migrated data

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

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

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

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

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

The equivalent OpenSearch Query DSL:

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

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

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

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

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

Updating your application code

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

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

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

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

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

Bonus: Improve search relevance with Automatic Semantic Enrichment

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

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

Cost

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

Clean up

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

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

Conclusion

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

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

 


About the authors

Michael Torio

Michael Torio

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

Jon Handler

Jon Handler

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

Announcing updates to the AWS Well-Architected Framework

Post Syndicated from Haleh Najafzadeh original https://aws.amazon.com/blogs/architecture/announcing-updates-to-the-aws-well-architected-framework-3/

Today, we are announcing updates to the AWS Well-Architected Framework with new and improved guidance across its six pillars, Operational Excellence, Security, Reliability, Performance Efficiency, Cost Optimization, and Sustainability. The Framework now separates account- and organization-level best practices from workload best practices, so you can establish foundational guardrails in the environment where your workloads run. New best practices address secure coding, cyber resilience for backup data, generative AI for operational efficiency, and measuring resource efficiency, so the Framework reflects how teams build and operate in the cloud today.

A brief history

The AWS Well-Architected Framework is a collection of best practices that organizations of every size and industry use to design, build, and operate workloads that are secure, reliable, high-performing, cost-effective, sustainable, and straightforward to operate.

We launched the first version of the Framework in 2012. Since then, it has grown from a single set of guidance into a full body of architectural knowledge. We published the AWS Well-Architected Framework whitepaper, added the Operational Excellence pillar, and released pillar-specific whitepapers and AWS Well-Architected Lenses for specific technologies and industries. Next, we refreshed the Framework so that best practices became the core unit of guidance, and we added Sustainability as the sixth pillar. As customers began building with generative and agentic AI, we introduced new lenses to guide them. In 2026, the Framework continues to change to help customers build and run secure, resilient, efficient, and sustainable workloads in the cloud.

AWS Well-Architected guidance timeline, 2012 to 2026

Figure 1: AWS Well-Architected guidance timeline, 2012 to 2026.

What’s new

Customers tell us they value Well-Architected reviews and want a more efficient way to run them. Account- and organization-level best practices apply across the entire environment, so customers want to assess them once and then focus each review on the workload itself. To streamline reviews, this release organizes the Framework into two areas, Well-Architected Cloud Foundations and Well-Architected Cloud Workloads. As a result, a workload review covers only the best practices that apply to that workload, which makes it faster to run and automate.

Well-Architected Cloud Foundations covers environment-wide decisions, such as multi-account structure, identity, and cost governance. It sets the guardrails that every workload inherits, and you refine them as your environment matures. Well-Architected Cloud Workloads covers how you design, build, and operate each workload, including updated architecture patterns focused on specific business outcomes. In both areas, best practices are organized into capabilities, which are groups of related best practices that share a common objective.

This release focuses on technical architecture. As more teams use AI agents to run reviews, guidance is most useful when an agent can check it against how your environment and workloads are built and operated. Best practices centered on business strategy, people, and organizational processes depend on human judgment and context that are not captured by configuration or telemetry. Mixing these elements with technical guidance makes it more difficult to automate reviews. We retired these best practices, and AWS continues to offer guidance on these topics through other resources. Each remaining best practice now addresses a technical decision that you, or an agent acting on your behalf, can review and act on.

We also updated service references throughout the Framework, removing services that no longer accept new customers or have reached end of support, and adding guidance for services launched since the last release.

Well-Architected Cloud Foundations

Best practices for account- and organization-level decisions were previously spread across the Framework and reviewed for every workload. Well-Architected Cloud Foundations consolidates them into guidance you apply when you set up or mature your multi-account environment. Of the best practices in Well-Architected Cloud Foundations, 33 come from moving or merging existing best practices from the Framework pillars.

We consolidated and rewrote the relocated best practices from an environment-wide perspective, then combined them with newly authored foundational guidance. That guidance includes new best practices for centralized event monitoring, an auditable cloud inventory record, and centralized DNS management. The result is 45 best practices across seven capabilities: Multi-account environment, Identity and access management, Central observability management, Resource and inventory management, Security and compliance, Cloud financial management, and Networking and connectivity.

Well-Architected Cloud Workloads

Well-Architected Cloud Workloads now has 216 best practices, down from 307, with no loss of technical coverage, so each workload review stays focused on its architecture decisions. Practices that apply across your environment moved into Well-Architected Cloud Foundations, practices with similar guidance were combined, and practices outside the technical scope of the Framework were retired.

Operational Excellence

Operational Excellence introduces new capabilities and best practices that follow the operations lifecycle, which covers observation, deriving insights, managing change flow, deployment, support, response, and evolution. It adds a new best practice for managing rollouts of external dependencies and expands guidance on using AI assistants and agents to instrument telemetry, draft dashboards, and investigate incidents, with validation against baselines and named human ownership at every step.

Security

Security moves account-wide concerns, such as root account protection, sign-in mechanisms, permission guardrails, emergency access, centralized logging, and forensic readiness, into the Identity and access management and Security and compliance capabilities of Well-Architected Cloud Foundations. Within Well-Architected Cloud Workloads, the pillar adds new best practices for centralized workload permissions management, detection metrics and dashboards, and secure coding guidelines.

Reliability

Reliability moves three networking best practices (IP subnet allocation, hub-and-spoke topologies, and non-overlapping address ranges) into the Networking and connectivity capability of Well-Architected Cloud Foundations, where they are consolidated into a single network strategy best practice. Within Well-Architected Cloud Workloads, the pillar adds a new best practice on cyber resilience for backup data, which helps protect backups against ransomware and other cyber threats.

Performance Efficiency

Performance Efficiency moves its best practice on policies and reference architectures into Well-Architected Cloud Foundations. Within Well-Architected Cloud Workloads, the pillar now focuses Architecture selection on validating your workload requirements and tracking them with key performance indicators (KPIs). It also combines related best practices, such as folding compute configuration into compute selection and load testing into workload performance evaluation.

Cost Optimization

Cost Optimization moves its best practices on account-level concerns, such as account structure, cost attribution, billing tools, and cost controls, into Well-Architected Cloud Foundations, where they form the core of the Cloud financial management capability. Within Well-Architected Cloud Workloads, the pillar combines overlapping best practices, such as merging its decommissioning guidance into a single resource lifecycle management best practice. It also adds a new best practice on using generative AI for operational efficiency.

Sustainability

Sustainability introduces new capabilities and best practices that follow how teams reduce workload impact, which covers measuring and monitoring, provisioning resources, improving workload efficiency, and optimizing data and processing. Based on customer feedback, earlier general guidance has been converted to best practices. It adds a new best practice for using the most resource-efficient computational approach, including using a less resource-intensive method or a smaller machine learning model where one meets the requirement. It expands guidance on combining resource usage efficiency metrics with carbon emissions data from the AWS Sustainability Console / API and AWS Data Exports, with baselines and targets that make progress measurable over time.

Call to action

AWS Well-Architected Framework is more than a set of best practices and tools for finding improvement opportunities. It is a mechanism that helps you strengthen governance and drive better outcomes across your organization. When you evaluate your architecture consistently against best practices, you build a culture of continuous improvement and address critical issues before they affect your workloads. Ready to get started? Explore the updated AWS Well-Architected Framework, soon to be available in 11 languages: English, Spanish, French, German, Italian, Japanese, Korean, Indonesian, Brazilian Portuguese, Simplified Chinese, and Traditional Chinese.


About the authors

Haleh Najafzadeh

Haleh Najafzadeh

Haleh is a Principal Solutions Architect on the AWS Well-Architected Solutions Innovation team, with more than 25 years of experience applying scientific techniques to challenging industrial problems. She shares technology best practices and helps customers architect and implement solutions at scale.

Nataliya Godunok

Nataliya Godunok

Nataliya is a Senior Solutions Architect at AWS, with more than 16 years of experience in tech, including 10 years working in cloud and AWS. She specializes in AWS Well-Architected, FinOps, and cloud cost optimization, and helps customers strengthen the architectural health of their workloads while building a lasting culture of cost awareness across their organizations. Nataliya also creates content and speaks at conferences, turning what she learns in the field into guidance others can use to build efficiently in the cloud.

Introducing enhanced snapshots for Amazon Managed Service for Apache Flink

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

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

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

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

Use cases

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

Support blue/green deployments for stateful applications

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

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

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

Disaster recovery in a second Region

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

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

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

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

How it works

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

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

Turn on enhanced snapshots

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

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

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

Start one application from another’s state

Create a snapshot of the running application:

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

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

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

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

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

Export and import

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

To export a snapshot:

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

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

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

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

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

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

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

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

Set up permissions

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

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

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

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

Now available

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

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

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

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

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

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

 


About the authors

Francisco Morillo

Francisco Morillo

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

Mayank Juneja

Mayank Juneja

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

AWS Weekly Roundup: AWS Nitro Sandboxes, AWS Emulator, and more (November 16, 2026)

Post Syndicated from Daniel Abib original https://aws.amazon.com/blogs/aws/aws-weekly-roundup-aws-nitro-sandboxes-aws-emulator-and-more-november-16-2026/

A second delivery of the same message can reveal more about an application than its happy-path demo. I like tools that make those cases easier to investigate while a change is still small. Last week’s launch of AWS Emulator brings part of that work onto your own machine: developers and coding agents can exercise AWS API interactions, inspect results, and try again without provisioning cloud resources for every attempt.

I wrote about the Emulator’s launch last week, and it’s my main highlight in this edition. There are also new ways to isolate workloads on shared infrastructure, give an agent narrowly scoped access to a backend, and prepare search applications for a regional disruption. Now, let’s get into this week’s AWS news…

Official AWS diagram showing application code, SDKs, CLI, and coding agents calling AWS Emulator on a laptop or CI environment, with a separate path for deployment to AWS.

AWS Emulator runs locally alongside your code and development tools. Image: AWS.

Headlines
Test your applications against AWS locally with AWS Emulator introduces a generally available local environment for AWS API interactions. Point the AWS CLI or AWS SDKs at its HTTPS endpoint, and your application keeps its normal SDK calls. The walkthrough shows a coding agent creating an Amazon DynamoDB table, writing an item, and reading it back. You don’t need an AWS account for emulated operations, and there is no additional service fee. The getting-started guide covers Linux packages, Docker for macOS and Windows, and agent-assisted setup; the source is on GitHub.

What I like is giving an agent concrete feedback while it works: run calls, inspect results, and revise the code. Matt Wood’s perspective on feedback for coding agents explores why that loop matters. Check the published fidelity results for your operations, because coverage varies and unimplemented calls return HTTP 501. The emulator doesn’t reproduce IAM and resource-policy enforcement or cross-account and cross-Region behavior, so test the complete application and its security configuration on AWS before production.

AWS Nitro Sandboxes bring hardware isolation to pods, tasks, and VMs. You can give an Amazon EKS pod or Amazon ECS task its own VM boundary while sharing an Amazon EC2 instance. That is useful for tenant workloads, build jobs, and agents executing generated code. Isolated mode separates workloads from their neighbors; confidential mode adds protection from node operators and cryptographic attestation. The Compute Blog deep dive explains both modes and their integrations. Nitro Sandboxes have no additional charge on supported instances; EC2 and applicable EKS Auto Mode or ECS Managed Instances fees still apply.

Last week’s launches
Here are some launches and updates from this past week that caught my attention:

Amazon Cognito supports OAuth 2.0 token exchange – You can now exchange a user’s token for one scoped to a downstream service in Amazon Cognito. The derived token can have narrower permissions and a single audience, with no refresh token; supplying an actor token also identifies the intermediary in an act claim. For an agent calling a backend on someone’s behalf, that makes delegation more explicit without forwarding the original token. The feature is available on Essentials and Plus plans in all Cognito Regions.

Claude Fable 5.2 is available on AWS – You can access the model through Amazon Bedrock or Claude Platform on AWS. Anthropic positions it as its most capable generally available model for technical work, including extended engineering tasks, scientific research, and quantitative finance. Bedrock has model-specific retention requirements: Fable 5.2 traffic is retained for up to 30 days for abuse detection, with a temporary zero-retention exception for eligible internal use.

Amazon ElastiCache Serverless adds search and aggregations – You can now combine vector, full-text, and hybrid search with server-side aggregations in Amazon ElastiCache Serverless for Valkey. That gives product discovery, recommendations, and agent-memory retrieval another option for querying frequently changing data. The capability requires Valkey 9, so create a compatible cache or upgrade an existing one. It is available in commercial Regions, AWS GovCloud (US), and the AWS European Sovereign Cloud.

Amazon OpenSearch Service adds managed cross-Region disaster recovery – You can now pair Amazon OpenSearch Service domains running version 3.7 or later in two Regions within one account. AWS specifies recovery objectives under one minute for data loss and under 20 minutes for recovery time. Planned switchovers preserve all writes; unplanned failovers can lose unreplicated data. The deep dive covers the remaining work: keeping configuration aligned and redirecting application writes after switching roles, plus secondary-domain and data-transfer charges.

Amazon CloudWatch Logs adds account-level retention policies – You can now set retention across all log groups or groups matching a name prefix in Amazon CloudWatch, with policies covering existing groups or only new ones. When policies overlap, the longest retention period applies. A platform team can set a baseline and retain security logs longer without updating every group individually. The feature has no additional charge and is available in commercial Regions except Middle East (Bahrain) and Middle East (UAE).

The next generation AgentCore runtime is now the default – New Amazon Bedrock AgentCore runtimes now use the next-generation runtime by default, so agent sessions start in under 2 seconds, scale up to 8 vCPU and 32 GB, scale to zero when idle, and bill up to 68% less memory, while each session still runs in its own isolated microVM.

For a full list of AWS announcements, be sure to keep an eye on the What’s New with AWS page.

Other AWS news
Here are some additional posts and resources that you might find interesting:

Optimizing cost per task and proving agent ROI on Amazon Bedrock – This guide follows an agent’s cost through repeated calls, reasoning, caching, and human review. I like its emphasis on measuring a completed task and comparing outcomes against a documented baseline. Its worked prices are illustrative; use your own workload and reconcile estimated costs with billing data.

How Zillow runs 100 million daily notifications on AWS Step Functions – Zillow describes reusable content modules and configuration-driven AWS Step Functions Express Workflows for more than 100 million daily notifications. The useful engineering details include idempotent modules, batching, campaign isolation, and testing expressions with the TestState API before deployment. Those patterns apply well beyond notification systems.

Upcoming AWS events
Check your calendar and sign up for upcoming AWS events:

AWS re:Invent – Join the community in Las Vegas from November 30 to December 4. Browse more than 2,200 sessions, including workshops and deep dives, or register for the free livestream to follow keynotes and selected sessions remotely.

AWS Community Days – Find community-led technical talks, workshops, and hands-on learning near you. Check each organizer’s page for current dates and registration details.

Join the AWS Builder Center to connect with builders, share solutions, and access content that supports your development. Browse here for upcoming AWS-led in-person and virtual events and developer-focused events.

That’s all for this week. Check back next Monday for another Weekly Roundup!

– Daniel Abib

This post is part of our Weekly Roundup series. Check back each week for a quick roundup of interesting news and announcements from AWS!

Amazon Threat Intelligence observes threat actors running cybercrime campaigns with Artex AI agents

Post Syndicated from CJ Moses original https://aws.amazon.com/blogs/security/amazon-threat-intelligence-observes-threat-actors-running-cybercrime-campaigns-with-artex-ai-agents/

From Oct. 3 to Nov. 5, 2026, Amazon’s MadPot, a globally distributed network of decoy threat sensors, captured requests from AI agents that included operating memory from offensive campaigns that threat actors ran on ARTEX, an open-source agentic AI penetration testing framework. The ARTEX agents sent these requests to MadPot sensors configured to present as popular large language model (LLM) inference APIs, and the requests carried the agents’ own records of their campaigns.

Amazon Threat Intelligence assessed threat activity referencing potentially affected AWS customers and notified them as appropriate. Because activity against other organizations could not be confirmed, this post shares the findings and indicators of compromise (IOCs) so that organizations that run the affected technologies can review their own environments.

The most prominent ARTEX campaign was a large-scale theft of credentials to access AI models, organized as a self-sustaining operation in which stolen keys paid for the LLM inference powering further credential hunting. Another campaign targeted cryptocurrency exchanges for know-your-customer (KYC) verification bypass using real-time deepfake injection. In aggregate, the agent records show that agentic frameworks have progressed from experimental use to sustained, multi-objective offensive operations that run with minimal human intervention. This post describes how these campaigns operated based on the agents’ own descriptions of the campaigns.

Attribution and instructions

Amazon Threat Intelligence assesses with moderate confidence that ARTEX was used for these campaigns due to prompt references to ARTEX tooling and other technical artifacts referencing ARTEX. Threat actors instructed ARTEX agents through standing instruction prompts that set the mission objectives, targeting rules, and operational constraints. Within those instructions, the agents handled the work themselves. In one credential theft campaign, operators told the agents to work through a fixed sequence of countries, prioritize enterprise production sites over personal projects, and grade every stolen credential by whether it worked and what it could reach. Agents were directed to treat credentials exposed publicly for more than 30 days as low-value inventory.

Amazon Threat Intelligence also assess with moderate confidence these are disparate Chinese-nexus threat groups due to use of simplified Chinese language in prompts, China time-zone configurations, targeting consistent with Chinese interests, and tooling predominantly used by Chinese-nexus threats. Sample instructions included setting red lines, such as excluding mainland China targets and government domains, and required all outbound traffic to go through proxies.

How MadPot saw inside these campaigns

MadPot presents controlled services to potential attackers and records how they discover, test, and attempt to compromise or abuse them. MadPot telemetry allows Amazon Threat Intelligence to observe attacker behavior without exposing customer workloads. In this case, the MadPot sensors presented popular LLM-compatible chat-completions interfaces on various ports. Agentic frameworks sent prompts to these interfaces as part of their offensive workflows, treating them as LLM inference backends.

The resulting telemetry contained the persistent task context, system prompts, tool histories, knowledge-graph state, and reported findings that these frameworks ordinarily send to an LLM to make operational decisions. Because agentic frameworks retain the history of past conversations, individual requests often contain the full operational history of a campaign. That history described activity that occurred before and between the captured requests, on systems MadPot does not monitor. Amazon Threat Intelligence did not observe that activity as it happened and cannot verify the outcomes the agents reported, but the records show what the actors were pursuing.

Most of the activity used ARTEX to divide work among planner, worker, verification, and compression agents sharing a persistent knowledge graph. The knowledge graph acts as the operation’s shared memory: every agent reads from it, and writes its results back, so each agent picks up where the others left off. The agents’ records described reconnaissance, vulnerability testing, credential theft, cloud-privilege expansion, and cryptocurrency fraud attempts across hundreds of targets spanning AI application platforms and other workloads. These records show how threat actors are organizing persistent, financially motivated offensive operations using agentic AI frameworks.

Campaign 1: Stealing AI credentials at industrial scale

In this campaign, threat actors used AI agents to steal API keys and other credentials that grant access to AI models, most likely so they could use those models while someone else paid for them. The agents’ records show stolen keys being fed into the framework’s own model gateway, where they powered the agents searching for more keys. Beyond AI model access keys, cloud credentials were treated as a doorway to more access. Agents validated identities through each provider’s token and identity services, enumerated storage, assessed permission scope, and went after managed AI model services, secrets and parameter stores, and application identities. They prioritized access to premium frontier models over general cloud permissions.

Agents recorded use of different AI gateways, keys, and models, but they all used a shared method: find internet-exposed AI applications, extract the upstream provider keys they hold, validate those keys, and store them in a managed pool. The agents focused on applications that aggregate provider keys, because one weak management interface can expose many downstream accounts. Targets included LLM gateways and proxy platforms such as One API, New API, Veloera, Sub2API, and LiteLLM, and AI application builders such as Dify, FastGPT, Langflow, RAGFlow, Open WebUI, LobeChat, and Ollama. A codified vulnerability playbook mapped each fingerprinted product to its known attack chain, including uninitialized installs that could be claimed, anonymous management and provider-configuration endpoints, default administrator credentials, such as the LiteLLM default master key, CVE-2025-3248 (Langflow), CVE-2026-28797 (RAGFlow), an authentication bypass via the isCliRequest header in One API family systems, SSRF through URL-fetch features to cloud metadata services, and secrets left in client-side JavaScript, source maps, debug routes, and environment files.

To find those keys, discovery drew on internet scanning services, certificate transparency, and public code and artifact sources: GitHub repositories and event archives (targeting secrets that fell outside automated revocation), npm and PyPI tarballs, container image layers, notebooks, model-hosting spaces, paste sites, and Telegram channels. One parallel operation worked through a fixed country sequence, prioritizing enterprise production sites, and graded every credential: L1 for a lead, L2 for a confirmed working API call, and L3 for quantified impact, such as readable data or spendable balance. Keys exposed publicly for more than 30 days were treated as low-value inventory.

Campaign 2: Defeating identity verification with deepfakes

In this campaign, threat actors used AI agents to defeat the identity verification (KYC) checks at two cryptocurrency exchanges with deepfakes. The agents’ records show generating real-time deepfake video to pass live selfie checks and forged ID document photos to pass document checks.

The records describe a methodical approach to the liveness check, which is a security method that confirms a person interacting with a digital system is a real, living human being physically present at the time of capture. The agents reverse-engineered one vendor’s liveness protocol in detail, documenting the face-detection event stream it sends, how it tracks face position during the check, and the coordinate system it uses to tell the user where to move. Their best recorded attempt completed the full movement sequence with the face positioned within 7 pixels of the target. Even so, the vendor’s server-side verdict rejected the deepfake in every attempt the agents recorded. In parallel, a separate session built a real-time deepfake video pipeline on a single consumer-grade GPU using an open-source face animation model. By splitting the model and avoiding unnecessary memory copies on the GPU, it reached 11.5 frames per second, close to what a live video check expects.

The agents worked on the ID document as well. Verification vendors look for signs that a document photo was edited or is a picture of a screen rather than a camera capture. To get past those checks, the agents recorded building synthetic camera metadata whose image dimensions matched the real values inside the JPEG file, and preserving the original camera compression tables that re-saving an edited image would normally replace. The result is an altered image that looks, at the file level, like an untouched camera photo.

This campaign also shows how ARTEX runs several workstreams toward one goal. At least four agent sessions ran at once: one searched for ways to cash out, one worked on clearing account balances, one set up the deepfake video pipeline, and one carried out the verification bypass. They shared findings and handed off tasks through cross-session tools.

What this means for defenders

None of the techniques in these campaigns were new. What AI agents change is the speed and persistence of the attacker. The agents succeeded where basic security hygiene was missing, including default or hardcoded credentials, keys left in code and public artifacts, unauthenticated interfaces and inference endpoints, and unpatched software. Getting those fundamentals right remains the most effective defense.

Given the speed and persistence of the attackers, organizations should assume exposed secrets and misconfigurations will be found quickly and remediate accordingly. They should bring AI applications, model gateways, and inference endpoints under the same controls as other production systems, and they should watch for misuse of AI services through unexpected spend or unusual usage.

Indicators of Compromise (IOCs)

IOC Value IOC Type First Seen Last Seen Annotation
104.28.225[.]223 IPv4 2026-10-17 2026-10-19 Campaign 1
31.22.91[.]156 IPv4 2026-10-14 2026-10-19 Campaign 1
150.136.38[.]110 IPv4 2026-10-31 2026-10-31 Campaign 1
128.242.115[.]131 IPv4 2026-10-31 2026-10-31 Campaign 1
216.176.239[.]231 IPv4 2026-11-02 2026-11-02 Campaign 1
212.107.28[.]51 IPv4 2026-10-14 2026-10-14 Campaign 2
103.142.140[.]158 IPv4 2026-10-17 2026-10-17 Campaign 2
104.28.251[.]98 IPv4 2026-10-18 2026-10-18 Campaign 2
104.28.251[.]99 IPv4 2026-10-18 2026-10-18 Campaign 2
104.28.219[.]97 IPv4 2026-10-18 2026-10-18 Campaign 2
125.103.213[.]41 IPv4 2026-10-18 2026-10-19 Campaign 2

If you have questions, start a new thread on AWS re:Post or reach out to AWS Support.


CJ Moses

CJ Moses

CJ Moses is the CISO of Amazon Integrated Security. In his role, CJ leads security engineering and operations across Amazon. His mission is to enable Amazon businesses by making the benefits of security the path of least resistance. CJ joined Amazon in December 2007, holding various roles including Consumer CISO, and most recently AWS CISO, before becoming CISO of Amazon Integrated Security September of 2023.

Prior to joining Amazon, CJ led the technical analysis of computer and network intrusion efforts at the Federal Bureau of Investigation’s Cyber Division. CJ also served as a Special Agent with the Air Force Office of Special Investigations (AFOSI). CJ led several computer intrusion investigations seen as foundational to the security industry today.

CJ holds degrees in Computer Science and Criminal Justice, and is an active SRO GT America GT2 race car driver.

Multi-statement transactions for Apache Iceberg tables in Amazon Redshift

Post Syndicated from Shiyu Xu original https://aws.amazon.com/blogs/big-data/multi-statement-transactions-for-apache-iceberg-tables-in-amazon-redshift/

Data pipelines often change a table in several steps, such as first upserting the day’s sales and then removing canceled orders. Amazon Redshift now supports multi-statement transactions for Apache Iceberg tables so you can run several data manipulation language (DML) statements against one Iceberg table inside a single BEGIN … COMMIT. Amazon Redshift publishes them as one Iceberg snapshot. Readers in other sessions and engines see the table before the batch commit or after it. A failed or rolled-back transaction leaves nothing to undo. Multi-statement transactions are available in Amazon Redshift with Patch 206 and later.

Multi-statement transactions extend existing Iceberg support in Amazon Redshift, which you can use to create Iceberg tables and write to them with INSERT, modify rows with DELETE, UPDATE, and MERGE, store materialized views as Iceberg tables, and commit concurrent writes that don’t overlap. Until now, though, each write committed on its own, one statement at a time.

In this post, we explain why one commit per statement makes multi-step pipelines fragile and how Amazon Redshift commits multiple statements as one snapshot. We also cover what you can run in a transaction, what concurrent readers and writers see, and how multi-statement transactions perform.

The challenge of one commit per statement

Consider a retailer whose finance team tracks daily revenue. During the day, some point-of-sale (POS) values are corrected, such as a price fix, and others are voided, such as a canceled order. Dashboards and downstream jobs read revenue from one Iceberg table, sales (sale_id, store_id, sale_date, amount), in the external schema iceberg_schema. Each night, the POS system delivers the day’s batch as two staging Iceberg tables. pos_sales holds new and corrected sales, one row per sale_id, and pos_voids lists voided sales. A job applies the batch in two statements:

-- 1. Upsert new and corrected sales
MERGE INTO iceberg_schema.sales USING iceberg_schema.pos_sales p
  ON sales.sale_id = p.sale_id
  WHEN MATCHED THEN UPDATE SET amount = p.amount
  WHEN NOT MATCHED THEN INSERT VALUES (p.sale_id, p.store_id, p.sale_date, p.amount);
-- auto-commits: revenue includes voided sales

-- 2. Remove voided sales
DELETE FROM iceberg_schema.sales
  WHERE sale_id IN (SELECT sale_id FROM iceberg_schema.pos_voids);
-- auto-commits: revenue is correct

Because each statement commits on its own, the state between them is public. Until the DELETE commits, every reader sees revenue that includes the voided sales. If the DELETE fails, for example because the query is canceled, the table stays that way. If a check after the job finds the batch wrong, both changes are already public, so you must work out which statements landed and write SQL to undo them. Each commit also costs time as it writes new table metadata to Amazon Simple Storage Service (Amazon S3) and updates the catalog. A job of N statements pays the catalog update N times.

How Amazon Redshift commits multiple statements as one snapshot

To make the batch atomic, wrap the same statements in BEGIN and COMMIT. No new syntax is needed, and the job can audit the result before it commits:

BEGIN;

-- 1. Upsert new and corrected sales (full statement above)
MERGE INTO iceberg_schema.sales USING iceberg_schema.pos_sales p ON ...;

-- 2. Remove voided sales
DELETE FROM iceberg_schema.sales
  WHERE sale_id IN (SELECT sale_id FROM iceberg_schema.pos_voids);

-- 3. Audit: data quality checks see the uncommitted changes
SELECT sum(amount)                                 AS day_total,
       sum(CASE WHEN amount < 0 THEN 1 ELSE 0 END) AS negative_rows
FROM iceberg_schema.sales
WHERE sale_date = '2026-10-06';

-- 4. COMMIT if the checks pass; otherwise ROLLBACK
COMMIT;

Here’s what happens in this transaction:

  1. Each statement builds on the previous statement’s uncommitted metadata, so the transaction accumulates one pending snapshot.
  2. Reads of sales inside the transaction, by the same name, see that pending snapshot. The audit SELECT checks the batch while no other session or engine can see it.
  3. At COMMIT, Amazon Redshift publishes the whole batch as one snapshot with one catalog update, instead of one per statement. Readers in other sessions and engines see the table before the batch or after it, never in between.
  4. If a statement fails or the job issues ROLLBACK, nothing is published. The table stays as it was before BEGIN, with nothing to undo.

This transaction is a session-scoped form of the write-audit-publish pattern in plain SQL. The job’s orchestrator, such as your application or an Apache Airflow task, commits only if day_total matches the control total from the POS system and negative_rows is zero. Otherwise it issues ROLLBACK, and readers keep seeing the last verified version of sales while the team investigates the batch.

Timeline diagram comparing auto-commit with a multi-statement transaction. With auto-commit, MERGE and DELETE each make a catalog commit, so between the two commits other readers see overstated revenue that includes voided sales. In a multi-statement transaction, MERGE, DELETE, and the audit SELECT stay pending inside the session, and other readers see the table as it was before the batch until COMMIT publishes the correct revenue in one catalog commit. ROLLBACK publishes nothing.

Figure 1: What other readers see with auto-commit and with a multi-statement transaction

What you can run inside a transaction

Iceberg DML is accepted in an explicit transaction block, in a multi-statement command string, and in prepared statements, including those sent through the Amazon Redshift JDBC driver.

All writes in a transaction must go to the same Iceberg table. The table can be in the AWS Glue Data Catalog or Amazon S3 Tables, and you can reference it through an external schema or the auto-mounted awsdatacatalog catalog. Refer to the table by the same name throughout the transaction. Amazon Redshift identifies a table by how you reference it. If you reference one physical table through two external schemas, or through an external schema and awsdatacatalog, it counts as two tables. A write through the second name is rejected.

Statement inside the transaction Behavior
Reads of Iceberg, Redshift managed storage (RMS), and external tables, across databases Allowed
INSERT, UPDATE, DELETE, MERGE against one Iceberg table Allowed. Published as one snapshot at COMMIT
REFRESH MATERIALIZED VIEW on one Iceberg materialized view Allowed. The view is the transaction’s write target
Reads of the Iceberg table you are writing, by the same name Allowed. Sees your uncommitted changes
A write to a second Iceberg table Rejected
Any other write, before or after the Iceberg writes: RMS or temporary table DML, COPY, UNLOAD, GRANT, REVOKE, ANALYZE, or other data definition language (DDL) Rejected
DDL on an Iceberg table: CREATE TABLE, CREATE TABLE AS, ALTER TABLE, CREATE MATERIALIZED VIEW, DROP TABLE, DROP MATERIALIZED VIEW Rejected
An Iceberg write inside a stored procedure Rejected

A rejected statement fails and aborts the transaction, so nothing that ran before it is published.

The nightly job fits these rules: it reads the Iceberg tables pos_sales and pos_voids and writes only sales. If the job also clears processed rows from a staging table, do that after COMMIT. Inside the transaction, it would be a write to a second Iceberg table.

Note: This changes behavior for existing workloads. A single Iceberg DDL statement inside BEGIN … COMMIT used to succeed and is now rejected. Run Iceberg DDL as a standalone statement.

Cleaning up orphan files

Intermediate files written by a transaction that doesn’t commit aren’t referenced by any snapshot and become orphan files. For Amazon S3 Tables, unreferenced file removal is enabled by default for table buckets. For tables in the AWS Glue Data Catalog, enable the orphan file deletion table optimizer. It removes only files created after you enable it, so enable it before you start using multi-statement transactions.

Concurrent readers and writers

A multi-statement transaction gives you three guarantees:

  1. Atomic publishing: Other sessions and engines see none of your changes until COMMIT, and then see all of them in one snapshot.
  2. Read your own writes: Reads of the Iceberg table you are writing include your uncommitted changes, as long as you use the same name.
  3. Repeatable reads of each table: The first read of an Iceberg table fixes its version for the rest of the transaction. Later reads of that table return the same data, even if other sessions commit to it in the meantime.

Each table’s version is fixed at its first read, not when the transaction begins. An Iceberg table that you first read later in the transaction can include changes that other sessions committed after the transaction started. For example, suppose the nightly job reads sales and then looks up store details in an Iceberg stores table. The lookup includes changes that another session committed to stores in between:

-- Session 1                              -- Session 2
BEGIN;
SELECT * FROM iceberg_schema.sales;
-- fixes the version of sales
                                          INSERT INTO iceberg_schema.stores ...;
                                          -- auto-commit
SELECT * FROM iceberg_schema.stores;
-- first read of stores:
-- includes Session 2's insert
COMMIT;

RMS tables follow their own snapshot, taken at the transaction’s first statement and not coordinated with the Iceberg catalog.

Performance

To measure the performance impact, we compared committing each statement on its own against batching the same statements into multi-statement transactions. We report results relative to single-statement commits.

Setup: An Iceberg table registered in the AWS Glue Data Catalog in the US East (N. Virginia) Region (us-east-1), written from a single Amazon Redshift provisioned cluster. Throughput tests run one session per writer over a fixed window. Each writer runs its transactions back to back. A transaction whose commit fails is rolled back and not counted. Results vary with statement size, partitioning, and contention.

Latency

We first measured the case that batching is meant to help: many small statements, where commits rather than data movement dominate the run time. Each configuration runs the same 500 small statements against one table, and only the number of statements per commit changes.

Line chart of the reduction in total run time from batching 500 small statements, by statements per transaction (1, 4, and 25), compared to committing each one separately. INSERT: 0.00%, 9.20%, and 14.77%. DELETE: 0.00%, 6.21%, and 11.29%.

Figure 2: Reduction in total run time for 500 small statements, relative to committing each statement separately

As Figure 2 shows, batching 25 statements per commit reduced total run time by 14.77% for INSERT and 11.29% for DELETE, compared to committing each statement separately. More than half of that gain already arrives at 4 statements per commit (9.20% and 6.21%). The gain comes from paying one catalog commit per transaction instead of one per statement, and from less per-statement transaction overhead.

However, when each statement already does heavy data work, the time saved by combining commits is too small to notice. Batching statements into one transaction doesn’t make the job meaningfully faster.

Throughput

With multi-statement transactions, a single catalog commit can carry the changes from several statements, which raises write throughput. To measure this, we ran an increasing number of concurrent writers against one table, comparing auto-commit single-statement INSERTs with transactions of four INSERTs. Figure 3 shows committed statements per second, normalized to a single auto-commit writer.

These results were measured with conflict resolution, which applies to every multi-statement transaction. Another writer can commit to the same table while your transaction is open. If the two sets of changes don’t overlap, Amazon Redshift rebases your transaction onto the latest table version and commits it as one snapshot, without re-running any of its statements. Only a genuine conflict, where both writes changed the same data, fails the COMMIT. In that case, retry the transaction from your application.

Line chart of committed statements per second for 1 to 32 concurrent writers, normalized to one auto-commit writer. Transactions of four INSERTs rise from 1.18x to 10.37x. Auto-commit single-statement INSERTs rise from 1.00x to 2.89x.

Figure 3: Committed statements per second as concurrent writers are added, normalized to a single auto-commit writer

The advantage grows with concurrency. With one writer, transactions commit 1.18× as many statements as auto-commit. As writers are added, the number of catalog commits per second levels off for both configurations, but each transaction commit carries four statements instead of one. At 32 concurrent writers, auto-commit reaches 2.89× the single-writer rate and transactions reach 10.37×. That is 3.59 times as many committed statements in the same window.

Conclusion

Multi-step writes are the normal shape of a data pipeline. Until now, each step against an Iceberg table was visible on its own and you could undo it only by hand. With multi-statement transactions, Amazon Redshift publishes a group of DML statements against one Iceberg table as a single atomic snapshot. Readers never see a half-applied change, and a failure leaves nothing to undo. The pipeline also pays one catalog commit instead of one per statement. To get started, upgrade to Patch 206 or later.

To learn more about Iceberg support in Amazon Redshift, see the following resources:


About the authors

Shiyu Xu

Shiyu Xu

Shiyu is a software engineer at Amazon Redshift who builds core storage infrastructure, including transactional support for Apache Iceberg tables, backup, and the data storage layer.

Jiuzhi Yu

Jiuzhi Yu

Jiuzhi is a software engineer at Amazon Redshift working on transactional support for Apache Iceberg tables, backup, and the data storage layer.

Xiening Dai

Xiening Dai

Xiening is a principal software engineer leading various efforts in Amazon Redshift query execution and data lake processing.

Madhukiran Vaddi

Madhukiran Vaddi

Madhukiran is an engineering lead with the Amazon Redshift team. Leads Iceberg transaction support, including conflict resolution and multi-table transactions, and Redshift concurrency scaling, backups, and durability. Madhukiran is passionate about building reliable data infrastructure at cloud scale.

Srishti Mittal

Srishti Mittal

Srishti is a Product Manager at AWS, with a focus on making open data lakes performant and interoperable across analytics engines. She leads product strategy for open table formats such as Apache Iceberg, partnering with customers and field teams to turn real-world data lake challenges into product capabilities.

Managed cross-Region disaster recovery for Amazon OpenSearch Service

Post Syndicated from Cedric Pelvet original https://aws.amazon.com/blogs/big-data/managed-cross-region-disaster-recovery-for-amazon-opensearch-service/

Amazon OpenSearch Service already offers high availability within a single AWS Region through Multi-Availability Zone (Multi-AZ) deployments. Some organizations, however, need a multi-Region architecture to meet specific business requirements. These include strict recovery point and recovery time objectives, data residency mandates, and business continuity plans for mission-critical search and AI workloads.

Until now, meeting that bar on Amazon OpenSearch Service meant building and operating your own replication with cross-cluster replication or dual writes to multiple Regions. That took months of engineering and ongoing maintenance, offered no coordinated way to switch roles between Regions, and gave no guaranteed recovery point objective (RPO).

Amazon OpenSearch Service now offers managed disaster recovery for domains running OpenSearch 3.7 or later. Managed disaster recovery replicates your data from a primary domain in one Region to a secondary domain in another and keeps the secondary continuously in sync. When you need to move your workload, you use API-driven switchover and failover. It provides an RPO under 1 minute and a recovery time objective (RTO) under 20 minutes, and you can set it up in two steps.

In this post, we explain how managed disaster recovery works, what to check before you start, and how to set it up, monitor it, and switch Regions.

Who should use managed disaster recovery

Managed disaster recovery is built for workloads where downtime or data loss has a direct business, customer, or compliance cost. Common patterns include:

  • Customer-facing search: Ecommerce, product catalog, and site search, where downtime means lost revenue and a degraded customer experience.
  • Financial services and risk: Fraud detection, transaction search, and risk analytics, where regulators expect demonstrated cross-Region recoverability and regular disaster recovery exercises.
  • Mission-critical operational data: Search and analytics that support incident response, security investigations, or regulated record retrieval, where teams need uninterrupted access to data.

If your recovery plan requires a copy of your OpenSearch data in another Region and a tested way to move your workload there, managed disaster recovery replaces the replication pipeline you would otherwise build and operate yourself.

Solution overview

Managed disaster recovery pairs two OpenSearch Service domains in different Regions. One domain is the primary: It accepts reads and writes. The other is the secondary: It continuously receives changes from the primary and serves reads only. The following diagram shows the architecture.

Managed disaster recovery architecture: a primary OpenSearch Service domain replicating to a secondary domain in another AWS Region

Figure 1: Managed disaster recovery pairs a primary domain in one Region with a read-only secondary domain in another, with managed replication between them

When you pair the domains, the service first copies the existing Lucene segments from the primary to the secondary. After this initial copy, every new document and update is indexed on both the primary and the secondary domain. Replication traffic stays within the OpenSearch Service network, so you don’t need to set up virtual private cloud (VPC) peering or any networking, and data is encrypted in transit. Because both domains index the data, the secondary is ready to take over as primary at any time.

Both domains serve reads, but only the current primary accepts writes. When roles change, you redirect your application’s writes to the new primary. For more details, see the Switch Regions section later in this post.

There are two ways to move the primary role to the other Region. The following table compares them and later sections refer back to this table.

Switchover Failover
Type of event Planned Unplanned
Coordination Coordinated role swap between both domains. Unilateral promotion of the secondary.
Data loss Zero: pending writes replicate before roles swap. Writes not yet replicated are lost, bounded by replication lag (RPO).
When to use Regulatory exercises, maintenance, planned Region moves, issues outside OpenSearch Service. The primary domain is unavailable.
Call on The secondary domain being promoted. The secondary domain being promoted.

You can also manage replication health from a built-in dashboard on the AWS Management Console, and the service supports customer managed AWS Key Management Service (AWS KMS) keys for encryption at rest.

Prerequisites and limitations

Before you start, confirm that your environment meets the following requirements:

  • Engine version: Both domains run OpenSearch 3.7 or later. If you’re on an earlier version, see Upgrade to OpenSearch 3.7 with a clone-based upgrade at the end of this section.
  • Same AWS account: The primary and secondary domains must be in the same AWS account, in different Regions.
  • Matching sizes: Both domains index all data and use the same number of primary shards and replicas, so they need similar CPU, memory, and storage capacity.
  • UltraWarm, Writable Warm, and Optimized engine for log analytics: Domains that use UltraWarm or Writable Warm storage or the OpenSearch Optimized engine for log analytics aren’t supported in this release.
  • Configuration isn’t replicated: Managed disaster recovery replicates data. Index State Management (ISM) policies, index templates, settings, and roles aren’t replicated, so manage them on both domains with infrastructure as code (see Best practices later in this post).
  • Client redirection: The service doesn’t redirect application writes after a switchover or failover. Your application or runbook must do this.

Upgrade to OpenSearch 3.7 with a clone-based upgrade

If your domains run an earlier version, you can upgrade them to OpenSearch 3.7 with a clone-based upgrade. Instead of upgrading your existing cluster in place, OpenSearch Service creates a clone of your domain on the target version and keeps it in sync with your data. Your domain keeps serving traffic from the original cluster. With a clone-based upgrade, you can:

  • Validate first: Test the clone with your own read requests before it takes effect.
  • Cut over when you’re ready: You choose when to move traffic. Writes are blocked during cutover, which can last up to several minutes.
  • Cancel or roll back: Cancel any time before cutover, or roll back to the original cluster during a retention period that you set.

Clone-based upgrades are available for domains running Elasticsearch 7.10 or OpenSearch 1.1 or later. Earlier versions need an in-place upgrade first. You’re charged for both the original cluster and the clone while you validate and during the retention period. Before you upgrade, take a manual snapshot and run the pre-upgrade check. For details, see Upgrading Amazon OpenSearch Service domains.

Set up managed disaster recovery

You can set up managed disaster recovery on the console or with the AWS Command Line Interface (AWS CLI). In both cases, the flow is:

  1. Create the primary domain (OpenSearch 3.7 or later) and start indexing and searching.
  2. Create the secondary domain of the same version in a different Region, with matching size.
  3. Pair the primary with the secondary.
  4. Check the replication status.

Set up on the console

On the AWS Management Console, open Amazon OpenSearch Service and select your primary domain. The disaster recovery section is available for domains running OpenSearch 3.7 or later.

Domain summary panel showing OpenSearch 3.7 and a Disaster recovery section marked Not configured with a Set up link

Figure 2: The domain summary shows the disaster recovery status as Not configured with a Set up link

Information banner reading Disaster recovery is now available, with a Set up disaster recovery button

Figure 3: An information banner offering a Set up disaster recovery button

Choose Set up or Set up disaster recovery, and then enter the Amazon Resource Name (ARN) of the secondary domain.

Set up disaster recovery page showing the primary domain and a field to enter the secondary domain ARN

Figure 4: The setup page, where you enter the secondary domain ARN and validate the prerequisites

Choose Validate prerequisites. When the domains are compatible, the console displays the message “These domains can be paired for disaster recovery.” Choose Create and enable disaster recovery. Pairing takes a few minutes.

Set up with the AWS CLI

Run the following command in the primary Region to add the secondary domain as a replication peer:

aws opensearch add-replication-peer \
    --domain-name <primary_domain> \
    --peer-domain-arn arn:aws:es:<secondary_region>:<account>:domain/<secondary_domain> \
    --region <primary_region>

Before pairing, you can call the CompareDomainConfiguration API to find where the two domains’ configurations differ across key categories.

Check the replication status

On the console, choose Manage in the disaster recovery section to view the peer role and replication status.

Disaster recovery dashboard showing primary and secondary domains in different Regions, both with replication status Active

Figure 5: The disaster recovery dashboard, showing both domains with an Active replication status

With the AWS CLI, call DescribeDomainReplication on either domain to see the peer role and replication status. To stop replication, call RemoveReplicationPeer. Each domain keeps its data.

aws opensearch describe-domain-replication --domain-name <name> --region <region>

Monitor replication

Managed disaster recovery publishes the following Amazon CloudWatch metrics on the secondary domain. We recommend creating alarms on each.

Metric Unit What it measures Healthy value Suggested alarm
DisasterRecoveryReplicationLagTime Milliseconds How far behind the primary the secondary is Up to 10 seconds, even when caught up Sustained above your RPO budget (for example, > 30,000 ms for 5 minutes)
DisasterRecoveryReplicationLagOps Count Changes the secondary hasn’t applied yet A few seconds under active writes, workload dependent. Growing continuously over several periods
DisasterRecoveryBootstrappingIndices Count Indices still doing their first full copy 0 (non-zero right after setup or new index creation) Non-zero longer than your expected initial sync time
DisasterRecoveryDegradedIndices Count Indices replicating but not fully healthy 0 > 0 for 15 minutes
DisasterRecoveryFailedIndices Count Indices where replication stopped with an error and no longer receive changes 0 > 0 (any datapoint)

For more information, see Monitoring Amazon OpenSearch Service domains.

Switch Regions with switchover or failover

Use switchover for planned events and failover when the primary is unavailable (see the comparison table in Solution overview). In both cases, call the API on the secondary domain that you’re promoting.

Perform a planned switchover

SwitchoverReplication performs a coordinated role swap with zero data loss. Run it on the secondary domain:

aws opensearch switchover-replication --region <secondary_region> \
    --domain-name <secondary_domain> \
    --peer-domain-arn arn:aws:es:<primary_region>:<account>:domain/<primary_domain>

Perform an unplanned failover

FailoverReplication promotes the secondary to primary unilaterally. Data written to the old primary but not yet replicated is lost. The loss is bounded by the replication lag. Because of this, the command requires the --allow-data-loss flag:

aws opensearch failover-replication --region <secondary_region> \
    --domain-name <secondary_domain> \
    --peer-domain-arn arn:aws:es:<primary_region>:<account>:domain/<primary_domain> \
    --allow-data-loss

Redirect client writes

Managed disaster recovery doesn’t redirect your applications. Both domains stay readable, but only the primary is writable, so after a switchover or failover your applications must send writes to the newly promoted primary. Make the write-path update part of the same runbook step as the API call, for example by updating a DNS record, a configuration parameter, or a service discovery entry.

After a switchover or failover

After a switchover, the former primary becomes the secondary and replication continues in the reverse direction with no further action.

After a failover, when the original domain is available again, you can fail back. The original domain needs to be re-seeded before it can be used again for replication. After the re-seed, you can switch over to restore the original primary Region.

Performance results

We measured setup, initial sync, steady-state replication lag, planned switchover, and unplanned failover across multiple r7g instance sizes and data footprints. The tests used synthetic Apache log data with a sustained write load of 240 MBps.

Domain details:

  • R7g.4xlarge domain: 6 data nodes + 3× m7g.large cluster managers, 12 TiB gp3 per node.
  • R7g.8xlarge domain: 6 data nodes + 3× m7g.large cluster managers, 12 TiB gp3 per node.
  • Indices use 12 primary shards + 1 replica, rollover at 50 GB per primary shard.

Note: Results can vary by workload, data size, and configuration.

Setup and initial sync

Pairing is one API call and completed in 1 to 3 minutes in our tests, from 1 TiB to 10 TiB. Initial sync time depends on data size.

Data Instance Turn on disaster recovery Full initial sync
1 TiB r7g.4xlarge ~1 min 20min
10 TiB r7g.4xlarge ~1 min 2 hr 31 min
10 TiB r7g.8xlarge ~1 min 2 hr 18 min

Steady-state replication lag

Replication lag is how far behind the secondary is under sustained write load, measured with DisasterRecoveryReplicationLagTime (p95 over the test window).

Data Instance Write load Replication lag (p95)
1 TiB r7g.4xlarge 240 MBps ~10 s
10 TiB r7g.4xlarge 240 MBps ~10 s
10 TiB r7g.8xlarge 240 MBps ~10 s

Planned switchover

Pending writes replicate to the new primary before the role swap completes, so data loss is zero. RTO is how long clients see writes fail before the new primary accepts them.

Data Instance Write load Writes down (RTO) Data loss
1 TiB r7g.4xlarge 240 MBps 36.8 s 0
10 TiB r7g.4xlarge 240 MBps 38 s 0
10 TiB r7g.8xlarge 240 MBps 57 s 0

Unplanned failover

RPO is how many seconds of writes were lost. Role flip confirmed is how long until the control plane confirms the promotion. Writes down is how long until clients receive HTTP 201 from the new primary.

Data Instance Write load Role flip confirmed Writes down (RTO) Data loss (RPO)
1 TiB r7g.4xlarge 240 MBps 6.4 s 69 s ~8 s (~2.0M docs)
10 TiB r7g.4xlarge 240 MBps 8.1 s 61 s ~10 s (~2.46M docs)
10 TiB r7g.8xlarge 240 MBps 5.8 s 60 s ~10 s (~2.46M docs)

Key takeaways

In our tests, we saw the following results:

  • RPO: Unplanned failover lost about 8 to 10 seconds of writes, well within the under-1-minute RPO target. Planned switchover lost no data.
  • RTO: Writes resumed in about 1 minute after failover and under 1 minute after switchover, well within the under-20-minute RTO target.
  • Scale: Pairing time, lag, and recovery times stayed roughly constant from 1 TiB to 10 TiB. Only the one-time initial sync grows with data size.

Best practices

  • Manage configuration with infrastructure as code – Keep index templates, ISM policies, settings, and roles in a Git repository and apply them to both domains, for example with the OpenSearch Terraform provider.
  • Upgrade the secondary first – When upgrading engine versions, upgrade the secondary domain first and the active primary last. We recommend testing the performance of the new version on the secondary, then upgrading the primary after the secondary domain upgrade is validated. Don’t run mixed versions permanently.
  • Size domains to match – Keep instance types, counts, storage, and shard configuration aligned, and use CompareDomainConfiguration to detect drift.
  • Decide your failover automation – Failover is manual by design, because the right trigger differs by business. You can build event-driven automation using CloudWatch alarms and the failover and switchover APIs.
  • Exercise your runbook – Use switchover regularly to rehearse Region moves, including the client write redirection step.

Pricing

There is no additional charge for managed disaster recovery. You pay for the secondary domain’s instances and for cross-Region data transfer. For instance pricing, see Amazon OpenSearch Service pricing.

Conclusion and next steps

Managed disaster recovery gives Amazon OpenSearch Service domains continuous cross-Region replication, a zero-data-loss planned switchover, and a bounded-RPO failover, without building and operating your own replication pipeline. It serves regulated industries and business-critical workloads with strict availability, recovery, and business continuity requirements.

To get started:

  1. Create or upgrade domains to OpenSearch 3.7 or later in two Regions in the same AWS account.
  2. Pair them on the console or with the AddReplicationPeer API.
  3. Set CloudWatch alarms on the replication metrics, and build and rehearse your switchover and failover runbook.

For more information, see the Amazon OpenSearch Service disaster recovery documentation and the API reference, open the OpenSearch Service console, or view a demo video.


About the authors

Cédric Pelvet

Cédric Pelvet

Cédric is a Principal AWS Specialist Solutions Architect. He helps customers design scalable solutions for real-time data and search workloads. In his free time, his activities are learning new languages and practicing the violin.

Michael Torio

Michael Torio

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