Tag Archives: Intermediate (200)

Know the identity behind the role: Authorize and audit with trusted identity propagation

Post Syndicated from Laura Reith original https://aws.amazon.com/blogs/security/know-the-identity-behind-the-role-authorize-and-audit-with-trusted-identity-propagation/

Today, AWS is making it easier to grant access and audit activity based on the user or workload (a non-human caller, such as an application, service, or an automated workflow) behind an AWS Identity and Access Management (IAM) role. Trusted identity propagation (TIP) carries the identity of the user or workload with each AWS request, so you can grant permissions to that user or workload and trace its actions in AWS CloudTrail. Until now, TIP was available only for users who access AWS through AWS IAM Identity Center. We’ve extended TIP to IAM federation and AWS IAM Roles Anywhere, making it work for users and workloads that federate directly into IAM roles or use X.509 certificates to obtain AWS credentials. We’ve also made TIP simpler to use with IAM Identity Center.

This post explains how TIP works and what’s new with this launch. It then shows two examples of how TIP improves auditability and access control based on the user or workload behind an IAM role. The post ends with how to get started depending on your preferred federation path into AWS.

How trusted identity propagation works

Customers have told us they want to control access to AWS resources and audit activity based on the user or workload behind an IAM role. Today, access control decisions apply to the role, and CloudTrail attributes each action to the role session. To give two users or workloads different access, you either create a separate role or share one role and write policies that check session attributes. Separate roles lead to role proliferation. Session attributes carry across role sessions only when you grant additional permissions, and the session doesn’t record who set each attribute.

TIP addresses this gap by attaching identity context from a trusted source, such as your identity provider (IdP), to the role session at the time of credential issuance. This identity context identifies the user or workload behind a request and can include optional claims for the session, such as a risk score or a continuous integration and delivery (CI/CD) workflow name. Trusted sources include external SAML or OIDC IdPs configured for IAM federation, IAM Identity Center, and X.509 certificates configured for IAM Roles Anywhere.

After AWS attaches identity context to a role session, the context can’t be changed for the lifetime of the session. This approach gives IAM policies and audit records a stable reference to the user or workload behind each request. The context also carries forward to supported downstream requests. When a TIP session (a role session that carries identity context) assumes another role, AWS Security Token Service (AWS STS) carries the context into the new role session. Similarly, when an AWS service makes a downstream request on your behalf, the request uses forward access sessions (FAS), and the FAS credentials carry the identity context from your session.

Note: TIP context propagates to a new role session only when the target role is in the account where the identity provider is configured, or if the target role is in another account in the same AWS organization. To learn how account and organization boundaries determine TIP context propagation, see Understand where TIP context propagates in the IAM User Guide.

Figure 1 shows how this flow works end-to-end. A user or workload obtains AWS credentials through one of three paths. With IAM federation, the source is a SAML assertion or OIDC token for a user or workload. With IAM Identity Center, the source is the username that IAM Identity Center receives from your identity source. With IAM Roles Anywhere, the source is an X.509 certificate for a user or workload. AWS validates the source and attaches identity context to the role session. That context stays with the session’s requests, whether the session calls an AWS service directly, assumes another role, or causes an AWS service to make downstream requests through FAS. IAM policies then evaluate the identity context to authorize requests, as the Amazon Simple Storage Service (Amazon S3) bucket policy example later in this post shows, and AWS CloudTrail records it, as the AWS Lambda example shows. With IAM outbound identity federation, the session can also request a signed JSON Web Token (JWT) that carries identity context to an external service.

Figure 1: How TIP carries identity information into authorization and audit workflows

Figure 1: How TIP carries identity information into authorization and audit workflows

AWS represents the identity context carried in a TIP session through three groups of context keys. The following table summarizes their purpose and points to the corresponding documentation. For details about what these context keys contain and when they appear in a TIP session, see TIP context keys in IAM policies.

Context keys Purpose
aws:OriginIdentity/* Identifies the user or workload that started the request and the source that issued its identity.
aws:TransactionContext/IdentityProvider/* Carries optional claims from your IdP, such as a risk score or a CI/CD workflow name. Available only for IAM federation.
aws:IdentityCenterInstanceArn and aws:IdentityStoreArn Identifies the IAM Identity Center instance and identity store behind a session. If you use IAM Identity Center permission sets or IAM account access manager, you can use these keys in IAM policy conditions. For example, you can allow access only to workforce users from a specific instance.

Table 1: TIP context key categories and what they represent.

aws:OriginIdentity/* is the common namespace for identity information from IAM federation, IAM Identity Center, and IAM Roles Anywhere. Across all three paths, aws:OriginIdentity/Subject identifies the user or workload that started the request, aws:OriginIdentity/SubjectType indicates whether the request was started by a user or workload, and aws:OriginIdentity/Issuer identifies the source that issued the identity. For IAM federation and IAM Roles Anywhere, aws:OriginIdentity/FederatedProviderArn also contains the Amazon Resource Name ARN) of the IAM IdP or IAM Roles Anywhere trust anchor that authenticated the identity.

IAM policies can evaluate TIP context keys when those keys are present in the request. CloudTrail records identity context in the userIdentity element of events. The userIdentity.onBehalfOf section records the user or workload identity from aws:OriginIdentity context keys, and the userIdentity.transactionContext section records IdP claims from aws:TransactionContext/IdentityProvider context keys. For field definitions and examples see Logging TIP activity with AWS CloudTrail.

Key benefits of trusted identity propagation

TIP gives you the following benefits for authorizing and auditing access based on the user or workload behind an IAM role.

  • Audit by identity, not only by role – CloudTrail records the user or workload behind each request.
  • Authorize based on who’s asking – IAM policies can grant or restrict access based on the user or workload, or on optional claims from your IdP, such as a risk score. This gives you precise access control for each session.
  • Rely on identity you can trust – AWS attaches identity context from a trusted source when it issues credentials. That context can’t be changed for the life of the session, and it carries forward when the session assumes another role or an AWS service makes requests on your behalf.
  • Use one model across federation paths – IAM federation, IAM Identity Center, and IAM Roles Anywhere share the same core aws:OriginIdentity context keys, so you write policies and review CloudTrail consistently across more than 250 supported AWS services. Across supported workflows, identity context propagates without adding the sts:SetContext permission to role trust policies.

What’s new with this launch

This launch extends TIP to IAM federation and IAM Roles Anywhere, and simplifies TIP in IAM Identity Center. You can also share identity context with services outside AWS through IAM outbound identity federation.

  • AWS IAM Identity Center – TIP already allows AWS applications integrated with IAM Identity Center, such as AWS Lake Formation and Amazon S3 Access Grants, to audit user activity and control access based on the user’s identity. When you enable the simplified experience, Identity Center adds a username, an identifier from your identity source, alongside the system-generated identity store user ID. This identity information is carried consistently across all access paths, including application access, account access through IAM Identity Center permission sets, and IAM account access manager. With this launch, you can now use the propagated username, mapped to the aws:OriginIdentity/Subject context key, in IAM policy conditions and view it in CloudTrail events. For more information, see Simplified experience for trusted identity propagation.
  • IAM federation – For users and workloads that use direct SAML or OIDC federation into IAM roles, you choose the SAML assertion field or OIDC token claim that identifies the user or workload, and TIP attaches it to the role session. You can also map optional SAML attributes or OIDC claims, such as a risk score or a CI/CD workflow name, into aws:TransactionContext/IdentityProvider/* context keys. TIP is turned on by default for new IAM IdPs, and you can turn it on for existing providers. For more information, see TIP for IAM Federation.
  • IAM Roles Anywhere – For users and workloads outside AWS that use X.509 certificates with IAM Roles Anywhere, TIP attaches the identity from the certificate to the role session. After IAM Roles Anywhere validates the certificate against the configured trust anchor, AWS sets aws:OriginIdentity/Subject to the certificate’s Subject common name by default, or to its URI Subject Alternative Name. TIP is turned on by default for new IAM Roles Anywhere profiles, and you can turn it on for existing profiles. For details, see Trusted identity propagation with IAM Roles Anywhere.
  • IAM outbound identity federation – A TIP session can now use the AWS STS GetWebIdentityToken API operation to request a signed JSON Web Toke that includes TIP session identity context for an external service. The external service validates the token and determines how to use the information. For details, see Federating AWS identities to external services.

Use identity context for auditability and access control

The following examples demonstrate two core benefits of TIP: auditability—tracing actions back to the user or workload—and access control based on that identity. In the first example, AnyCompany uses identity context logged in CloudTrail to identify the GitHub Actions workflow run that deployed new code to a production AWS Lambda function. In the second, AnyCompany uses an Amazon Simple Storage Service (Amazon S3) bucket policy that grants read access only to low-risk sessions initiated from a specific IdP.

Trace a Lambda deployment to its GitHub Actions run

This example shows how TIP improves auditability: identity context in CloudTrail identifies the workload, and the specific workflow run, behind an action taken with a shared role. AnyCompany stores the backend code for its payment-processing application in the anycompany/payments-api GitHub repository. A code change merged into the repository’s main branch triggers the GitHub Actions workflow defined in .github/workflows/deploy.yml. The workflow uses GitHub OIDC federation to assume a shared CICDDeployRole role, then calls the Lambda UpdateFunctionCode API operation to deploy the new code to the production payments-api-prod function. CloudTrail records this operation as an UpdateFunctionCode20150331v2 management event.

Before TIP, the CloudTrail event shows that the CICDDeployRole/GitHubActions role session updated payments-api-prod. It doesn’t identify the GitHub repository, workflow file, or workflow run that performed the update. Investigators must match the event timestamp with GitHub records to find the responsible workflow run.

Figure 2: How TIP enables attribution of a production Lambda code update to the GitHub Actions run that performed it

Figure 2: How TIP enables attribution of a production Lambda code update to the GitHub Actions run that performed it

AnyCompany enables TIP on its GitHub OIDC IdP. It maps the GitHub OIDC token subject to aws:OriginIdentity/Subject, configures aws:OriginIdentity/SubjectType as workload, and maps the repository, workflow_ref, and run_id claims into aws:TransactionContext/IdentityProvider/* context keys. The resulting role session identifies the workload and carries the information needed to trace the deployment to its GitHub Actions run.

With TIP, the CloudTrail management event for the Lambda UpdateFunctionCode API operation on payments-api-prod now contains the workload and workflow information:

{ 
  "eventSource": "lambda.amazonaws.com", 
  "eventName": "UpdateFunctionCode20150331v2", 
  "recipientAccountId": "111122223333", 
  "requestParameters": { 
    "functionName": "payments-api-prod" 
  }, 
  "userIdentity": { 
    "type": "AssumedRole", 
    "arn": "arn:aws:sts::111122223333:assumed-role/CICDDeployRole/GitHubActions", 
    "onBehalfOf": { 
      "federatedProviderArn": "arn:aws:iam::111122223333:oidc-provider/token.actions.githubusercontent.com", 
      "subject": "repo:anycompany/payments-api:environment:production", 
      "subjectType": "workload", 
      "issuer": "token.actions.githubusercontent.com" 
    }, 
    "transactionContext": { 
      "IdentityProvider": { 
        "repository": "anycompany/payments-api", 
        "workflow_ref": "anycompany/payments-api/.github/workflows/deploy.yml@refs/heads/main", 
        "run_id": "19283746550" 
      } 
    } 
  } 
} 

An investigator can now see that GitHub Actions run 19283746550 from the anycompany/payments-api repository updated the production payments-api-prod function through the deploy.yml workflow. The shared role, its trust policy, and its permissions remain unchanged. TIP adds workload and workflow attribution to the existing deployment model.

Authorize access based on session risk

This example shows how TIP supports access control: an Amazon S3 bucket policy uses a runtime risk signal from an IdP to decide, per session, whether a user of a shared role can read sensitive data. AnyCompany’s workforce users federate to AWS through an OIDC IdP and use a shared DataAccessRole to read objects from an Amazon S3 bucket. AnyCompany configures its IdP to evaluate each authentication and add a numeric risk score, from 0 to 100, to the OIDC token as a custom claim. AnyCompany enables TIP on the IAM OIDC IdP and maps the riskScore claim to the aws:TransactionContext/IdentityProvider/riskScore context key. During federation, AWS validates the token and attaches the mapped riskScore value to the role session. AWS derives aws:OriginIdentity/Issuer from the iss (issuer) claim in the OIDC token.

Before TIP, a bucket policy that grants access to DataAccessRole gives every user who assumes the role the same access, regardless of how risky their authentication was. With TIP, an S3 bucket policy can evaluate both the IdP that issued the token and the risk score carried in the session. The following policy grants read access only when the expected IdP (issuer) issued the identity, and the current session has a risk score of 30 or lower. The issuer condition prevents a riskScore value from another IdP from satisfying the policy.

Figure 3: How an S3 bucket policy uses trusted identity context to make a per-session access decision

Note: This policy example is for the IAM federation access path. Mapping SAML attributes or OIDC claims to optional aws:TransactionContext/IdentityProvider/* context keys is available only for IAM federation.

Amazon S3 bucket policy using trusted runtime context

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowLowRiskSensitiveDataRead",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::111122223333:role/DataAccessRole"
      },
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::amzn-s3-demo-bucket/restricted/*",
      "Condition": {
        "StringEquals": {
          "aws:OriginIdentity/Issuer": "idp.example.com"
        },
        "NumericLessThanEquals": {
          "aws:TransactionContext/IdentityProvider/riskScore": "30"
        }
      }
    }
  ]
}

The policy has two conditions: the identity must come from idp.example.com, and the session’s risk score must be 30 or lower. A low-risk session from idp.example.com satisfies both conditions. A session with a risk score above 30, a missing risk score, or a different issuer doesn’t receive access from this policy. The risk score remains fixed for the lifetime of the role session, so choose a session duration appropriate for the sensitivity of the access.

Additional considerations

Missing TIP context keys. A TIP context key is missing when the session carries no identity context or the request goes to an AWS service that doesn’t support TIP. To prevent an Allow statement from granting access when a required key is missing, use operators without IfExists, such as StringEquals or NumericLessThanEquals, as the preceding bucket policy does. Avoid operators such as StringEqualsIfExists in an Allow statement because they evaluate to true when the key is missing. In a Deny statement, add IfExists when the Deny should also apply if the key is missing. Such a Deny also applies to requests sent to AWS services that don’t support TIP, so confirm service support before adding TIP conditions. For more information, see Condition operators.

TIP conditions with cached AWS KMS data keys. Some AWS services, such as Amazon SQS, reuse cached AWS KMS data keys across requests from different sessions of the same IAM role, because the cache key is based on the role and does not include TIP context. When an AWS service reuses a cached data key, it does not send a new authorization request to AWS KMS, so AWS KMS does not evaluate the later session’s TIP context. If you use TIP context to control access to encrypted data, enforce the TIP conditions in the policy for the encrypted resource, such as an Amazon S3 bucket policy, rather than relying only on the AWS KMS key policy. For more information, see AWS KMS guidance for cached data keys.

Choose your TIP approach and get started

Your first step to getting started with TIP depends on how your users and workloads obtain AWS credentials. Use the following table to find the TIP option for your use case and get started.

Use case TIP option How to start
Centrally managed workforce access IAM Identity Center All IAM Identity Center instances can upgrade to the simplified experience for TIP. Before you upgrade, review the considerations for the simplified experience. For more information, see Simplified experience for trusted identity propagation.
Direct SAML or OIDC federation into IAM roles IAM federation New IAM IdPs have TIP turned on by default. For an existing IdP, turn on TIP on that provider, then map the claim that identifies the user or workload, and any optional claims your policies need, to TIP context keys. For more information see TIP for IAM Federation.
X.509-based access for users and workloads outside AWS IAM Roles Anywhere New profiles have TIP turned on by default. For an existing profile, enable TIP on the profile. For details, see Trusted identity propagation with IAM Roles Anywhere.

Conclusion

With this launch, TIP carries the identity of the user or workload from a trusted identity source into the role session for IAM federation, IAM Identity Center, and IAM Roles Anywhere. You can grant access based on the user or workload making the request and use CloudTrail to trace actions across more than 250 supported AWS services back to that identity. This gives you a consistent authorization and audit model across federation paths, without creating a separate role for every identity or adding the sts:SetContext permission to role trust policies.

To get started, find your federation path in the preceding table and follow the steps in the How to start column.

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


Laura Reith

Laura Reith

Laura is an Identity Solutions Architect at AWS, where she thrives on helping customers overcome security and identity challenges. In her free time, she enjoys wreck diving and traveling around the world.

Rishi Tripathy

Rishi Tripathy

Rishi is a Principal Product Manager on the AWS Identity and Access Management (IAM) team. He focuses on access control mechanisms that help enterprises secure their AWS environments at scale. He is passionate about building security primitives that are straightforward to adopt and hard to misconfigure.

Songzhi Liu

Songzhi Liu

Songzhi is a Principal Big Data Architect with the AWS Identity Solutions team. In this role, he collaborates closely with AWS customers and cross-functional teams to design and implement scalable data architectures, focusing on integrating big data and machine learning solutions to enhance identity awareness within the AWS ecosystem.

Shweta Motwani

Shweta Motwani

Shweta is a Senior Product Manager on the AWS IAM Identity Center team, focused on increasing identity awareness across AWS services to allow for improved auditing and access control. Shweta joined AWS in 2017 and has previously worked as a product manager in Amazon EBS, driving Provisioned IOPS growth and with software partners in the AWS Partner Network.

Introducing AWS WAF simplified pricing

Post Syndicated from Fenil Patel original https://aws.amazon.com/blogs/security/introducing-aws-waf-simplified-pricing/

Starting today, AWS WAF pricing is easier to predict. Your bill is now based on three dimensions: the resources you protect, the traffic AWS WAF inspects, and the level of protection you apply to that traffic.

Existing AWS WAF customers move to the new pricing on February 1, 2027. Until then, you keep your current pricing, and you don’t need to do anything at launch. This post explains what’s changing, how to estimate your costs under the new model, and where to find full pricing details and examples on the AWS WAF pricing page.

For new or smaller workloads, the Free plan of CloudFront flat-rate pricing plans is another way to start. If your application serves fewer than 1 million requests per month, the Free plan costs $0 per month for each CloudFront distribution. It includes AWS WAF protection against common web threats, DDoS protection, and the CloudFront CDN, with no overage charges.

Why the pricing is changing

Under the previous model, adding a protection often meant adding a charge, so every security decision was also a billing decision. The new pricing separates those two questions and makes the trade off between cost and security posture easy to see. Turning on a rule, the Bot Control common protection, or the Anti-DDoS rule group doesn’t add a subscription or a separate per-request charge. Those requests bill at the base request rate.

Capacity also stops affecting your rate. Each protection pack (web ACL) now includes up to 2,500 web ACL capacity units (WCUs), up from 1,500, and going past your included capacity no longer raises what you pay per request. The premium request fee applies only to the traffic you choose to send through advanced protections.

You can estimate costs before writing a single rule, and those estimates hold even as your rules change. Security rules change often. A new CVE or a shift in bot behavior can require a configuration update the same day. Adding, reordering, or removing rules doesn’t change your rate.

What this means for existing customers

If you already use AWS WAF, your account stays on current pricing until February 1, 2027. If you hold an AWS WAF private pricing agreement, it stays in force until it expires.

You don’t have to work out the math yourself. The AWS WAF pricing page includes worked examples that show how the three fees add up for common workloads. If you have questions about how the new pricing applies to your account, contact your AWS account team or open a Support case.

For AWS Shield Advanced subscribers, nothing changes. Your Shield Advanced subscription, its price, and your included AWS WAF entitlement stay the same. AWS WAF remains included up to 1,500 WCU per protection pack (web ACL), the resources Shield Advanced protects stay unmetered, and AWS WAF base requests remain free up to 50 billion per calendar month.

Customers on a CloudFront flat-rate pricing plan also see no change. AWS WAF stays included in your plan, and your plan’s included requests stay the same.

How the new pricing works

AWS WAF bills three fees. The resource fee is an hourly charge for each resource associated with a protection pack (web ACL). It covers resources that AWS WAF can protect, such as Amazon CloudFront distributions, Application Load Balancers, and Amazon API Gateway APIs. The base request fee applies to each request AWS WAF inspects. The premium request fee applies on top of the base request fee, to the requests that advanced protections evaluate, such as Bot Control targeted protections, Fraud Control, API Security, and AI Security. AWS WAF also launches two new managed rule groups today, API Security and AI Security. Both use the same premium request fee, with no separate subscription or rate. For the current list of advanced protections, see the AWS WAF Developer Guide.

Fee What it’s charged for Rate
Resource fee Each resource associated with a protection pack (web ACL), prorated hourly $0.01 per hour (about $7.30 per month)
Base request fee Each request that AWS WAF inspects $0.60 per million requests
Premium request fee Requests evaluated by advanced protections, in addition to the base request fee $5.00 per million requests

Requests evaluated by one or more advanced protections are billed $5.60 per million: the $0.60 base request fee plus the $5.00 premium request fee. AWS WAF charges the premium request fee once per request, however many advanced protections evaluate it. A request that Bot Control targeted protections, API Security, and AI Security evaluate is still billed $5.60 per million. A request that an earlier rule blocks before it reaches an advanced protection pays only the base request fee. For instance, a request blocked by a custom rule before it reaches Bot Control pays $0.60 per million, not $5.60.

Figure 1 shows where each previous charge lands under the new pricing model. AWS WAF also inspects request bodies up to the maximum size that each associated resource type supports, at no extra charge. For the current limits by resource type, see Considerations for managing body inspection in AWS WAF.

Figure 1: Mapping of previous AWS WAF pricing components to the new three-dimension model

Figure 1: Mapping of previous AWS WAF pricing components to the new three-dimension model

See your traffic with the Security analytics dashboard

The new pricing also includes the Security analytics dashboard. The dashboard shows full traffic metrics for your protected applications over a rolling 21 day window. You can use it to see the requests your protection packs (web ACLs) inspect and how your rules act on them, which helps you tune the protections and understand what drives your request fees. The dashboard is included at no additional cost.

Estimating your bill

Figure 2 shows how the three dimensions add up for three example workloads.

Example 1: One protected resource. One Application Load Balancer serving 20 million requests per month.

  • Resource fee: 1 resource × $0.01 per hour × 730 hours = $7.30
  • Base request fee: 20 million × $0.60 per million = $12.00
  • Total: $19.30 per month

Example 2: A larger footprint. 40 resources serving 150 million requests per month.

  • Resource fee: 40 × $7.30 = $292.00
  • Base request fee: 150 million × $0.60 per million = $90.00
  • Total: $382.00 per month. At this size, the resource fee is the larger share.

Example 3: Advanced protections. 5 resources, 300 million requests, 30 million of them evaluated by advanced protections.

  • Resource fee: 5 × $7.30 = $36.50
  • Base request fee: 300 million × $0.60 per million = $180.00
  • Premium request fee: 30 million × $5.00 per million = $150.00
  • Total: $366.50 per month

 

Figure 2: How the three dimensions add up for three example workloads

Figure 2: How the three dimensions add up for three example workloads

To estimate your own bill, start with how many resources each protection pack (web ACL) is associated with, since that drives the resource fee. For request volumes, AWS WAF publishes Amazon CloudWatch metrics for each protection pack (web ACL) and each protected resource, including the requests your advanced protections evaluate. The Security analytics dashboard gives you the same traffic view without building your own reports.

A few architectural choices can also help. Where it fits your architecture, protecting traffic at Amazon CloudFront can cost less than protecting many downstream resources one by one. If you serve many customer domains, Amazon CloudFront SaaS Manager lets you manage them as tenants of one multi-tenant distribution, so you can apply one protection pack across them. Scope-down statements send advanced protections only the traffic that warrants them, such as login or checkout paths.

Availability and getting started

The new AWS WAF pricing is available starting today. To get started, open the AWS WAF console, review your protection packs (web ACLs) and their resource associations, and review the examples on the AWS WAF pricing page.

Frequently asked questions

Does AWS WAF charge for requests it blocks? Yes. AWS WAF bills each request it inspects, including the requests it blocks. The protected resource bills those requests as usual, except Amazon CloudFront, which doesn’t charge for requests that AWS WAF blocks (learn more).

If a request passes through two protection packs (web ACLs), is it billed twice? Yes. For example, if a request passes a protection pack (web ACL) on a CloudFront distribution and another on the Application Load Balancer behind it, each protection pack (web ACL) bills it.

Does the Security analytics dashboard cost extra? No. The dashboard is included with AWS WAF at no additional cost.

Does pricing change for AWS Marketplace managed rule groups or AWS Shield Advanced? No. Pricing for AWS Marketplace managed rule groups and AWS Shield Advanced stays the same, and resources protected by Shield Advanced stay on their current pricing.

Is there a free tier? AWS WAF does not have a standalone free tier. If you serve your application through CloudFront and it handles fewer than 1 million requests per month, the CloudFront flat-rate Free plan includes AWS WAF at $0 per month. For plan details, see CloudFront flat-rate pricing plans.

What if my application needs more than 2,500 WCU? Open an AWS Support case to request a capacity increase.

Conclusion

The new AWS WAF pricing makes cost easier to plan around, so it does not become a blocker to security best practices. Your bill follows three things you can measure: the resources you protect, the requests AWS WAF inspects, and the requests that advanced protections evaluate. Adding, changing, or reordering rules doesn’t change your rate, and turning on Bot Control common protections or the Anti-DDoS rule group doesn’t add a subscription. The Security analytics dashboard gives you 21 days of traffic visibility at no additional cost.

To see what the change means for you, review the examples on the AWS WAF pricing page, or model a new workload in the AWS Pricing Calculator.

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


Fenil Patel

Fenil Patel

Fenil Patel is a Solutions Architect on the AWS Edge Services team. He helps customers build fast, secure, and resilient applications using Amazon CloudFront, AWS WAF, AWS Shield, and AWS Global Accelerator. He specializes in web acceleration, perimeter security, and CDN migrations.

Eitav Arditti

Eitav Arditti

Eitav is a Senior Solutions Architect at AWS and a technology leader with over 15 years of experience in the tech industry. He specializes in edge computing, serverless, and platform engineering, and works with engineering teams to design secure, globally scalable architectures on CloudFront and AWS WAF. His current focus is on internet-scale systems—from global content delivery to edge security.

Alok Rana

Alok Rana

Alok is a Finance Business Partner at AWS, supporting the Perimeter Protection portfolio, including AWS WAF and AWS Shield. He brings experience in strategic finance, product pricing, deal strategy, and P&L management, plus Transaction Services work at EY and PwC. He partners with Sales, Product, and Engineering teams to drive growth, shape pricing strategy, and support strategic customer engagements.

Introducing API and AI security on AWS, from discovery to protection

Post Syndicated from Gopinath Durairaj original https://aws.amazon.com/blogs/security/introducing-api-and-ai-security-on-aws-from-discovery-to-protection/

APIs have run digital businesses for more than a decade. For a while, there seemed to be nothing new left to say about them. That changed in 2026, when AI endpoints joined them. Teams now run large language model (LLM) inference endpoints, Model Context Protocol (MCP) servers, and Agent2Agent (A2A) servers beside their REST APIs, on services such as Amazon Bedrock, Amazon Bedrock AgentCore, and Amazon Elastic Kubernetes Service (Amazon EKS), and more companies sell their API as the product itself. On the other end, AI agents read API descriptions, pick the tools they need, and chain calls with no person clicking through an app.

APIs have always had two kinds of callers: other services and people who use an app. Now there’s a third: AI agents that act on a person’s behalf. It feels like everyone has a personal AI agent that can call APIs for them. Who knew curl would be important again?

Today, we’re launching capabilities across AWS WAF, Amazon CloudFront, Application Load Balancer, and Amazon API Gateway that help you discover and protect the APIs and AI endpoints that services, apps, and AI agents call:

  • API Portal, a new feature in Amazon API Gateway, discovers your APIs and AI endpoints.
  • API Security, a new managed rule group in AWS WAF, protects your APIs.
  • AI Security, a new managed rule group in AWS WAF, protects your AI endpoints.

All three are generally available today. You can enable discovery in API Portal for one account or for your organization in AWS Organizations. The two rule groups protect the resources that you associate with your protection pack (web ACL). They work together: API Portal shows which discovered endpoints AWS WAF protects, and the security events that AWS WAF detects appear on each managed API’s detail page.

Same APIs, new callers, new attack surface

Your APIs are the same APIs they always were. What changed is how you expose them, who calls them, and what threatens them.

How you expose them.

A new MCP server or LLM endpoint takes minutes to stand up. It can be placed behind a load balancer or a CloudFront distribution without ever passing through your API gateway, so it’s missing from the API registry and the security review. An agent that can reach it doesn’t need your documentation, either, because the endpoint describes itself: an MCP client asks the server for its tools with tools/list, and an A2A client reads the agent card that the server publishes.

Who calls them.

The following table compares the three kinds of callers that reach your APIs today.

Caller

What normal looks like

What abuse looks like

What it means for protection

Service to service

Predictable, authenticated calls that repeat the same pattern

A stolen API key, or a partner that scrapes beyond its contract

Track rate and behavior for each API key and endpoint

Person to service, through an app

Sessions and UI-driven calls at a human pace

Account takeover and scripted checkouts

Browser-based signals, such as CAPTCHA and browser fingerprints, apply here

AI agent to service, for a person

Human intent with machine behavior, from an HTTP client or an automated browser

An agent with stolen credentials, or a bot that poses as an agent

Browser signals only go so far, so you need visibility into the API itself

What threatens them. The APIs behind your web and mobile apps were built for one client: your own app. Your app calls them in the right order, at a human pace, with input it already validated. Legitimate agents now call those same APIs directly, and so do attackers and fraudsters. None of them have to follow the rules that your app follows.

What we’re launching

Here’s how we respond to those changes, as shown in Figure 1. In the figure, services, people, and AI agents call your APIs through their entry points. There, API Portal maps your endpoints, and AWS WAF runs API Security and AI Security on the same traffic to stop threats.

Figure 1: API Portal inventories the APIs and AI endpoints that services, people, and AI agents call. AWS WAF protects the entry points in front of them

Figure 1: API Portal inventories the APIs and AI endpoints that services, people, and AI agents call. AWS WAF protects the entry points in front of them

  • API Portal builds an inventory of your APIs from their configuration and live traffic, identifies which of them are AI endpoints (LLM inference, MCP, and A2A), and shows you what to protect. It does this by analyzing configuration and traffic across your API entry points: CloudFront, Application Load Balancer, and API Gateway.
  • API Security covers three kinds of API abuse: broken object level authorization, authentication attacks such as tampered tokens and credential stuffing, and reconnaissance such as probing for undocumented routes. It does this with rules that work from a single request and with behavioral detections that learn your traffic.
  • AI Security identifies your AI traffic (LLM inference, MCP, and A2A), validates MCP and A2A requests against their protocol, and checks prompts and responses through Amazon Bedrock Guardrails for prompt attacks, harmful content, and sensitive information.

All three work with Amazon CloudFront, Amazon API Gateway REST APIs, and Application Load Balancer. For the current list of supported resources, protocols, and endpoint types, see AWS WAF API Security and AWS WAF AI Security rule group in the AWS WAF Developer Guide.

The three capabilities live in two places. API Portal is in the Amazon API Gateway console. That’s where it can be found, not what it covers: it discovers APIs behind CloudFront, Application Load Balancer, and API Gateway alike. API Security and AI Security are in the AWS WAF console.

Discover: You can’t secure an invisible API

Ask a platform team how many APIs they run, and you’ll get a number from a registry. Ask what’s answering requests on the internet right now, and the number changes. The MCP server that a team set up for a hackathon isn’t in the registry. Neither is the v1 endpoint that nobody turned off. Both still answer requests.

API Portal builds the inventory from both live traffic and API configuration. You enable discovery in API Portal for one account or for your organization in AWS Organizations, and you can exclude resources that you don’t want in the inventory. It reads the service logs and configuration records of your API entry points. There’s nothing to attach, no logs to forward, and no traffic to reroute. It lists the endpoints that receive traffic, by host, path, and HTTP method. Every endpoint starts as a shadow API: deployed and reachable, but not yet governed. When you promote it, it becomes a managed API. For APIs you manage, API Portal also flags zombie APIs, which have no traffic and no configuration change for a set period, and orphaned APIs, whose owning account was closed or removed from your organization. Retire a zombie API that nothing needs, and resolve the ownership of an orphaned one. For the classification rules, see the API Portal Developer Guide.

API Portal also discovers your AI endpoints. It reports each endpoint’s type, such as an LLM inference endpoint, an MCP server, or an A2A server. It finds them in the traffic at the same entry points (CloudFront, Application Load Balancer, and API Gateway) and lists them in the same inventory as your other APIs, so you don’t build a separate view for them. Combined, one row can show a shadow MCP server that nobody manages yet. Figure 2 shows the inventory.

Figure 2: The API inventory in API Portal lists the endpoints discovered behind API Gateway and Application Load Balancer, with each endpoint's AWS WAF status, classification, and AI workload type

Figure 2: The API inventory in API Portal lists the endpoints discovered behind API Gateway and Application Load Balancer, with each endpoint’s AWS WAF status, classification, and AI workload type

“We can manage our API environment more effectively when we have a clear picture of what’s running across AWS. API Portal gives us that visibility without requiring teams to change how they deploy APIs or route traffic, helping us create a more complete view across the enterprise.”
— Mike Hasani, Senior Software Engineer, Principal Financial Group

Some abuse shows in one request. Some appears only over time.

Two requests show why protecting an API takes two kinds of detection. Here’s the first one:

GET /v1/orders/48213 HTTP/1.1
Host: orders.example.com
Authorization: Bearer eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiJhZG1pbiIsInJvbGUiOiJhZG1pbiJ9.

This JSON Web Token (JWT) declares alg: none. It asks your API to skip signature verification, and a correctly built client doesn’t send that. The API Security managed rule group blocks the request before it reaches your origin, from the first request and with no learning period. The same rules catch other token tampering, such as pointing the token at a signing key that the attacker controls. These rules check the structure of a token in the Authorization header. They don’t verify its signature, so your application still has to validate the token. For the full list of rules and what each one does by default, see API Security managed rule group in the AWS WAF Developer Guide.

Here’s the second one:

GET /accounts/1337 HTTP/1.1

Nothing is wrong with this request, and the caller’s token is valid. It’s abuse only if the caller doesn’t own account 1337, and no single request can tell you that. This is broken object level authorization (BOLA), the first entry in the OWASP API Security Top 10.

So, the managed rule group also learns. It builds a baseline from your own traffic and looks for callers who don’t fit it. There’s nothing to set up for this. You don’t turn on logging or mirror traffic.

The hard part is to avoid flagging your own scripts. For example, a nightly export job reads thousands of records on a steady machine schedule. On those two signs alone, it looks like an attacker. So a detection reaches high confidence only when different kinds of signs agree, and at least one is something your own traffic never does. For example, the caller reaches records through a sequence of calls that your app never makes, or your API keeps denying it access. High confidence also needs a caller that AWS WAF can identify from a credential on the request, such as a token. A caller that AWS WAF knows only by IP address stays at medium confidence. Figure 3 compares a nightly export job with an attacker on these signs.

Figure 3: Volume and timing alone don't reach high confidence. A sign that your own traffic never shows has to agree with them

Figure 3: Volume and timing alone don’t reach high confidence. A sign that your own traffic never shows has to agree with them

The behavioral detections cover more than object access. They also flag credential stuffing, where one source presents an unusual number of different credentials in the Authorization header, and probing, where a caller keeps requesting routes or parameters that your traffic never uses.

The same thinking applies to the response, what your APIs send back. The behavioral detections take account of the status codes that your application returns, such as a caller’s rate of denied or failed requests. A caller stands out when, for example, its successful calls turn into a run of authorization failures. API Security doesn’t inspect the content of responses. Figure 4 shows the APIs view of the protection pack (web ACL) dashboard in the AWS WAF console.

Figure 4: The APIs view of the protection pack (web ACL) dashboard shows API Security detections over time, the detections that matched the most requests, and how AWS WAF handled the labeled requests.

Figure 4: The APIs view of the protection pack (web ACL) dashboard shows API Security detections over time, the detections that matched the most requests, and how AWS WAF handled the labeled requests.

Every detection is a label under awswaf:managed:aws:api-security:. A label starts with a stage (attack, recon, or warning) and names the finding. Behavioral detections also end with a confidence (high, medium, or low). Each rule has its own default action. The single-request rules that identify token tampering and unsafe methods block, and the posture and schema discovery rules count. Behavioral detections block at high confidence and count at medium and low confidence, at either stage. Detections that work from a single request have no confidence. For example, attack:alg_none:jwt_header and attack:object_level:high block, and recon:path_schema counts. AWS WAF also repeats a caller’s finding as an actor_identity label on that caller’s later requests across the whole protection pack (web ACL), for about five minutes after the last detection. At high confidence, the rule group blocks those requests by default. At medium and low confidence it counts them, and your own rules can act on the label.

AI Security understands the protocols that agents speak

LLM inference endpoints, MCP servers, and A2A servers are APIs, too. API Portal shows you which of your endpoints they are, and the API Security managed rule group already inspects their requests like any other API path.

The AI Security managed rule group adds checks made for agent traffic. It first recognizes the traffic and labels each request as LLM, MCP, A2A, or not recognized, so the checks that follow fit each endpoint type. It runs in the same AWS WAF protection pack (web ACL) as your other rules, with no new service to deploy.

Its first layer checks each MCP and A2A request against the protocol version that the request declares in its MCP-Protocol-Version or A2A-Version header. It supports MCP versions 2025-06-18, 2025-11-25, and 2026-07-28, and A2A version 1.0. For the current list, see AI Security managed rule group. These protocol compliance checks are deterministic and run entirely in AWS WAF. They come in two levels. Baseline covers the violations that let a request slip past routing or inspection, as the example that follows shows, and blocks by default. Strict adds malformed requests that are worth flagging but are usually an outdated client, and counts by default. Each failed check also adds its own label, so you can see exactly which check failed. Here’s the kind of trick that Baseline catches. The header tells every component in front of the MCP server that the request only lists tools. The body calls a tool that reads a file:

POST /mcp HTTP/1.1
Host: tools.example.com
Content-Type: application/json
MCP-Protocol-Version: 2026-07-28
Mcp-Method: tools/list
Mcp-Name: read_file

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "read_file",
    "arguments": { "path": "/etc/passwd" }
  }
}

A gateway or authorizer that trusts the header treats the request as read-only, and the server runs the tool. AWS WAF blocks the request at the API entry point, because the header and the body disagree about the method.

Its second layer checks content through Amazon Bedrock Guardrails. You don’t create or configure a guardrail for this. You turn on the option in the rule group and choose a service role, and AWS WAF assumes that role to call Bedrock Guardrails with your account’s identity. Bedrock Guardrails returns a score for each check. AWS WAF groups the scores into three levels (high, medium, and low), and the rule group has one rule for each check at each level, so you choose the action for each one. AWS WAF picks the checks for each endpoint type and each direction, as the following table shows. Response checks run only when you turn on response inspection. They cover the response body up to the body size that AWS WAF inspects for that resource, and content beyond that size isn’t checked.

Bedrock Guardrails check

What it looks for

On requests

On responses

Prompt attack

Jailbreaks, prompt injection, and attempts to extract the system prompt

Yes

MCP and A2A only

Content filter

Hate, insults, sexual content, violence, and misconduct

LLM and A2A only

No

Sensitive information

Personal data such as card numbers, US Social Security numbers, email addresses, and bank account numbers, plus credentials such as passwords and AWS access keys

No

Yes

By default, AWS WAF blocks a high-severity prompt attack, on the request or the response. Everything else counts and adds a label that names what matched, such as a prompt injection or a card number. You can change the action for any rule. If Bedrock Guardrails can’t check a request, AWS WAF adds a label that says why and lets the request through. The label is guardrails:not_assessed when the content can’t be assessed, such as an empty prompt. It’s guardrails:call_failed when the call to Bedrock Guardrails fails, plus a second label with the reason, such as guardrails:call_failed:throttling. Like every label, these appear in your AWS WAF logs and CloudWatch metrics. For how labels work, see Web request labeling in AWS WAF. To fail closed when the call to Bedrock Guardrails fails, set the Guardrails_CallFailed rule to block. Throttling then blocks requests, too. Content checks run in the supported Regions listed in AWS WAF AI Security rule group. Figure 5 follows one request through these checks.

Figure 5: AWS WAF recognizes agent traffic and checks its protocol itself, and calls Amazon Bedrock Guardrails to check the prompt on the way in and the answer on the way out

Figure 5: AWS WAF recognizes agent traffic and checks its protocol itself, and calls Amazon Bedrock Guardrails to check the prompt on the way in and the answer on the way out

The AI Security labels follow the same steps, under awswaf:managed:aws:ai-security:. For example, traffic:recognized_mcp says what the traffic is, protocol_compliance_level:baseline:mcp is the level you act on, protocol_compliance_check:mcp_method_mismatch names the check that failed, and request:guardrails:prompt_attack:severity:high carries the Bedrock Guardrails result. For the full label list, supported protocols, and configuration, see AI Security managed rule group. Figure 6 shows the AI endpoints view of the protection pack (web ACL) dashboard.

Figure 6: The AI endpoints view of the protection pack (web ACL) dashboard shows AI Security detections over time, the Amazon Bedrock Guardrails findings that matched the most requests, and how AWS WAF handled AI traffic

Figure 6: The AI endpoints view of the protection pack (web ACL) dashboard shows AI Security detections over time, the Amazon Bedrock Guardrails findings that matched the most requests, and how AWS WAF handled AI traffic

Every detection is a label, and labels work with the rest of AWS WAF

Every detection from the API Security and AI Security rule groups is also a label on the request. Any rule that runs later in your protection pack can match those labels and combine them with labels from other managed rule groups. Examples are AWS WAF Bot Control, AWS WAF Fraud Control account takeover prevention, and the Amazon IP reputation list. That list draws on MadPot, the threat intelligence tool that Amazon uses to protect customers from cybercrime. Use request labels in your own rules. Labels from response checks, such as sensitive information in a response, drive the AI Security rule group’s own actions and appear in your CloudWatch metrics.

Here are four examples of what that makes possible:

  • Rate limits keyed on labels. One probe for your API schema can be noise. Fifty from the same caller in 5 minutes is reconnaissance. A rate-based rule scoped to the reconnaissance labels counts only those requests.
  • No unsigned agents on your MCP server. If your MCP server is only for agents you work with, block requests without an access token or a verified Web Bot Auth signature. Then match the Bot Control bot name label for the operators you trust. Application Load Balancer JWT verification, CloudFront Functions, Lambda@Edge, or your MCP server still validates the token itself.
  • Two weak signals that add up. A low-confidence API Security label or a Bot Control signal by itself isn’t enough to block. Block only the requests that carry both.
  • Tighter limits on sensitive paths. Bot Control targeted protection labels callers by confidence. Use those labels to set a lower rate limit on /checkout than on the rest of your API.

The following rule shows the first example. For each IP address, it counts the requests that carry an API Security reconnaissance label. When an address sends more than 50 requests in 5 minutes, the rule blocks them. Place it after the API Security managed rule group so that its labels are available.

{
  "Name": "RateLimitAPISecurityRecon",
  "Priority": 40,
  "Statement": {
    "RateBasedStatement": {
      "Limit": 50,
      "EvaluationWindowSec": 300,
      "AggregateKeyType": "IP",
      "ScopeDownStatement": {
        "LabelMatchStatement": { "Scope": "NAMESPACE", "Key": "awswaf:managed:aws:api-security:recon:" }
      }
    }
  },
  "Action": { "Block": {} },
  "VisibilityConfig": { "SampledRequestsEnabled": true, "CloudWatchMetricsEnabled": true, "MetricName": "RateLimitAPISecurityRecon" }
}

Labels don’t have to stop at AWS WAF. With custom request headers and dynamic label interpolation, AWS WAF can forward the matched labels to your origin. Your application then sees what AWS WAF saw and can show less data, require step-up authentication, or log the request for review. For how it works, see Do more with AWS WAF labels using dynamic label interpolation.

We keep adding labels, so the documentation holds the current lists. See API Security labels, AI Security labels, and AWS WAF Bot Control rule group.

See what the rule groups found, and act on it

Every label is also an Amazon CloudWatch metric, with no extra setup, and appears in your AWS WAF logs. The protection pack (web ACL) dashboard in the AWS WAF console shows them as traffic arrives. In API Portal, each managed API’s detail page shows the security events that AWS WAF detected on it, as shown in Figure 7.

Figure 7: Each managed API's detail page in API Portal shows the events that AWS WAF detected on it

Figure 7: Each managed API’s detail page in API Portal shows the events that AWS WAF detected on it

The managed rule groups enforce their own detections at your API entry points. To write a rule of your own, start from a label. Scope a rate-based rule to the paths it appears on, key it on the IP address or TLS fingerprint, and start in count mode.

When a detection type spikes, your existing alerting can act on it. That can be a CloudWatch alarm, or the observability or security platform that already reads your metrics and logs. For log destinations, see Logging AWS WAF protection pack (web ACL) traffic.

How we test API Security

No single test shows whether a detection works, so we combine several for API Security:

  • Automated red teaming – LLM-powered agents run continuously against deliberately vulnerable test APIs that we maintain. They probe, adapt, and chain steps the way an attacker does.
  • A growing attack suite – Each working exploit that the agents find becomes a repeatable test case. We replay the suite against the managed rule group when it changes.
  • Realistic legitimate traffic – We replay traffic such as batch jobs, seasonal spikes, and power users next to the attacks, so we measure false positives together with detections.

Results from our test environment don’t transfer directly to yours, because your APIs and the attacks against them differ. The numbers that matter come from your own traffic, and the next section shows how to get them. API Security is designed to detect and block callers who walk object IDs to harvest other users’ records, and tokens whose structure shows tampering. It also flags credential stuffing against the Authorization header and callers who probe for routes that your API doesn’t serve. Efficacy and expansion work for API Security, like AWS WAF security in general, is a continuous effort. For the current list of detections, see API Security managed rule group in the AWS WAF Developer Guide.

Check what gets blocked on your own traffic

The managed rule groups apply their default actions from the moment you add them. To see what a rule group finds before it blocks anything, first add it with all rule actions overridden to count, review the results, and then remove the override. Later, to review one rule, override only that rule to count. AWS WAF still evaluates an overridden rule and adds its label, so you see what it would have blocked on your own production traffic.

Behavioral detections need time to learn your traffic. For the learning period, see Testing and deploying AWS WAF API Security. For a step-by-step evaluation, see Testing and tuning your AWS WAF protections.

Availability

API Portal, API Security, and AI Security are generally available today. Detection of data exfiltration and sensitive data exposure in responses for API Security is coming soon.

Pricing

Each capability is priced by the service it runs in. For API Portal, see Amazon API Gateway pricing. For the API Security and AI Security managed rule groups, see AWS WAF pricing. For the content checks that AI Security runs through Bedrock Guardrails, see Amazon Bedrock pricing.

Get started

To get started, complete the following steps:

  1. In API Portal, enable discovery for one account or for your organization in AWS Organizations, and exclude any resources that you don’t want in the inventory. This step doesn’t need AWS WAF. As the inventory builds, look for endpoints you didn’t expect, such as shadow APIs and AI endpoints, and add them to your managed APIs.
  2. In the AWS WAF console, add the API Security managed rule group to the protection pack in front of your APIs. Start with all rule actions overridden to count, review what it finds on your own traffic, and then remove the override.
  3. If you run AI endpoints, add the AI Security managed rule group to the same protection pack. To turn on the Bedrock Guardrails checks, choose a service role that AWS WAF can assume to call Bedrock Guardrails, and turn on response inspection if you want responses checked and your protection pack (web ACL) protects CloudFront or an Application Load Balancer. Start with the four rules that block by default overridden to count, review what they find on your own traffic, and then remove the overrides one rule at a time.
  4. After the first baseline is available, the behavioral detections label abuse and block it at high confidence. Watch the labels in your CloudWatch metrics, and in your AWS WAF logs if you turn on logging.
  5. Use those labels in your own rules, such as a lower rate limit on your most sensitive paths.

For step-by-step instructions, see Adding the API Security managed rule group and Adding the AI Security managed rule group in the AWS WAF Developer Guide.

Best practice: Put Amazon CloudFront in front of your APIs

Put Amazon CloudFront in front of your API Gateway APIs, your Application Load Balancers, and any other endpoint that is public on port 80 or 443, and associate your protection pack (web ACL) with the CloudFront distribution. That includes APIs that run outside AWS, with another cloud provider or on premises: CloudFront works with any HTTP or HTTPS origin, so those APIs get the same delivery, acceleration, and protection. The same applies to your MCP servers, A2A servers, and LLM endpoints, whether you host them on Amazon Bedrock AgentCore Gateway, on Amazon EKS, or elsewhere. With this setup:

  • AWS WAF inspects requests at the edge, before they reach your origin.
  • AWS WAF sees the caller’s own IP address.
  • AWS WAF mitigates attacks close to their source.
  • For origins in AWS, CloudFront VPC origins mean your Application Load Balancer or private API Gateway REST API isn’t exposed directly to the public internet and is reached through CloudFront.

For more information, see Use AWS WAF protections and Restrict access with VPC origins in the Amazon CloudFront Developer Guide, and the posts Introducing Amazon CloudFront VPC origins and Accessing private Amazon API Gateway endpoints through custom Amazon CloudFront distribution using VPC Origins.

Conclusion

Your APIs are the same APIs they always were. The callers changed, and so did the attack surface. With API Portal, you can see the APIs and AI endpoints that the internet is calling. With API Security and AI Security in AWS WAF, you can protect them at their entry points, without changes to your backend code.

AWS built the building blocks for what comes next: an inventory from traffic, labels that you can act on, and protection where requests first arrive. As agents and the protocols they speak change, those building blocks are where new protection shows up. For the most up-to-date information, see AWS WAF API Security and AWS WAF AI Security in the AWS WAF Developer Guide.

To get started, enable discovery in API Portal, and add the API Security and AI Security managed rule groups in the AWS WAF console.

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


Gopinath Durairaj

Gopinath is a product leader who built enterprise technology businesses across cybersecurity, cloud infrastructure, AI / ML and networking. He currently leads web application security product strategy at AWS, a portfolio that includes AWS WAF, API security, and security for AI-powered applications.

Eitav Arditti

Eitav is a Senior Solutions Architect at AWS and a technology leader with over 15 years of experience in the tech industry. He specializes in edge computing, serverless, and platform engineering, and works with engineering teams to design secure, globally scalable architectures on CloudFront and AWS WAF. His current focus is on internet-scale systems—from global content delivery to edge security.

Gabe Sin

Gabe is a Senior Product Manager at AWS on the Amazon API Gateway team, focused on API management. Before AWS, he led product and strategy at a cryptocurrency exchange, where he built the company’s end-to-end analytics infrastructure on AWS, bringing the same visibility and governance to data that he now brings to APIs.

Aykut Tuzunkan

Aykut is a Senior Technical Program Manager at AWS, based in Seattle, with more than 15 years of experience across edge security, distributed networks, and infrastructure capacity. He owns AWS WAF’s cross-org programs, which cover protection for web applications, APIs, bots, and AI traffic. He focuses on adding new protections to AWS WAF and strengthening the ones customers rely on.

Announcing custom execution roles for AWS CloudFormation StackSets

Post Syndicated from Tanvi Ravindra Malali original https://aws.amazon.com/blogs/devops/announcing-custom-execution-roles-for-aws-cloudformation-stacksets/

With AWS CloudFormation StackSets, you can create, update, and delete stacks across many accounts and Regions from a single operation. By default, StackSets creates an execution role with AdministratorAccess in each target account, which requires no additional setup. With custom execution role templates, you can define the IAM role that StackSets uses in each member account instead.

This provides two capabilities. First, you can scope the execution role’s permissions to only what your workload needs. Second, service-managed stack sets can deploy templates that use nested stacks, macros, and transforms.

Note: Switching to a custom execution role does not remove the default AdministratorAccess execution role from member accounts. For true least-privilege access, delete the default role in each member account after you confirm the custom role works.

How it works

When you create or update a stack set with an execution role template, StackSets validates it and stores it. For each target member account, StackSets then deploys the template as a small bootstrapping stack that creates the IAM role. StackSets uses the name you passed in the ExecutionRoleName parameter for all subsequent operations. The StackSetExecutionRoleName output is used only to validate that the role the template provisioned matches that name.

The bootstrapping stack is created once per member account, always in the home Region of the partition (us-east-1 for commercial, cn-north-1 for China). It is named stacksets-exec-role-stack-<region>-<stackset-id>-<short-uuid>. From that point on, every create, update, and delete operation StackSets runs in that member account uses your custom role.

Templates with nested stacks, macros, and transforms

With a custom execution role, service-managed stack sets can deploy workload templates that use nested stacks (AWS::CloudFormation::Stack), CloudFormation transforms (such as AWS::Serverless-2016-10-31), and custom macros. Previously, these features were not supported in service-managed stack sets.

This capability applies to the workload template you deploy with your stack set, not to the execution role template itself. The execution role template must still follow the requirements in the next section, including no nested stacks and no transforms.

For a workload template that uses transforms or macros, such as a SAM template, pass both CAPABILITY_NAMED_IAM and CAPABILITY_AUTO_EXPAND when creating the stack set:

aws cloudformation create-stack-set \
--stack-set-name my-sam-stack-set \
--template-body file://my-sam-template.yaml \
--permission-model SERVICE_MANAGED \
--execution-role-template-body file://execution-role-template.yaml \
--execution-role-name stacksets-exec-custom-my-role \
--capabilities CAPABILITY_NAMED_IAM CAPABILITY_AUTO_EXPAND

Prerequisites

Before you configure a custom execution role template, make sure:

  • Your StackSet uses the service-managed permissions model. Custom execution role templates are not supported with self-managed permissions.
  • Activate trusted access with AWS Organizations. This creates the AWSServiceRoleForCloudFormationStackSetsOrgAdmin service-linked role in your management account.
  • You have your management account ID available for use in the trust policy.

Execution role template requirements

Your execution role template must meet all four of the following requirements. If any requirement is not met, CreateStackSet or UpdateStackSet returns a validation error.

1. A single IAM role resource

The template must contain exactly one resource, and that resource must be of type AWS::IAM::Role. Templates with multiple resources or non-IAM resources are rejected.

Note: Name the role with the required prefix stacksets-exec-custom- (for example, stacksets-exec-custom-my-role). The service’s default execution role is named stacksets-exec-<hash>, so this prefix is what lets StackSets tell a custom role from a default one by name alone. Roles without this prefix fail validation. Use the same role name across all stack instances. Don’t vary it per account or Region.

2. A trust policy for the StackSets service-linked role

The IAM role must include an AssumeRolePolicyDocument that grants assume-role access to the StackSets service-linked role in your management account. The trust policy must contain exactly one Statement and exactly one AWS principal, in this format:

arn:aws:iam::<management-account-id>:role/aws-service-role/stacksets.cloudformation.amazonaws.com/AWSServiceRoleForCloudFormationStackSetsOrgAdmin

Replace <management-account-id> with your organization’s management account ID.

If your organization uses a delegated administrator account for StackSets, the trust policy must still reference the organization management account rather than the delegated administrator account.

You can optionally strengthen the trust policy with a condition on your organization ID:

AssumeRolePolicyDocument:
  Version: "2012-10-17"
  Statement:
    - Effect: Allow
      Principal:
        AWS: arn:aws:iam::123456789012:role/aws-service-role/stacksets.cloudformation.amazonaws.com/AWSServiceRoleForCloudFormationStackSetsOrgAdmin
      Action: sts:AssumeRole
      Condition:
        StringEquals:
          aws:SourceOrgID: o-exampleorgid

3. A required output

The template must define a CloudFormation output with the key StackSetExecutionRoleName, and its value must be the name of the IAM role created by the template. StackSets uses this output to validate that the role name the template provisioned matches the ExecutionRoleName you passed when you created or updated the stack set. If the output is missing or the key is misspelled, the template fails validation.

4. No nested stacks or transforms

The template must not include:

  • Nested stack resources (AWS::CloudFormation::Stack).
  • CloudFormation transforms, such as AWS::Serverless-2016-10-31 or custom macros.

A working example

The following least-privilege template creates an execution role scoped to S3 bucket operations on buckets matching a naming prefix, plus the CloudFormation actions StackSets needs to drive stack operations in the member account.

AWSTemplateFormatVersion: "2010-09-09"
Description: Custom execution role for CloudFormation StackSets
Resources:
  StackSetExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: stacksets-exec-custom-my-role
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              AWS: arn:aws:iam::123456789012:role/aws-service-role/stacksets.cloudformation.amazonaws.com/AWSServiceRoleForCloudFormationStackSetsOrgAdmin
            Action: sts:AssumeRole
      Policies:
        - PolicyName: StackSetExecutionPolicy
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action:
                  - s3:CreateBucket
                  - s3:DeleteBucket
                  - s3:PutBucketPolicy
                  - s3:GetBucketPolicy
                Resource: "arn:aws:s3:::amzn-s3-demo-*"
              - Effect: Allow
                Action: cloudformation:*
                Resource: "*"
Outputs:
  StackSetExecutionRoleName:
    Value: !Ref StackSetExecutionRole
    Description: Name of the execution role used by StackSets

This template is an illustrative example. The cloudformation:* permissions on all resources are the minimum StackSets needs to drive stack operations in each member account. Narrowing them below this can cause stack operations to fail. Adjust the S3 statement to match the resources your workload uses.

Replace 123456789012 with your management account ID. Using !Ref on the role returns the role name dynamically, so you don’t need to repeat it in the output.

Creating a StackSet with a custom execution role template

Supply the template to CreateStackSet in one of two ways:

  • ExecutionRoleTemplateBody – the template body as an inline string (JSON or YAML).
  • ExecutionRoleTemplateUrl – the Amazon Simple Storage Service (Amazon S3) URL of the template file.

Specify either one of these. If you provide both, the operation returns an error.

Console view of the StackSet creation wizard showing the custom execution role template options, with the default option selected.

Figure 1: Console view of the configurable options when creating a StackSet custom execution role

Using the AWS CLI

aws cloudformation create-stack-set \
--stack-set-name my-stack-set \
--template-body file://my-stackset-template.yaml \
--permission-model SERVICE_MANAGED \
--execution-role-template-body file://execution-role-template.yaml \
--execution-role-name stacksets-exec-custom-my-role \
--capabilities CAPABILITY_NAMED_IAM

The --execution-role-name value must match the RoleName in your execution role template, and it must start with stacksets-exec-custom-. StackSets validates this prefix and returns an error if it does not match.

Custom execution role templates always require CAPABILITY_NAMED_IAM. This flag acknowledges that the templates create named IAM resources. The execution role template always creates a named IAM resource, because it must use the required stacksets-exec-custom- prefix through an explicit RoleName. If your workload template also uses transforms (such as AWS::Serverless-2016-10-31) or macros, add CAPABILITY_AUTO_EXPAND as well. Capabilities apply at the stack set level and pass down to each stack instance.

With an S3-hosted template:

aws cloudformation create-stack-set \
--stack-set-name my-stack-set \
--template-body file://my-stackset-template.yaml \
--permission-model SERVICE_MANAGED \
--execution-role-template-url https://s3.amazonaws.com/amzn-s3-demo-bucket/execution-role-template.yaml \
--execution-role-name stacksets-exec-custom-my-role \
--capabilities CAPABILITY_NAMED_IAM

Note: If you use an S3 URL, your credentials must have read access to the S3 object. The URL can be in path style (https://s3.amazonaws.com/my-bucket/key.yaml) or virtual-hosted style (https://my-bucket.s3.region.amazonaws.com/key.yaml).

Using the CloudFormation console

The create StackSet wizard defaults to Use default execution role, which is the AdministratorAccess role. To attach a custom execution role, select Set execution role and either paste an S3 URL or upload a local template file.

The console also asks for an IAM execution role name in a separate field. StackSets uses the name you enter in this field as the execution role name, not the RoleName value in the template. Make sure the name in the field still starts with the required stacksets-exec-custom- prefix.

StackSet creation wizard on the CloudFormation console defaulting to the AdministratorAccess execution role, with the Set execution role option available to add a custom role.

Figure 2: The StackSet creation wizard defaulting to the AdministratorAccess execution role, with the option to set a custom execution role

Updating the execution role template

To update the execution role template for an existing stack set, call UpdateStackSet with a new ExecutionRoleTemplateBody or ExecutionRoleTemplateUrl. The same validation requirements apply. When you update the execution role template, StackSets updates the role on every existing stack instance. You can’t specify deployment targets in the same call.

The --execution-role-name value is required only when you transition from the default execution role to a custom execution role. On subsequent updates to the execution role template, it’s optional.

aws cloudformation update-stack-set \
--stack-set-name my-stack-set \
--execution-role-template-body file://updated-execution-role-template.yaml \
--use-previous-template \
--capabilities CAPABILITY_NAMED_IAM

On the console, you can also change the execution role name without replacing the template. Select the Use current execution role tile to keep the existing template, and enter a new role name in the IAM execution role name field.

Console showing the Use current execution role tile selected, which keeps the existing template and changes only the execution role name.

Figure 3: Keeping the current execution role template and changing only the execution role name

On the console, choose the Replace current execution role tile and either paste an S3 URL or upload a new template file.

Console showing the Replace current execution role tile selected, with options to provide an S3 URL or upload a local template file.

Figure 4: Replacing the execution role template by providing an S3 URL or uploading a local template file

Setting up an output bucket

StackSets always stores the validated execution role template in a service-owned bucket. You can also configure a bucket you own, and StackSets writes a copy of the template there. This is useful when you want direct visibility into the stored template.

To configure a custom output bucket:

  • Create an S3 bucket in the same Region as your stack set.
  • Update the bucket policy to allow the CloudFormation service principal (cloudformation.amazonaws.com) to perform s3:PutObject on the bucket path.
  • Pass the bucket name using --stack-set-output-bucket on create-stack-set or update-stack-set.
  • StackSets writes the copy at s3://<bucket>/aws-cloudformation-stacksets/<stack-set-id>/output.json, where the colons in the stack set ID are replaced by periods.

Reverting to the default execution role

To revert a StackSet to the default AdministratorAccess execution role, set UseAdminExecutionRole to true:

aws cloudformation update-stack-set \
--stack-set-name my-stack-set \
--use-admin-execution-role \
--use-previous-template

Reverting switches StackSets back to the default AdministratorAccess execution role, but it does not remove the custom execution role or its bootstrapping stack from member accounts. There is no automated cleanup today. Delete them manually in each member account if you no longer need them.

On the console, choose the Use default execution role tile during update.

Console view of the Use default execution role tile selected when updating a stack set.

Figure 5: Reverting to the default AdministratorAccess execution role by selecting the Use default execution role tile when updating a stack set

Viewing the current execution role template

Call DescribeStackSet to see the configured execution role template. If an output bucket is configured, the response includes the StackSetOutputBucketPath field, which points to the stored template in S3.

aws cloudformation describe-stack-set \
--stack-set-name my-stack-set

On the console, go to StackSet details, and under StackSet info expand Execution role template. The View in S3 button opens the stored template in a new tab. During update, the Use current execution role tile shows the template currently in use.

StackSet info tab on the console showing the configured execution role template with a View in S3 button, alongside the stack set ARN, admin role ARN, permission model, drift status, and stack set status.

Figure 6: The StackSet info tab showing the configured execution role template, where the View in S3 button opens the stored template in a new tab

If you configure a custom output bucket, StackSetOutputBucketPath in the DescribeStackSet response is configuration. It shows where StackSets writes the output file, not whether the write succeeded. Check S3 directly to confirm the object is present.

Common validation errors

CreateStackSet and UpdateStackSet validate your execution role template against the preceding requirements and return a ValidationException when something doesn’t match. Most error messages restate a requirement: more than one resource, a missing output key, a role name that doesn’t start with stacksets-exec-custom-, and so on. Three are easier to miss:

  • The account ID in the trust policy principal Amazon Resource Name (ARN) must be your organization’s management account, even when you’re using a delegated administrator.
  • The IAM role in the template must not set a Path property (other than /). This requirement isn’t obvious from the role’s shape.
  • When you update the execution role template, you can’t also specify deployment targets. StackSets always reprovisions the role in every existing stack instance.

For the full list of error strings and causes, see the Troubleshooting section of the User Guide.

If the execution role stack fails to create in a specific member account, that account’s stack instance deployment fails. Other accounts in the same deployment aren’t affected. Check the stack events in the failing member account for details, then retry by creating new stack instances for those accounts.

Get started

With custom execution role templates, you can keep the cross-account convenience of StackSets while bringing your permissions in line with least-privilege guidance. To learn more about the service, see the AWS CloudFormation product page.

 


About the authors

Tanvi Ravindra Malali

Tanvi Ravindra Malali

Tanvi Malali is a Delivery Consultant on the AWS Industries Healthcare team, where she helps healthcare customers design and deliver production workloads on AWS. She is a member of the AWS Technical Field Community for Infrastructure as Code. Tanvi is based in New York.

Idriss Laouali Abdou

Idriss Laouali Abdou

Idriss Abdou is a Sr. Product Manager Technical on the AWS Infrastructure-as-Code team based in Seattle. He focuses on improving developer productivity through CloudFormation and StackSets Infrastructure provisioning experiences. Outside of work, you can find him creating educational content for thousands of students, cooking, or dancing.

How Klaviyo processes 3 billion daily events at scale with Amazon MSK Express

Post Syndicated from Jonathan Li original https://aws.amazon.com/blogs/big-data/how-klaviyo-processes-3-billion-daily-events-at-scale-with-amazon-msk-express/

Klaviyo (NYSE: KVYO) is an autonomous business-to-consumer (B2C) customer relationship management (CRM) platform used by more than 200,000 brands to understand and act on customer relationships in real time. Every personalized email, SMS, and push notification that Klaviyo sends depends on a streaming pipeline that ingests roughly 3 billion events per day. These events range from email opens and website visits to purchase completions and cart abandonments.

In this post, we share how Klaviyo migrated from RabbitMQ to Amazon Managed Streaming for Apache Kafka (Amazon MSK) Express brokers. We also show how Amazon MSK Express let a small team scale its event pipeline ahead of Black Friday/Cyber Monday (BFCM) 2025. With Amazon MSK Express, Klaviyo delivered more than 22.7 billion messages, up 25 percent year over year, and scaled back down afterward over a five-day period.

The challenge

Events are the lifeblood of Klaviyo’s platform. Every customer interaction flows through the streaming pipeline. Klaviyo’s previous RabbitMQ-based event infrastructure supported the platform through years of rapid growth. As volume climbed, scaling it beyond a certain point became increasingly difficult, so the team set out to build a foundation for the next stage of scale, with three requirements:

  • Absorb extreme bursts – BFCM drives roughly 7 times normal event volume, concentrated into five days.
  • Serve two service level objective (SLO) classes on one pipeline – Real-time triggers (5-second SLO) and analytics aggregates (20-minute SLO) share infrastructure, so slower work can never hold up time-critical events.
  • Zero data loss – Every event is a customer interaction that drives personalized marketing, so nothing can be silently dropped.

The replacement had to sustain peaks of 170,000 events per second, absorb a 7 times spike, and scale back down afterward.

Solution overview

Klaviyo rebuilt its event gateway infrastructure on Apache Kafka, choosing Amazon MSK Express brokers as its fully managed streaming backbone serving as the front door for all inbound events.

Klaviyo event pipeline on Amazon MSK Express, from event sources through the event gateway and orchestrator to consumers and delivery channels

Figure 1: Klaviyo’s event gateway architecture on Amazon MSK Express, showing the gRPC publisher, p10/p20/p30 priority topics, the Kubernetes orchestrator, retry topics and dead-letter queue, Amazon S3 failure capture, and a second gateway cluster in eu-central-1

The solution includes the following key components:

  • Event gateway cluster – The entry point for all inbound events (email opens, clicks, site activity, API calls), running on express.m7g.4xlarge brokers in the US, with a second cluster in the EU.
  • Three-tier priority topics – Events are routed to priority topics (p10, p20, p30) with 360 partitions each. The partition count is set by the consumer topology rather than the broker count: the event orchestrator runs as StatefulSets with one pod per partition, which comes to 90 pods in each of four Kubernetes clusters and 360 pods in total.
  • Graduated retry architecture – Five retry delay levels with exponential backoff, plus a dead-letter queue, so no event is silently dropped.

Priority-based event processing

Rather than treating all events equally, Klaviyo routes events to priority tiers through a gRPC publisher proxy. This design degrades gracefully under extreme load. High-priority events (such as purchase confirmations that trigger transactional flows) are processed first, while lower-priority events (such as batch analytics updates) can tolerate higher latency.

Critically, Klaviyo runs one unified set of processors across all three priority levels instead of standing up separate infrastructure per level. That consolidation cut costs by roughly 30 percent through improved resource utilization. For the design in depth, see Building a Distributed Priority Queue in Kafka.

Resilient event publishing

Klaviyo designed its event publisher to survive failure at every layer. A publish that fails against one Kafka cluster has several fallback mechanisms to make sure that there will be no permanent data loss. Most failures recover automatically, and the rest are preserved for replay. Over one three-month window, roughly 20,000 events were recovered without human intervention, out of approximately 300 billion processed in that period.

Klaviyo also retains seven days of event history for replay in the case of downstream incidents.

For more on Klaviyo’s eventing design, see Rebuilding Event Infrastructure at Scale and Building a Resilient Event Publisher with Dual Failure Capture.

Scaling for Black Friday with MSK Express

The clearest demonstration of this architecture came during BFCM 2025, the largest ecommerce event of the year, when the pipeline carried the traffic behind Klaviyo customers’ most revenue-critical campaigns across five consecutive days.

The scale-out timeline

Period Brokers Context
Steady state (through September 2025) 12 Normal daily processing of ~3B events
Early October 2025 18 First capacity increase ahead of the holiday season
Late October–November 2025 (BFCM) 60 Full Black Friday / Cyber Monday capacity
December 2025 (post-BFCM) 18 Optimized steady-state fleet

The team scaled the event gateway cluster up several-fold over about seven weeks, held it through Cyber Monday, then scaled it back down in December.

Why MSK Express made this possible

Three capabilities of MSK Express were critical to making this operational with a lean team.

No storage provisioning – Express brokers remove storage sizing and provisioning entirely. You pay for the data ingested into the cluster and the data stored in it, per GB per hour, and all stored data is replicated across three Availability Zones for high availability. This pay-as-you-go model eliminates wasted capacity costs. For Klaviyo, it meant a large holiday scale-out required no storage capacity planning at all.

Intelligent Rebalancing – Adding brokers to an Apache Kafka cluster normally means redistributing partition data across the new brokers, which traditionally requires careful manual planning, monitoring, and throttle management. MSK Express Intelligent Rebalancing automates that redistribution without manual intervention or performance degradation, and AWS reports that Express brokers rebalance partitions 180 times faster than Standard brokers. For Klaviyo, this meant adding brokers at scale for BFCM without an engineer owning partition reassignment at scale.

Built-in high availability – Based on AWS internal testing, Express brokers recover from failure 90 percent faster than Standard brokers, thanks to storage improvements. A replacement node starts up with almost no disruption to the rest of the cluster, rather than triggering a significant rebalance. Express brokers are also highly available by default, with the service managing the critical cluster and topic configurations that would otherwise need hand-tuning.

Results

Since migrating to Amazon MSK Express, Klaviyo has achieved the following results:

  • Multi-fold broker scale-out in under two months to absorb BFCM peak traffic, with a clean scale-down afterward.
  • Approximately 30 percent cost reduction from running unified processors across all three priority levels instead of separate infrastructure per level.
  • 5-second SLO held for real-time event triggers at a peak of 170,000 events per second.
  • 22.7 billion messages delivered over BFCM 2025, up 25 percent year over year.
  • Multi-Region since May 2026, with a second event gateway cluster in eu-central-1 serving European customers.
  • MSK Express adopted across Klaviyo’s event gateway clusters in both US and EU AWS Regions.

As Klaviyo’s engineering team wrote in Rebuilding Event Infrastructure at Scale:

“Moving to managed Kafka infrastructure on AWS MSK was one of those decisions that keeps paying dividends.”

It freed up engineers to spend their time building features rather than operating messaging infrastructure.

Key learnings

Based on Klaviyo’s experience building and operating this architecture, here are key takeaways for teams considering a similar approach:

  • Design for extreme elasticity from day one – Klaviyo’s BFCM traffic drives a multi-fold surge in event volume into five days. Designing partition layouts, topic structures, and consumer groups to accommodate elastic scaling before you need it avoids painful re-architecture under pressure.
  • Size partitions for your consumers, not your brokers – Klaviyo’s 360 partitions per topic come from its consumer topology (one orchestrator pod per partition), which stays fixed while the broker fleet scales up and back down underneath it. Coupling partition count to broker count would have forced a partition change in the middle of the holiday ramp.
  • Scale down as deliberately as you scale up – Klaviyo returned to a right-sized fleet after BFCM rather than carrying peak capacity all year. Because Express bills storage per GB rather than per provisioned volume, scaling down left no stranded storage cost behind.
  • Run multiple SLO classes on one pipeline – A single set of processors serves all three priority tiers, which cut costs by roughly 30 percent. Priority routing still protects latency: real-time triggers held their 5-second SLO at a peak of 170,000 events per second.
  • Build fault tolerance into every layer – Cross-cluster failover, a dead-letter queue, and an Amazon Simple Storage Service (Amazon S3) fallback mean individual failures don’t cause data loss. Express broker recovery keeps a lost broker from turning into a cluster-wide disruption.

Conclusion

Klaviyo’s journey from RabbitMQ to Amazon MSK Express demonstrates how a managed streaming service helps high-growth companies operate mission-critical event infrastructure at massive scale without proportionally growing their operations team. By combining MSK Express Intelligent Rebalancing with thoughtful architecture design (priority-based topics, graduated retry queues, and layered failure capture), Klaviyo’s lean infrastructure team scaled 5 times during the largest ecommerce event of the year.

Klaviyo’s use of Amazon MSK has since grown beyond the event pipeline. Its change data capture (CDC) infrastructure now runs on Amazon MSK Express as well. The team is also evaluating migrating its remaining self-managed Apache Kafka clusters on Amazon Elastic Compute Cloud (Amazon EC2), which serve data lake workloads, to MSK.

If you’re operating Apache Kafka workloads that require elastic scaling, operational simplicity, or both, consider Amazon MSK Express brokers for your next streaming workload.


About the authors

Jonathan Li

Jonathan Li

Jonathan is a Lead Engineer at Klaviyo, where his Data Automation team owns most of the company’s Apache Kafka infrastructure and tooling, including its change data capture (CDC) platform also on MSK. He previously worked on the team that built Klaviyo’s event gateway on Amazon MSK Express, the system described in this post.

Jason Palmer

Jason Palmer

Jason is a Senior Technical Account Manager (TAM) at AWS Enterprise Support, based in Seattle, Washington. With over 6 years at AWS, Jason combines deep technical expertise with a genuine passion for people — helping enterprise customers transform complex challenges into scalable cloud solutions.

Mazrim Mehrtens

Mazrim Mehrtens

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

Announcing in-place upgrades from Standard brokers to Express brokers for Amazon MSK

Post Syndicated from Ankita Mishra original https://aws.amazon.com/blogs/big-data/announcing-in-place-upgrades-from-standard-brokers-to-express-brokers-for-amazon-msk/

Amazon Managed Streaming for Apache Kafka (Amazon MSK) now supports in-place upgrades from Standard brokers to Express brokers. With in-place upgrade, you can modernize your existing MSK Provisioned cluster to Express brokers through a fully managed workflow, designed to minimize application changes while helping to maintain high availability throughout. Express brokers deliver increased stability at higher throughputs, scale up to 20 times faster, and recover up to 90% faster than standard Apache Kafka brokers. The in-place upgrade is a direct path to those benefits. Until now, adopting Express brokers meant standing up a new MSK Provisioned cluster and migrating both your data and your applications to it. That cut-over added weeks or months of cross-team coordination and put application availability at risk. The in-place upgrade removes that work entirely. Amazon MSK modernizes your existing cluster to Express brokers through a fully managed workflow, with no new cluster, no application changes, and no downtime, turning a multi-month migration into a few hours.

With the in-place upgrade, Amazon MSK adds Express brokers to your existing cluster and moves topics for you, preserving both the cluster endpoint and your Kafka topic offsets. As partitions move, MSK reassigns their replicas to the Express brokers and transfers partition leadership through Kafka’s standard leader-election process. Producers and consumers continue using the same topics and the same cluster endpoint without interruption. Applications can continue serving traffic throughout the migration, delivering a zero-downtime client experience. Because the upgrade uses Kafka-native protocols that preserve topic offsets, your stateless and stateful applications (including Apache Flink and Kafka Streams) can resume from their exact position, with no reprocessing, errors, or duplicates. The upgrade can be reversed until you decommission the Standard brokers, keeping you in control throughout the process.

Prerequisites

In-place upgrade to Express brokers is available for MSK Provisioned clusters configured with Standard brokers, in all AWS Regions where MSK Express brokers are supported. Before you begin, confirm your cluster meets the following requirements. These are also validated when you assess upgrade readiness with the API, described in the next section:

  • Kafka version: The cluster must run Apache Kafka version 3.9 with KRaft metadata management.
  • Three Availability Zones: The cluster must be deployed across three Availability Zones.
  • No tiered storage support: Clusters with tiered storage enabled are not supported.
  • Topic and broker configuration requirements: Express brokers enforce a set of best-practice configurations to maintain stability and high availability. Before initiating upgrade, confirm your cluster meets the following Express requirements:
    • replication.factor=3.
    • min.insync.replicas=2.
    • unclean.leader.election.enable = false.
    • segment.ms set to at least 60,000 milliseconds.
    • max.message.bytes set to no more than 8 MiB.
    • max.compaction.lag.ms set to at least 24 hours.
    • A supported broker instance type.
    • Per-broker partition counts within the Express broker partition quota.

The upgrade process

The following steps use the AWS Command Line Interface (AWS CLI). You can also perform them programmatically with the AWS Management Console or SDK. To perform the upgrade with an AI agent, use the managing-amazon-msk Agent Skill, which powers agents to manage the upgrade process end to end. All sections of this post can be automated with the managing-amazon-msk Agent Skill.

You can upgrade your existing Standard brokers on M5, M7g or M8g instances to Express brokers on M7g or M8g instances. Express brokers on AWS Graviton4-based M8g instances deliver up to 15% lower compute costs, up to 45% lower P99 produce latency, and 2x faster recovery when consumers fall behind, than Express brokers on M7g. You also no longer pay the broker-side cost when moving data across Availability Zones, which reduces total cross-AZ data transfer costs by 50%.

Pre-upgrade: Assess upgrade readiness

To confirm your cluster is ready for in-place upgrade to Express brokers, use the CreateAssessment API. The assessment validates your broker and topic configurations against Express requirements and returns its findings, including any changes to make first. Address any changes that the assessment flags as blockers before you initiate the upgrade. When you initiate the upgrade, MSK automatically re-validates your configuration and proceeds only after all checks pass.

Create the assessment

To create an assessment, specify the target Express instance type. Express brokers are available in the M7g and M8g instance families. You choose the family, and the upgrade keeps your broker size and broker count. For example, if you are on Standard kafka.m5.large, specify express.m7g.large or express.m8g.large. Clusters with Standard brokers on M8g instances can also upgrade to Express brokers on M8g instances:

aws kafka create-assessment \
--region "$AWS_REGION" \
--cluster-arn "$CLUSTER_ARN" \
--assessment-type UPDATE_BROKER_TYPE \
--assessment-parameters TargetInstanceType=express.m8g.large

Check the assessment status

To check the assessment status, use the following and wait until Status shows COMPLETE (assessments typically finish in about two minutes):

aws kafka describe-assessment \
--region "$AWS_REGION" \
--cluster-arn "$CLUSTER_ARN" \
--assessment-arn "$ASSESSMENT_ARN"

List assessment findings

To read the findings after the assessment is complete, use:

aws kafka list-assessment-findings \
--region "$AWS_REGION" \
--cluster-arn "$CLUSTER_ARN" \
--assessment-arn "$ASSESSMENT_ARN"

ERROR findings are blocking and must be resolved before initiating the upgrade. WARNING and INFO findings are informational. Resolve any blocking findings before continuing.

Performing the upgrade

The in-place upgrade to Express brokers is a managed workflow that you drive at your own pace.

Step 1: Initiate the upgrade

To initiate the upgrade using the CLI, use the UpdateBrokerType API. It takes four inputs:

  • --cluster-arn, the ARN of the cluster you’re upgrading.
  • --current-version, the cluster’s current version (to get it, use the DescribeCluster API).
  • --target-instance-type, a combined string naming your current Standard instance type and the target Express instance type, joined with a hyphen. For example, to upgrade a cluster from kafka.m7g.large Standard brokers to express.m8g.large Express brokers, set the target to kafka.m7g.large-express.m8g.large.
  • --topic-reassignment, how to move topics to Express brokers:
    • AUTO: Amazon MSK manages the topic migration for you. It validates your configuration, provisions Express brokers matching the count and size of your Standard brokers and moves every topic from Standard to Express in safe, managed batches. Your applications keep producing and consuming against the same cluster endpoint throughout. After all topics are on Express and you have validated your applications, you complete the upgrade to decommission the Standard brokers.
    • MANUAL: Amazon MSK provisions the Express brokers but moves no topics until you reassign them yourself, giving you a controlled, topic-by-topic experience. You move and validate topics at your own pace, as described in Step 2.

For example:

aws kafka update-broker-type \
--cluster-arn "$CLUSTER_ARN" \
--current-version "$CURRENT_VERSION" \
--target-instance-type "$TARGET_INSTANCE" \
--topic-reassignment AUTO

Step 2: Move topics (controlled mode only)

When you initiate in controlled mode (--topic-reassignment MANUAL), MSK adds the Express brokers but moves no topics until you drive the reassignments. Wait until the cluster returns to Active with both Standard and Express brokers. Then move topics with the StartTopicReassignment API.

You can selectively move topics with the --topics-to-include and --topics-to-exclude wildcard patterns, and set the direction with --target-instance-type. To move topics to Express brokers, pass your Express instance type ($EXPRESS_INSTANCE, for example express.m8g.large). To move topics back to your Standard brokers, pass your Standard instance type ($STANDARD_INSTANCE, for example kafka.m7g.large). Start with lower-risk topics, validate application performance on Express, then continue.

To complete a migration, all topics (including internal topics) must be moved to the Express brokers. After you finish testing with application topics, confirm you also move internal topics to Express brokers.

Move a specific set of topics onto Express:

For example, to move the orders.* topics to Express brokers:

aws kafka start-topic-reassignment \
--cluster-arn "$CLUSTER_ARN" \
--target-instance-type "$EXPRESS_INSTANCE" \
--topics-to-include 'orders.*'

This moves every topic whose name matches the include pattern onto Express brokers. Patterns are regular expressions, so orders.* can match many topics. It does not name a single topic.

Hold specific topics back from Express:

To move all orders.* topics except the payments topics to Express brokers:

aws kafka start-topic-reassignment \
--cluster-arn "$CLUSTER_ARN" \
--target-instance-type "$EXPRESS_INSTANCE" \
--topics-to-include 'orders.*' \
--topics-to-exclude 'orders\.payments.*'

This moves topics such as orders.created and orders.shipped onto Express, and the orders.payments topics stay on Standard. MSK applies the exclude patterns after the include patterns, so a topic that matches both stays where it is. You can move the held-back topics later in a separate reassignment.

Move all topics at once:

You can also move all topics at once to Express brokers. This is useful if you’ve tested a subset of topics on Express, and are ready to complete moving the remaining topics:

aws kafka start-topic-reassignment \
--cluster-arn "$CLUSTER_ARN" \
--target-instance-type "$EXPRESS_INSTANCE" \
--topics-to-include '.*'

This broad include pattern moves every topic, you can narrow the pattern (or exclude) to move topics incrementally.

Stop in-flight reassignment:

To stop a reassignment, you need its topic reassignment operation ARN. The StartTopicReassignment API returns it in the response. You can also get it from the ListTopicReassignments API, which lists every reassignment on the cluster with its operation ARN and status.

aws kafka list-topic-reassignments --cluster-arn "$CLUSTER_ARN"

Pass the ARN to stop-topic-reassignment:

aws kafka stop-topic-reassignment \
--cluster-arn "$CLUSTER_ARN" \
--topic-reassignment-operation-arn "$OP_ARN"

This stops the in-progress reassignment identified by its operation ARN. Topics that already moved stay on Express brokers. Only one reassignment can run on a cluster at a time, so wait until list-topic-reassignments shows the status as STOPPED. Then start a new reassignment with the same start-topic-reassignment command and patterns you used before. The new reassignment gets its own operation ARN, so use that new ARN if you need to stop it later. To move topics back to Standard instead, set --target-instance-type to $STANDARD_INSTANCE, as shown in the following rollback example.

Roll back process:

To roll back a set of topics by name or wildcard, pass the Standard instance type (for example, kafka.m7g.large) in the --target-instance-type:

aws kafka start-topic-reassignment \
--cluster-arn "$CLUSTER_ARN" \
--target-instance-type "$STANDARD_INSTANCE" \
--topics-to-include 'orders.*'

Targeting the Standard instance type moves the matching topics back to Standard while the rest stay on Express. Move topics again after the issue is resolved and you’re ready to move the topics back to Express. To roll back all topics from Express brokers to Standard brokers, first use the StartTopicReassignment API with .* as the topic wildcard and your Standard instance type as the target instance type:

aws kafka start-topic-reassignment \
--cluster-arn "$CLUSTER_ARN" \
--target-instance-type "$STANDARD_INSTANCE" \
--topics-to-include '.*'

Then, decommission the Express brokers by calling UpdateBrokerType with the Standard instance type as the target instance type:

aws kafka update-broker-type \
--cluster-arn "$CLUSTER_ARN" \
--current-version "$CURRENT_VERSION" \
--target-instance-type "$STANDARD_INSTANCE"

Step 3: Monitor progress

Track the overall upgrade on the Cluster operations tab on the console, or with the DescribeClusterOperation API, passing the operation ARN returned by update-broker-type. In Amazon CloudWatch, graph PartitionCount, BytesInPerSec, and BytesOutPerSec by broker ID to watch partitions and throughput shift from the Standard brokers to the Express brokers.

To check whether the upgrade operation is in progress, complete, or failed, use:

aws kafka describe-cluster-operation --cluster-operation-arn "$OPERATION_ARN"

To show migration progress per topic, so you can see which topics have moved to Express and which are still in flight, use:

aws kafka list-topic-reassignments --cluster-arn "$CLUSTER_ARN"

To list each broker node with its BrokerNodeType, so you can identify which brokers are Standard and which are Express as leadership shifts, use:

aws kafka list-nodes --cluster-arn "$CLUSTER_ARN"

The upgrade takes a few hours depending on cluster size and data volume.

Step 4: Validate applications on Express

After every topic has moved to Express brokers, check your workload before you complete the upgrade. The Standard brokers stay in the cluster during this step, so you can still move topics back to them if you find an issue.

To confirm that all partitions have moved, run list-topic-reassignments. Then check that LeaderCount is 0 on every Standard broker. After that:

  • Verify that topics, partitions, and consumer groups are present.
  • Confirm cluster health: ActiveControllerCount is 1 and OfflinePartitionsCount is 0.
  • Confirm producer and consumer throughput and performance align with pre-upgrade baselines.
  • Confirm stateful applications (for example, Apache Flink and Kafka Streams) remain healthy and continue processing after partition leadership moves to Express brokers.

If a topic has problems, move it back to Standard with the rollback commands in Step 2. Run this check for at least one full processing cycle of your workload before you continue.

Step 5: Complete the upgrade

MSK waits for you to confirm before it removes the Standard brokers. When your validation is done, choose Complete Upgrade on the console, or call UpdateBrokerType again with only the Express instance type:

aws kafka update-broker-type \
--cluster-arn "$CLUSTER_ARN" \
--current-version "$CURRENT_VERSION" \
--target-instance-type "$EXPRESS_INSTANCE"

Amazon MSK decommissions the Standard brokers, and the cluster returns to the ACTIVE state as an Express-only cluster. This step is final: once the Standard brokers are removed, reverting to Standard requires creating a new cluster and migrating to it with Amazon MSK Replicator. After the upgrade completes, update or retire any monitoring alerts and dashboards that are specific to your former Standard brokers.

Step 6: Post-upgrade optimization

After the upgrade, intelligent rebalancing is paused on your cluster. New Express clusters have it turned on by default, but upgraded clusters do not. With intelligent rebalancing, you can scale your clusters up or down by editing the broker count in your clusters in a single action, and Amazon MSK will keep partitions evenly distributed across brokers. Because MSK provisions one Express broker for each Standard broker, your cluster may have more capacity than your workload needs. Turn on intelligent rebalancing first, then use your post-upgrade metrics to right-size the cluster by reducing the broker count or changing the instance size as required.

Additionally, Express brokers surface an improved bootstrap endpoint for client connections. The boot-XXX.clustername.kafka.us-east-1.amazonaws.com endpoints are managed by MSK Express and improve distribution of connections for metadata requests across your brokers. You can update applications to use these new endpoints at any time to improve reliability and connection distribution. Your applications configured with broker ID-based bootstrap endpoints (for example, b-1.clustername.kafka.us-east-1.amazonaws.com) will continue to function after the upgrade, so this step is optional.

Additional considerations

Beyond these prerequisites, plan for the following during the upgrade window:

  • Billing: During the upgrade, MSK adds Express brokers to your existing cluster, matching the size and count of your Standard brokers. For example, for a cluster with 3 kafka.m5.large Standard brokers MSK adds 3 express.m7g.large Express brokers during the upgrade. Because both broker sets are provisioned throughout the upgrade period, you are charged for both broker types until the upgrade completes. There is no additional charge for the upgrade itself.
  • Restricted operations: Some cluster modification operations, such as version upgrades, broker configuration changes, and authentication or monitoring changes, are blocked during the upgrade to prevent configuration mismatches between broker types. Kafka read and write, topic create and delete, and broker reboots continue to work. MSK pauses migration during scaling operations and resumes automatically afterward.
  • Monitoring metrics: Standard and Express brokers emit different CloudWatch metrics. Plan to update dashboards and alarms as topics move to Express. In particular, replace KafkaDataLogsDiskUsed with StorageUsed, and retire Amazon Elastic Block Store (Amazon EBS) storage metrics such as BurstBalance.

Get started with Express brokers on Amazon MSK

The in-place upgrade from Standard brokers to Express brokers gives you a straightforward path to the performance, faster scaling, and lower operational overhead of Express brokers, without application changes, cross-team coordination, or reprocessing state. Amazon MSK handles the broker provisioning, topic movement, and offset preservation for you, whether you let MSK move every topic automatically or move topic by topic. What used to take months of migration effort can now complete in hours.

To move even faster, you can use the managing-amazon-msk skill with your AI coding agent (such as Kiro or any MCP-compatible agent) through the AWS MCP server. The skill assesses your cluster’s compatibility with Express requirements and provides commands to resolve any issues, generates a proof-of-concept package to validate Express performance for your workload, and recommends a right-sized Express cluster footprint.

In-place upgrade to Express brokers is available for MSK Provisioned clusters configured with Standard brokers, in all AWS Regions where MSK Express brokers are supported. To get started, see the Amazon MSK Developer Guide.

 


About the authors

Ankita Mishra

Ankita Mishra

Ankita is a Product Manager for Amazon Managed Streaming for Apache Kafka. She works closely with AWS customers to understand their needs for real-time analytics and high throughput, low latency streaming workloads. Working backwards from their needs, she helps drive the MSK roadmap and deliver new innovations that help AWS customers focus on building novel streaming applications.

Ravindranath Kakarla

Ravindranath Kakarla

Ravindranath is a Senior Software Development Engineer for Amazon Managed Streaming for Apache Kafka. He builds the systems that run customers’ real-time, high-throughput streaming workloads, and recently led the launch of in-place migration from Standard to Express brokers. He also works on cross-region disaster recovery and data distribution, helping customers replicate their streaming data across AWS Regions. Working backwards from customer needs, he focuses on making MSK resilient and simple to operate, so customers can focus on building novel streaming applications.

Ashley Millette

Ashley Millette

Ashley is a Specialist Solutions Architect for Streaming and Analytics at AWS. She partners with customers to design and implement real-time data streaming architectures using services like Amazon MSK helping them build scalable, cost-effective pipelines that turn data in motion into actionable insights. She is passionate about simplifying complex streaming workloads and enabling customers to modernize their data infrastructure with confidence.

Simon Peyer

Simon Peyer

Simon is a Solutions Architect at AWS based in Switzerland. He is a practical doer and passionate about connecting technology and people using AWS Cloud services. A special focus for him is data streaming and automations. Besides work, Simon enjoys his family, the outdoors, and hiking in the mountains.

Introducing Amazon EMR Serverless Flex: Run non-urgent Spark jobs at a discount

Post Syndicated from Neil Mukerje original https://aws.amazon.com/blogs/big-data/introducing-amazon-emr-serverless-flex-run-non-urgent-spark-jobs-at-a-discount/

With Amazon EMR Serverless, you can run Apache Spark applications without provisioning or managing clusters. You submit jobs, EMR Serverless allocates the compute, scales it during execution, and releases it when the job finishes. There are no clusters to tune and no idle capacity to pay for. Since launch, customers have used EMR Serverless to run production extract, transform, and load (ETL) pipelines, machine learning (ML) feature engineering, and large-scale data transformations, replacing Spark clusters that required dedicated engineering effort to operate.

Customers also have workloads that aren’t time-sensitive. On EMR on EC2 or self-managed Spark clusters on EC2, teams use Amazon Elastic Compute Cloud (Amazon EC2) Spot Instances to run these workloads on spare compute capacity at a lower cost. For top EMR customers, EC2 Spot Instances are a key cost-optimization lever, with many running a portion of their workloads on spare capacity. For customers looking to modernize from clusters to serverless to lower their operational overhead, the absence of an equivalent option on EMR Serverless meant they could only move part of their platform. The time-sensitive workloads came over, but the cost-optimized workloads running on spare capacity stayed on EC2 Spot Instances. Spare capacity support on EMR Serverless has been one of the most requested features, with customers telling us it’s a prerequisite for full migration.

Today we are launching Amazon EMR Serverless Flex, a new execution option that runs Spark batch jobs on spare compute capacity at a fixed 60 percent discount compared to standard pricing. With Flex, EMR Serverless now offers two execution options: Standard for workloads that need predictable start times and dedicated resources, and Flex for workloads where cost matters more than execution-time predictability. Customers who previously split their Spark platforms between EMR Serverless and EMR on EC2 or self-managed clusters on Spot Instances can now consolidate onto a single serverless platform. Customers who didn’t consider EMR Serverless at all, because spare capacity support was missing, can now evaluate EMR Serverless as a full replacement for their cluster-based deployments.

Why Flex matters for your Spark platform

When we talk to customers running Spark at scale, we see a common pattern: two tiers of workloads with different cost and reliability requirements.

Time-sensitive production workloads – ETL pipelines that feed dashboards, ML models, and downstream applications on a schedule. These need fast startup, dedicated compute, and predictable completion times. On EMR Serverless, these run on the Standard execution option.

Non-urgent batch workloads – Pre-production validation, test and development runs, backfills, nightly batch transformations, one-time data loads, and recurring reports with generous processing windows. These jobs are cost-sensitive but time-flexible. They need to finish, but not on a strict deadline.

On EMR on EC2 or self-managed Spark clusters on EC2, customers often deploy non-urgent workloads on Spot Instances. But without a spare-capacity option on EMR Serverless, moving to serverless meant giving up the cost lever on non-urgent batch workloads.

What it takes to run Spark on spare capacity today

On EMR on EC2, running Spark on Spot Instances is a shared responsibility between the service and the customer.

What the EMR service provides: EMR on EC2 provides the infrastructure features for running workloads on spare capacity:

  • Instance fleets with Spot allocation strategies (capacity-optimized) that spread capacity requests across instance types and Availability Zones.
  • Graceful decommissioning that gives Spark time to migrate shuffle data and finish running tasks when a Spot Instance receives a 2-minute termination notice.
  • Spark resilience enhancements (decommission-aware task scheduling, exclusion of decommissioning nodes, and shuffle block tracking) that help Spark recover from node loss without getting stuck on fetch failures.

What customers implement: Based on best practices that have evolved over the years, here’s what teams have built and maintained on top of the preceding EMR features:

  • Instance fleet diversification – Select the right mix of instance types across instance variants (m5, m5a, m5d, r5, r5a, r5d) that meet vCPU and memory requirements. Use the Spot Instance Advisor to target types with lower interruption rates. Configure allocation strategies and fallback behavior.
  • Multi-AZ placement – Launch clusters targeting multiple Availability Zones to tap into the capacity in the entire AWS Region.
  • Driver protection with YARN node labels – Configure YARN node labels to pin the Spark driver to On-Demand core nodes, keeping it off Spot task nodes. If the driver lands on a Spot Instance and that instance is reclaimed, the entire job fails. Setting this up requires YARN label configuration, node-label expression settings in Spark, and ongoing validation.
  • Configuring resilience and decommissioning settings – Tune decommissioning timeouts, understand how the Spark resilience enhancements work, and configure them correctly for each workload.
  • Ongoing tuning and debugging – Monitor interruption rates by instance type, adjust fleet composition as Spot pricing shifts, debug capacity-related job failures, and maintain the configuration as EMR release versions change.

What Flex handles for you

EMR Serverless Flex applies all of these spare-capacity best practices on your behalf. You add one parameter to your job submission with no fleet configuration or YARN tuning. EMR Serverless takes on the responsibility of running your workloads on spare capacity:

  • AZ selection – EMR Serverless evaluates spare capacity pools across Availability Zones in the AWS Region and places workers where capacity is most available.
  • Instance diversification – EMR Serverless spreads executors across multiple instance types and generations so that reclamation of one instance type doesn’t hit all workers at once.
  • Driver protection – The Spark driver runs on a dedicated Standard worker that isn’t subject to spare capacity reclamation. The driver holds job state (the directed acyclic graph, stage progress, and task assignments) so protecting it prevents job failure, without YARN node labels to configure.
  • Decommission-aware scheduling and worker exclusion – When a Flex worker receives a 2-minute reclamation notice, EMR Serverless stops scheduling new tasks on that worker and excludes it from future assignments. The Spark resilience enhancements that EMR developed for handling node loss (decommission-aware task scheduling, proactive worker exclusion, and shuffle block tracking) are applied automatically.
  • Automatic task retry – Spark’s built-in fault tolerance retries affected tasks on healthy Flex workers. The job continues without manual intervention.
  • Shuffle offload with Serverless Storage (optional) – With EMR Serverless Storage, shuffle data is written to remote storage instead of local disk. When a reclaimed executor’s tasks are retried, the new executor reads the stored upstream shuffle output instead of recomputing it, reducing the fetch-failure problem for shuffle-heavy jobs.

All existing EMR Serverless capabilities (AWS Lake Formation fine-grained access control, AWS Graviton support, AWS Glue Data Catalog integration, and data source connectors) work the same with Flex jobs.

What happens when you run a Flex job

Here is the life cycle of a Flex job from submission to completion:

  1. Job submission – You submit a Spark job with Flex enabled. EMR Serverless accepts the job and begins acquiring spare compute capacity.
  2. Capacity acquisition – EMR Serverless selects an Availability Zone within the chosen Region where spare capacity is most available and requests workers across a diverse set of instance types and generations. The Spark driver starts on a dedicated Standard worker.
  3. Job execution – Executors run on Flex workers. The job proceeds as it would on Standard using the same Spark runtime and APIs.
  4. If capacity is reclaimed – When a Flex worker receives a reclamation notice, EMR Serverless excludes it and stops scheduling new tasks on it. Spark retries the affected tasks on healthy Flex workers. If you have Serverless Storage enabled, retried tasks read stored shuffle data instead of recomputing upstream stages. Billing for the reclaimed worker stops at reclamation.
  5. Completion – The job completes and results are written to the output location.
  6. Failure handling – If no executor joins the driver within 20 minutes of job start, the job fails. To recover from failures, resubmit the job using the best practices you apply to restart a failed job.

How Flex workers are billed

Flex workers are billed at a fixed 60 percent discount on vCPU-hours and memory GB-hours compared to Standard workers. The Spark driver runs on a Standard worker and is billed at the Standard rate. The discount is fixed and unlike EC2 Spot doesn’t fluctuate with supply and demand.

Each worker is billed for the time it was part of the job run, per second with a 1-minute minimum. When a Flex worker is reclaimed, billing for that worker stops. For example, if a 10-minute job runs 20 Flex workers and 3 of them are reclaimed after 5 minutes, you are billed for 17 workers at 10 minutes and 3 workers at 5 minutes.

Flex spend appears as separate line items in AWS Cost Explorer and on your bill, so you can distinguish Flex spend from Standard spend. Flex also works with job-level cost allocation tags, so you can continue attributing costs by team or project. For pricing details, see Amazon EMR pricing.

Flex in practice: Resilience and cost

We ran a 103-query decision-support benchmark (derived from TPC-DS 1 TB and 3 TB scale factor) on Spark to compare Flex and Standard at two data scales. Both runs used the same queries, worker configuration, and release label (emr-7.14.0).

Scale factor Execution Queries completed Wall-clock time Estimated cost Total executors used Executors reclaimed Task failures
1 TB Standard 103 of 103 11.5 min $5.68 12 0 0
Flex 103 of 103 12.3 min $2.07 (64% savings) 15 1 0
3 TB Standard 103 of 103 12.4 min $6.29 12 0 0
Flex 103 of 103 16.1 min $2.32 (63% savings) 21 1 0

Resilience: In each Flex run, we observed one executor reclaimed mid-job. EMR Serverless excluded the reclaimed worker, and Spark retried the affected tasks on healthy executors. All 103 queries completed in both runs, with zero job resubmissions.

Cost: For this benchmark, we saw Flex reduce estimated cost by about 63 percent at both data scales, from $5.68 to $2.07 at 1 TB, and from $6.29 to $2.32 at 3 TB.

Note: The actual savings and frequency of reclamations will vary by workload, Region, and available spare capacity at the time of execution. We recommend running your own workloads on both Flex and Standard to establish a baseline. This workload is derived from the TPC-DS Benchmark and isn’t comparable to published TPC-DS Benchmark results, as this implementation doesn’t comply with all requirements of the TPC-DS Benchmark.

Runtime tradeoff – The 1 TB Flex run took 7 percent longer than Standard. The 3 TB run took 30 percent longer. The gap widened at larger scale because the reclaimed executor’s tasks needed more time to recompute. Flex jobs can also take longer to start if spare capacity isn’t immediately available. Flex works well for any job where the completion deadline is flexible, including short jobs. A job that runs in 10 minutes on Standard and 12 minutes on Flex is a good candidate if it doesn’t have a strict service level agreement (SLA).

Getting the best results from Flex

Three practices we recommend to get the most from Flex:

Avoid top-of-the-hour peaks

We observe that spare capacity availability drops when many jobs start simultaneously at the top of each hour. Shifting your job start times by even a few minutes (for example, submitting at 9:20 instead of 9:00) reduces contention for spare capacity and improves the chance of a fast start.

Run outside business hours when possible

Spare capacity is most available when overall compute demand is lower. We see the best availability when customers schedule non-urgent workloads to run after 6:00 PM in the Region, or on weekends, giving Flex jobs access to deeper capacity pools with fewer interruptions.

Use Serverless Storage

EMR Serverless Storage writes shuffle data to remote storage, so retried tasks read stored intermediate results instead of recomputing upstream stages. This reduces the runtime cost of interruptions on shuffle-heavy jobs and adds another layer of resilience.

Getting started

Flex is a job-run setting. You create your EMR Serverless application as usual and add one parameter when submitting a job:

aws emr-serverless start-job-run \
    --application-id <application-id> \
    --execution-role-arn <job-role-arn> \
    --flex-execution '{"enabled": true}' \
    --job-driver '{
        "sparkSubmit": {
            "entryPoint": "s3://<bucket>/scripts/my-spark-job.py"
        }
    }'

In EMR Studio, select the Enable Flex execution checkbox when submitting a job, as shown in the following screenshot:

EMR Studio job submission form with the Enable Flex execution checkbox selected

Figure 1: Enable Flex execution checkbox in the EMR Studio job submission form

You can run Flex and Standard jobs on the same application. For step-by-step instructions, see the Amazon EMR Serverless User Guide.

Conclusion

In this post, we shared how Amazon EMR Serverless Flex runs non-urgent Spark batch jobs on spare compute capacity with built-in resilience features, closing a gap that previously blocked customers from modernizing their entire Spark platforms onto EMR Serverless.

To get started, pick a non-critical job, submit it with --flex-execution '{"enabled": true}' and compare the cost and runtime against your Standard baseline. For more detail, see the Amazon EMR Serverless User Guide.


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.

Manjeet Chayel

Manjeet Chayel

Manjeet serves as Big Data Manager, Worldwide Specialist Solutions Architects at AWS, where he leads a global team of specialist architects driving customer-facing engagements across Amazon EMR, AWS Glue, and the broader Big Data Analytics portfolio.

Announcing 30-minute timeout for on-demand AWS Lambda Event Functions

Post Syndicated from Tarun Rai Madan original https://aws.amazon.com/blogs/compute/announcing-30-minute-timeout-for-on-demand-aws-lambda-event-functions/

AWS Lambda now supports a 30-minute function timeout for Event Functions that run on demand, doubling the previous 15-minute limit for synchronous, asynchronous, and event source mapping (ESM) invocations. On Lambda Managed Instances, synchronous invocations also support up to 30 minutes, while asynchronous and ESM invocations keep the 90-minute timeout we announced in September 2026. You can now run AI inference, media transcoding, and financial calculations on Lambda for spiky or steady-state traffic without re-architecting your applications. The new timeout also applies when you use Lambda durable functions or invoke your functions from AWS Step Functions Standard workflows.

Evolution of function timeout on Lambda

Lambda launched in 2014 with a 60-second function timeout, which we extended to 5 minutes in 2015 and to 15 minutes in 2018.

Lambda now offers three form factors: Event Functions, Web Functions, and MicroVMs. Event Functions process events from more than 200 AWS event sources through synchronous, asynchronous, and ESM invocations. With Web Functions, you can run HTTP servers on Lambda with an HTTP-native, multi-concurrent programming model and opt-in multi-Region endpoints. MicroVMs give each user or session an isolated environment for running user-generated or AI-generated code.

By default, all three form factors run on demand, with Lambda provisioning compute as requests arrive. For steady-state traffic, Event Functions can also run on the Lambda Managed Instances capacity provider. With Lambda Managed Instances, you can process multiple concurrent requests per instance and choose specialized compute configurations, without managing infrastructure. You can also use EC2 pricing options such as AWS Savings Plans and Reserved Instances. Figure 1 shows the form factors.

The three Lambda form factors: Event Functions, Web Functions, and MicroVMs

Figure 1: Lambda form factors

Each form factor has its own duration limit (Table 1). Until today, Event Functions had a 15-minute timeout, except for asynchronous and ESM invocations on Lambda Managed Instances, which we extended to 90 minutes in September 2026.

Lambda durable functions run on demand and on Lambda Managed Instances, and provide application-level checkpointing and workflow-as-code. Your code saves execution state with step() and wait() operations and resumes from the last checkpoint after a failure. A durable execution (the complete lifecycle of a durable function) can run for up to 1 year, but each invocation within it is bound by the function timeout.

Customers told us that 15 minutes was still too short for many Event Functions workloads that run on demand, and for synchronous invocations on Lambda Managed Instances. Agentic AI requests that chain model calls and tool invocations can take longer than 15 minutes to return a result. Media transcoding and file conversion jobs often run past 15 minutes when input files are large. Financial calculations such as Monte Carlo simulations, bond pricing, and portfolio risk analysis are memory-intensive and need more continuous execution time. Report generation across multiple data sources can also exceed 15 minutes during peak volumes. ETL steps triggered by Amazon Simple Queue Service (Amazon SQS) or Amazon Simple Storage Service (Amazon S3) events can run just as long. Many of these workloads have spiky traffic that doesn’t justify steady-state capacity on Lambda Managed Instances.

With today’s launch, Event Functions support up to 30 minutes for synchronous, asynchronous, and ESM invocations, and up to 90 minutes for asynchronous and ESM invocations on Lambda Managed Instances. Table 1 shows the maximum durations across Lambda form factors.

Duration Event Functions Web Functions MicroVMs
On demand (default) Lambda Managed Instances
Without durable execution

Synchronous: 30 minutes

Asynchronous: 30 minutes

ESM: 30 minutes

Synchronous: 30 minutes

Asynchronous: 90 minutes

ESM: 90 minutes

15 minutes 8 hours (running and suspended)
With durable execution

Synchronous: 30 minutes

Asynchronous: 1 year

ESM: 30 minutes

Synchronous: 30 minutes

Asynchronous: 1 year

ESM: 90 minutes

– –

Table 1: Supported durations on Lambda form factors

Configuring the 30-minute function timeout

You can configure any Event Function with a timeout of up to 30 minutes (1,800 seconds). For asynchronous and ESM invocations on Lambda Managed Instances, you can configure up to 90 minutes (5,400 seconds). Lambda rejects higher values with a validation error. Your function runs exactly as before, with the same runtime, handler, IAM execution role, and virtual private cloud (VPC) configuration. The Init phase keeps its existing limits of 10 seconds for functions that run on demand and 15 minutes on Lambda Managed Instances. Provisioned concurrency and Lambda SnapStart, which aren’t available on Lambda Managed Instances, keep their 15-minute initialization limit.

To set the timeout, update your function configuration using the AWS Command Line Interface (AWS CLI):

aws lambda update-function-configuration \
--function-name my-demo-function \
--timeout 1800 \
--region us-east-1

To set the timeout in an AWS Serverless Application Model (AWS SAM) template, use the Timeout property:

MyFunction:
  Type: AWS::Serverless::Function
  Properties:
    FunctionName: my-demo-function
    Runtime: python3.14
    Handler: app.handler
    Timeout: 1800
    MemorySize: 2048

You can also update the timeout in the Lambda console under Configuration > General configuration (Figure 2), where synchronous test invocations now run for up to 30 minutes. If you use an AI coding assistant such as Kiro, Claude Code, or Codex, you can install the Agent Toolkit for AWS and configure the timeout with natural language prompts.

Lambda console General configuration page with the function timeout set to 30 minutes

Figure 2: Configuring Lambda function timeout

The new timeout applies to invocations that start after you update the function. For event source mappings, allow a few minutes for the change to propagate. Amazon CloudWatch metrics, AWS CloudTrail, and AWS X-Ray continue to capture the full invocation lifecycle. For details, see monitoring Lambda functions and monitoring durable functions.

For Event Functions that run on demand, the 30-minute timeout is available in all commercial AWS Regions. For synchronous invocations on Lambda Managed Instances, it is available in all AWS Regions where Lambda Managed Instances is available. Standard AWS Lambda pricing applies.

30-minute timeout and durable functions

The 30-minute function timeout and durable functions are complementary. The function timeout (--timeout) controls how long each individual invocation can run, whereas the durable execution timeout (ExecutionTimeout in --durable-config) controls the total elapsed time from execution start to completion. On replay after a failure, the function re-executes from the beginning and skips completed steps.

Functions that run on demand: Each durable function invocation can run for up to 30 minutes, whether you invoke it synchronously, asynchronously, or through an event source mapping. When you invoke the function asynchronously, the durable execution can run for up to 1 year. When you invoke it synchronously through the Invoke API or a function URL, the durable execution is limited to 30 minutes, and Lambda rejects higher values. ESM invocations have the same 30-minute limit.

Lambda Managed Instances: Synchronous invocations can run for up to 30 minutes, and asynchronous and ESM invocations can run for up to 90 minutes. When you invoke the function asynchronously, the durable execution can run for up to 1 year. The durable execution is limited to 30 minutes for synchronous invocations and 90 minutes for ESM invocations.

For idempotent jobs, such as an ETL step triggered by Amazon SQS, the extended timeout alone might be enough. A failed invocation returns the message to the queue for a fresh attempt. For jobs where re-execution is expensive, combine the extended timeout with durable functions. A 25-minute inference run that fails at minute 22 restarts from zero without checkpoints, but resumes from its last checkpoint with durable functions.

Invocation behavior: Synchronous, asynchronous, and event source mappings

Synchronous invocations (up to 30 minutes): Synchronous invocations now support up to 30 minutes, whether the function runs on demand or on Lambda Managed Instances. If another AWS service invokes your function synchronously, that service applies its own timeout, so verify that it supports the longer duration before you raise the function timeout. Set your client’s read and socket timeouts longer than the function timeout. For example, increase the read timeout of your AWS SDK client when you call the Invoke API. On Lambda Managed Instances, Lambda applies the 30-minute limit to synchronous invocations even if the function timeout is higher, and the GetFunctionConfiguration API reports the configured value.

Asynchronous invocations (up to 30 minutes, or up to 90 minutes on Lambda Managed Instances): If the function fails or times out, Lambda applies your configured retry policy (up to two retries by default). It then routes failed events to your dead-letter queue or on-failure destination.

Event source mappings (up to 30 minutes, or up to 90 minutes on Lambda Managed Instances): For SQS, set the queue’s visibility timeout to at least six times the function timeout, so at least 3 hours for a 30-minute function. This gives Lambda enough time to retry if a function is throttled while it processes a previous batch. Lambda validates this when you create the event source mapping, but it doesn’t prevent later changes to queue or function settings that create a mismatch.

For Amazon Kinesis Data Streams and Amazon DynamoDB Streams, Lambda processes one batch per shard at a time by default, so longer invocations slow how quickly each shard is read. Monitor the IteratorAge metric and increase the parallelization factor if records start to back up. Longer invocations also mean that a failure late in a batch wastes more work. Enable partial batch failure reporting so that Lambda retries only the failed records. You can use it with SQS, Amazon Kinesis, DynamoDB Streams, Amazon Managed Streaming for Apache Kafka (Amazon MSK), and self-managed Apache Kafka event source mappings.

Invocations from Amazon MQ (ActiveMQ and RabbitMQ) and Amazon DocumentDB (with MongoDB compatibility) event source mappings remain limited to 14 minutes. The same limit applies to Kafka event source mappings that were created before November 19, 2026, and don’t use provisioned mode. To use the 30-minute timeout with Kafka, create a new event source mapping or turn on provisioned mode for your existing one. For these mappings, keep the function timeout at 14 minutes (840 seconds) or less.

Considerations and best practices

Longer-running functions need extra care with concurrency and components that can expire mid-invocation, such as network connections and credentials.

Concurrency: Concurrency equals requests per second multiplied by average duration in seconds. At the same request rate, a function that runs for 30 minutes instead of 15 needs twice the concurrency. For example, 1 request per second at 30 minutes each needs 1,800 concurrent executions. Check your account concurrency quota and reserved concurrency settings before you raise the timeout. On Lambda Managed Instances, check the maximum scaling limits of your capacity provider.

Networking: Make sure idle connection timeouts on downstream services such as Amazon Relational Database Service (Amazon RDS), Amazon ElastiCache, and external APIs accommodate the full function duration. If your function routes traffic through a NAT gateway, which drops idle connections after 350 seconds, send keep-alive packets. For long synchronous invocations, also turn on TCP keep-alive on the calling client. DNS caching depends on your runtime and HTTP client. For example, the AWS SDK for Java relies on the JVM DNS cache, which on some configurations never refreshes. Set a short DNS TTL, such as 5 seconds for the JVM, and configure custom HTTP clients to re-resolve hostnames.

Credentials: If your function acquires temporary credentials or tokens, verify they remain valid for the full execution duration or refresh them in the background.

Idempotency: Lambda does not guarantee exactly-once processing, and longer-running functions widen the window for retries and duplicate deliveries. Use Powertools for AWS Lambda to make operations such as payments or database writes idempotent. In durable functions, steps have at-least-once execution semantics by default. The SDK skips completed steps during replay, but steps that fail before checkpointing might re-execute. You can use execution names as idempotency keys for durable functions.

Conclusion

The 30-minute function timeout brings longer continuous execution to Event Functions that run on demand and to synchronous invocations on Lambda Managed Instances. It complements the 90-minute timeout for asynchronous and ESM invocations on Lambda Managed Instances that we launched in September 2026. Workloads such as AI inference, media transcoding, and report generation that exceed 15 minutes can now run on Lambda without architectural workarounds, for spiky or steady-state traffic. If your workloads need a longer timeout, let us know on the AWS Lambda Roadmap GitHub page.

To get started, update your function’s timeout configuration and deploy. For details, see Configure Lambda function timeout in the AWS Lambda Developer Guide. For sample code that shows long-running functions with durable checkpointing, see durable functions examples. To learn more, visit the AWS Lambda product page.

 


About the authors

Tarun Rai Madan

Tarun Rai Madan

Tarun is a Principal Product Manager at Amazon Web Services (AWS), where he leads product areas across AWS Serverless Compute, including developer and agentic experiences, event-driven data ingestion, orchestration, and compute for data-intensive workloads. His work centers on removing infrastructure complexity so developers can concentrate on their differentiated business logic. Before joining AWS, he was an engineering leader in the semiconductor industry, where he developed high-performance processors for data center, wireless, and automotive applications.

Dan Slusariuc

Dan Slusariuc

Dan is a Software Development Manager at AWS, where he leads the Lambda Frontend team. His team builds the backend services that receive and route Lambda function invocations. He also leads compliance and availability for Lambda. In his prior role, Dan was a Software Development Engineer in Amazon Advertising, where he helped build the engine that generates banners for products listed on Amazon.

Snehil Ameta

Snehil Ameta

Snehil is a Software Development Engineer at AWS, where he works on AWS Lambda. He focuses on Lambda scalability and availability, and leads capabilities such as Lambda response streaming and Lambda Managed Instances. In his prior role, Snehil worked in Amazon seller services, where he helped build its recommendation service.

Get more from your Kiro investment with credit pooling: A guide for admins

Post Syndicated from Kirankumar Chandrashekar original https://aws.amazon.com/blogs/devops/get-more-from-your-kiro-investment-with-credit-pooling-a-guide-for-admins/

You’ve turned on credit pooling, or you’re about to, and now the decisions are yours: how many seats to keep, how many additional credits to buy, and what limit each developer gets. Set limits too tight and developers get blocked in the middle of a task. Set them too loose and one runaway automation job can drain the pool and pause Kiro for everyone. The data to make these calls is already in your AWS account, in your Kiro user activity reports. This post shows you how to read it.

The launch post, Share Kiro credits across your team with credit pooling, published November 4, 2026, introduced credit pooling: a shared pool of Kiro credits that every user in the pool draws from. Credits one developer doesn’t need automatically become available to a teammate who does.

Credit pooling is for organizations. It works with Kiro profiles that use AWS IAM Identity Center, Okta, or Microsoft Entra ID. Individual Kiro subscriptions, such as a personal account with a social login, can’t share credits through a pool, and credit pooling isn’t available in AWS GovCloud (US).

This post is a hands-on guide for admins. It describes how the credit pool behaves day to day and how to size it and dial in your limit settings from your own usage data. It also covers the best practices that keep it running smoothly.

How credit pooling works

In credit pooling, a seat is one user’s access to the pool, and each seat adds 500 monthly credits. When someone leaves, removing them frees their seat for someone else. For details, see Manage seats.

The following diagram shows how each seat’s 500 monthly credit inclusion flows into one shared pool, together with any additional credits you buy, and how every user draws from that pool. It also compares pooling with per-user credits.

How credit pooling works: each seat adds 500 monthly credits to one shared credit pool, additional credits can be bought at any time and are good for 12 months, and every user draws from the pool. Before pooling, each user’s credits are set by their subscription tier and credits a user doesn’t need go unused. With pooling, heavy users draw on credits light users don’t need before you buy anything extra.

Figure 1: How each seat’s 500 monthly credits flow into one shared pool that every user draws from, compared with per-user credits

Here’s a short summary of the core mechanics and how they play out once your pool is running. Each billing cycle, every $20 seat adds 500 credits to the pool, so 100 seats add 50,000. Every seated user draws from the pool, including users that run Kiro in headless mode, such as continuous integration and continuous delivery (CI/CD) pipelines. These credits continue to reset at the end of each billing cycle, but now they’re available for anyone in the pool to use.

When the pool runs out

Admins can buy additional credits at any time in the Kiro console. Additional credits roll over and are good for 12 months after purchase.

Which credits are used first

Monthly credits are used first because they reset at the end of each billing cycle. After the monthly credits run out, Kiro draws from additional credits, starting with the oldest purchase.

Where the savings come from

Credit pooling can help you save in three ways:

  • Shared credits absorb uneven usage. Your heaviest users draw on credits teammates don’t need before you buy anything extra.
  • Seats follow your team. Add seats as people join, and remove a user to release their seat when they leave.
  • Additional credits only when you need them. Buy them at any time, and they roll over for 12 months.

Walkthrough

Today, all you have is a daily report of each user’s consumption. This walkthrough turns that report into a plan in four steps. Step 1 loads the reports into Amazon Athena. Step 2 shows how each month used the pool. Step 3 recommends a seat count and a buffer of additional credits. Step 4 suggests a limit for each user.

Prerequisites

Before you start, confirm that the following are in place.

  • User activity reports turned on for your Kiro profile. The analysis in this post is based on the daily user activity CSV reports that Kiro writes to an Amazon Simple Storage Service (Amazon S3) bucket. To set them up, including the bucket policy Kiro needs to write to the bucket, see Turn on the CSV report.
  • Access to Amazon Athena, with permission to read the report location and write query results. For example, attach the AWS managed policy AmazonAthenaFullAccess, and allow s3:GetObject and s3:ListBucket on your report bucket.
  • The number of seats you bought for a prepaid pool, or the number of users in a postpaid pool. You manage seats under Access management > Credit sharing in the Kiro console. The activity report can’t give you this number.
  • An administrator role with the credit pooling permissions, so you can change seats, limits, and additional credits after the analysis.

Right-size your pool from your usage data

Your per-user activity reports record each user’s consumption.

Where to start depends on whether you already have data. If your team already uses Kiro, the activity report has recorded every user’s consumption all along, and the following queries run on that history as-is. Run Steps 2 and 3 now, before you pick a seat count. Step 3 tells you what that count needs to be.

If you are new to Kiro, there is nothing to analyze. Buy one seat for each person who needs access. That is the license, and the pool follows from it at 500 credits per seat. Keep a small buffer of additional credits (best practice 4), and start with generous limits (best practice 2). Either way, run one full billing cycle on pooling and come back to Step 2.

Step 1: Create the table and view

In the LOCATION line, replace the four capitalized placeholders. Use the Amazon S3 location you chose when you turned on the CSV report.

  • YOUR-BUCKET: the bucket name from your Amazon S3 location, for example amzn-s3-demo-bucket.
  • YOUR-PREFIX: the folder after the bucket name, for example user-activity-reports.
  • ACCOUNT-ID: the 12-digit AWS account where your users are subscribed.
  • REGION: the Region where you installed your Kiro profile, for example the US East (N. Virginia) Region (us-east-1).

For example, if your S3 location is s3://amzn-s3-demo-bucket/user-activity-reports/, the LOCATION line becomes s3://amzn-s3-demo-bucket/user-activity-reports/AWSLogs/111122223333/KiroLogs/user_report/us-east-1/. Keep the AWSLogs/.../KiroLogs/user_report/ part exactly as written. Kiro creates those folders itself.

CREATE EXTERNAL TABLE kiro_user_activity_raw (
c1 STRING, c2 STRING, c3 STRING, c4 STRING, c5 STRING,
c6 STRING, c7 STRING, c8 STRING, c9 STRING, c10 STRING,
c11 STRING, c12 STRING, c13 STRING, c14 STRING, c15 STRING,
c16 STRING, c17 STRING, c18 STRING, c19 STRING, c20 STRING
)
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'
WITH SERDEPROPERTIES ('separatorChar' = ',', 'quoteChar' = '"')
LOCATION 's3://YOUR-BUCKET/YOUR-PREFIX/AWSLogs/ACCOUNT-ID/KiroLogs/user_report/REGION/';

Then create the view that the queries in the next steps read from:

CREATE OR REPLACE VIEW kiro_user_activity AS
WITH headers AS (
-- The first row of each report file names its columns.
SELECT "$path" AS report_file,
ARRAY[c1, c2, c3, c4, c5, c6, c7, c8, c9, c10,
c11, c12, c13, c14, c15, c16, c17, c18, c19, c20] AS names
FROM kiro_user_activity_raw
WHERE c1 = 'Date'
),
report_rows AS (
SELECT "$path" AS report_file,
ARRAY[c1, c2, c3, c4, c5, c6, c7, c8, c9, c10,
c11, c12, c13, c14, c15, c16, c17, c18, c19, c20] AS vals
FROM kiro_user_activity_raw
WHERE c1 <> 'Date'
)
-- Pick each value by its column name in that file's header.
-- A column the file doesn't have comes back NULL.
SELECT TRY(vals[array_position(names, 'Date')]) AS report_date,
TRY(vals[array_position(names, 'UserId')]) AS user_id,
TRY(vals[array_position(names, 'Client_Type')]) AS client_type,
TRY(vals[array_position(names, 'Credits_Used')]) AS credits_used,
TRY(vals[array_position(names, 'User_Email')]) AS user_email,
TRY(vals[array_position(names, 'Usage_Limit')]) AS usage_limit,
TRY(vals[array_position(names, 'Subscription_Tier')]) AS subscription_tier
FROM report_rows
JOIN headers USING (report_file);

Three details in that setup are worth knowing:

  • OpenCSVSerde, not ROW FORMAT DELIMITED. Kiro quotes some fields, and the simpler row format leaves the quote marks on, which breaks any join on user id.
  • The view finds columns by name, not position. Kiro has added columns to the report over time, so a position can hold a different column in an older file. The view reads each file’s header row and picks values by name. A column a file doesn’t have, like usage_limit in older reports, comes back empty.
  • The table reads the first 20 columns, all as text. They must be text, because the first row of each file holds column names. Everything the queries use is within the first 14 columns, and anything past 20 is ignored. If a column the queries need ever moves past 20, add c21 and up to both the table and the view.

Confirm it worked before going further:

SELECT COUNT(DISTINCT user_id) AS users,
ROUND(SUM(CAST(credits_used AS DOUBLE)), 2) AS credits,
MIN(report_date) AS first_day,
MAX(report_date) AS last_day
FROM kiro_user_activity;

For an example 100-seat team with six months of reports, that returns:

users | credits | first_day | last_day
-------+-----------+------------+------------
90 | 245990.46 | 2026-05-01 | 2026-10-23

If that returns zero users, the LOCATION prefix is wrong. If user_id values come back wrapped in quote marks, the table was created with ROW FORMAT DELIMITED.

Step 2: Re-run every cycle and let the data correct your estimate

This is the query you come back to each cycle. It returns one row per closed month at today’s seat count, so one run shows your whole history. Change only the seat count. It answers the right-sizing question directly: at the seats I pay for now, which months overflow the pool, and how much sat unused?

WITH
-- ========================= EDIT ME =========================
inputs AS (
SELECT 100 AS seats -- the seats you pay for today, from the console
),
-- ======================= END EDIT ME =======================

-- Closed months only: the current month is not a full billing cycle yet.
per_user_month AS (
SELECT substr(a.report_date, 1, 7) AS month,
a.user_id,
SUM(CAST(a.credits_used AS DOUBLE)) AS credits
FROM kiro_user_activity a
WHERE date(a.report_date) < date_trunc('month', current_date)
GROUP BY substr(a.report_date, 1, 7), a.user_id
),

totals AS (
SELECT month,
COUNT(*) AS active_users,
SUM(credits) AS consumed,
SUM(GREATEST(credits - 500.0, 0)) AS beyond_own_seat,
approx_percentile(credits, 0.50) AS p50,
approx_percentile(credits, 0.90) AS p90,
MAX(credits) AS max_user
FROM per_user_month
GROUP BY month
)

SELECT
t.month,
i.seats,
t.active_users,
GREATEST(i.seats - t.active_users, 0) AS seats_never_used,
ROUND(t.consumed, 0) AS credits_consumed,
ROUND(GREATEST(i.seats * 500.0 - t.consumed, 0), 0) AS pool_credits_unused,
ROUND(GREATEST(i.seats * 500.0 - t.consumed, 0) * 0.04, 2) AS unused_credit_value_usd,
ROUND(t.beyond_own_seat
- GREATEST(t.consumed - i.seats * 500.0, 0), 0) AS credits_covered_by_sharing,
ROUND(GREATEST(t.consumed - i.seats * 500.0, 0), 0) AS additional_credits_needed,
ROUND(i.seats * 20.0
+ GREATEST(t.consumed - i.seats * 500.0, 0) * 0.04, 2) AS estimated_monthly_cost,
ROUND(t.active_users * 20.0
+ GREATEST(t.consumed - t.active_users * 500.0, 0) * 0.04, 2)
AS cost_if_never_used_seats_reclaimed,
ROUND(t.p90, 0) AS p90_credits_per_user,
ROUND(t.max_user, 0) AS max_credits_per_user
FROM totals t CROSS JOIN inputs i
ORDER BY t.month;

Sample output for the same team, one column per closed month. The current month is left out because it isn’t a full cycle:

month | 2026-05 | 2026-06 | 2026-07 | 2026-08 | 2026-09
------------------------------------+---------+---------+---------+---------+---------
seats | 100 | 100 | 100 | 100 | 100
active_users | 85 | 89 | 83 | 79 | 83
seats_never_used | 15 | 11 | 17 | 21 | 17
credits_consumed | 41863.0 | 44528.0 | 48003.0 | 38274.0 | 41943.0
pool_credits_unused | 8137.0 | 5472.0 | 1997.0 | 11726.0 | 8057.0
unused_credit_value_usd | 325.49 | 218.86 | 79.9 | 469.05 | 322.26
credits_covered_by_sharing | 10225.0 | 11214.0 | 13816.0 | 7654.0 | 9687.0
additional_credits_needed | 0.0 | 0.0 | 0.0 | 0.0 | 0.0
estimated_monthly_cost | 2000.0 | 2000.0 | 2000.0 | 2000.0 | 2000.0
cost_if_never_used_seats_reclaimed | 1700.0 | 1781.14 | 1920.1 | 1580.0 | 1677.74
p90_credits_per_user | 897.0 | 932.0 | 761.0 | 762.0 | 749.0
max_credits_per_user | 2022.0 | 2601.0 | 2368.0 | 1748.0 | 2768.0

For this team, credits that light users didn’t need covered 7,654 to 13,816 credits of heavier users’ demand every month, so it never bought additional credits. That’s how pooling can work. Even so, 2,000 to 11,700 credits went unused each month and 11 to 21 seats sat idle, which Step 3 turns into a plan.

Read it across, not down. If pool_credits_unused stays large for a couple of cycles, the seats behind it are not a one-off. Reclaim them from people who no longer need access and re-run next month to confirm.

If additional_credits_needed is climbing, buy additional credits earlier in the cycle rather than adding seats (see best practice 7). credits_covered_by_sharing, multiplied by $0.04, estimates what sharing saved you each month. When p90_credits_per_user and max_credits_per_user settle into a stable range, that is your signal to set limits with headroom above them.

seats_never_used counts seats with no activity that month, and cost_if_never_used_seats_reclaimed is your cost if you reclaimed them all. Treat it as a bound, not a target. Step 3 looks across several months before it recommends cuts.

The percentiles are your starting point for limits. p90_credits_per_user reflects your heavy users, and max_credits_per_user is the person who reaches a limit first. With fewer than a few dozen active users, lean on max. Step 4 suggests a limit for each person.

Step 3: Turn the numbers into a resizing plan

Step 2 shows what happened. This query turns that into a plan: seats to keep and reclaim, additional credits to hold, and what the change saves. In the EDIT ME block, set your seat count and how many closed months to look back over. Three months is a sensible default, because one quiet month doesn’t mean a seat is unneeded.

WITH
-- ========================= EDIT ME =========================
inputs AS (
SELECT 100 AS seats, -- the seats you pay for today, from the console
3 AS lookback_months -- closed months to base the plan on
),
-- ======================= END EDIT ME =======================

bounds AS (
SELECT i.seats,
date_trunc('month', current_date) AS this_month,
date_add('month', -i.lookback_months,
date_trunc('month', current_date)) AS since
FROM inputs i
),

-- Everyone who used Kiro since the window started, this month included,
-- needs a seat. Seats nobody used in that time are the ones to reclaim.
users AS (
SELECT COUNT(DISTINCT a.user_id) AS active_users
FROM kiro_user_activity a
CROSS JOIN bounds b
WHERE date(a.report_date) >= b.since
),

-- Credits consumed in each closed month of the window.
months AS (
SELECT substr(a.report_date, 1, 7) AS month,
SUM(CAST(a.credits_used AS DOUBLE)) AS consumed
FROM kiro_user_activity a
CROSS JOIN bounds b
WHERE date(a.report_date) >= b.since
AND date(a.report_date) < b.this_month
GROUP BY substr(a.report_date, 1, 7)
),

-- Never recommend more seats than you have, so every result stays sensible.
sized AS (
SELECT b.seats,
u.active_users,
LEAST(b.seats, u.active_users) AS rec
FROM bounds b
CROSS JOIN users u
),

-- Each window month at today's seats and at the recommended seats, with
-- anything past the pool bought as additional credits.
plan AS (
SELECT s.seats,
s.active_users,
s.rec,
MAX(m.consumed) AS busiest,
AVG(s.seats * 20.0
+ GREATEST(m.consumed - s.seats * 500.0, 0) * 0.04) AS cost_now,
AVG(s.rec * 20.0
+ GREATEST(m.consumed - s.rec * 500.0, 0) * 0.04) AS cost_resized
FROM sized s
CROSS JOIN months m
GROUP BY s.seats, s.active_users, s.rec
)

SELECT
seats,
active_users AS active_users_in_window,
rec AS recommended_seats,
seats - rec AS seats_to_reclaim,
ROUND(busiest, 0) AS busiest_month_credits,
rec * 500 AS recommended_pool_credits,
ROUND(GREATEST(busiest - rec * 500.0, 0), 0) AS additional_credits_to_keep,
ROUND(cost_now, 2) AS avg_monthly_cost_now,
ROUND(cost_resized, 2) AS avg_monthly_cost_resized,
ROUND(cost_now - cost_resized, 2) AS avg_monthly_savings
FROM plan;

Sample output for the same team at 100 seats, looking back over July through September:

seats | 100
active_users_in_window | 86
recommended_seats | 86
seats_to_reclaim | 14
busiest_month_credits | 48003.0
recommended_pool_credits | 43000
additional_credits_to_keep | 5003.0
avg_monthly_cost_now | 2000.0
avg_monthly_cost_resized | 1786.7
avg_monthly_savings | 213.3

recommended_seats is one seat for everyone who used Kiro in the lookback or so far this month, however lightly, and seats_to_reclaim is the rest. The report can’t tell you who joined last week or is on leave, so check the names in the Kiro console before you reclaim anything.

additional_credits_to_keep is how far your busiest month ran past the recommended pool. Keep at least that many additional credits on hand going into each cycle (best practice 4). That’s a balance to hold, not an amount to buy every month, so check what’s already in your pool on the Kiro dashboard and buy only the difference. If Step 2 shows consumption climbing, keep more than this.

The cost columns compare the lookback months at your current seats with their cost at the recommended seats, averaged per month. Each month costs $20 per seat plus $0.04 per credit used beyond the pool, counted in the month it’s used. For this example team, reclaiming 14 idle seats would save about $213.30 a month on average, roughly $2,600 a year if the pattern holds. In July, the busiest month, about $200 of the $280 in seat savings came back as additional credits, which is why the buffer matters.

Step 4: Find users whose limits need to change

Seats and the pool are half of right-sizing. Per-user limits are the other half. This query lists the people whose limit is out of step with what they use. It flags anyone whose busiest month in the lookback reached 80% of their limit, anyone who stayed under 25% of their limit every month, and anyone with no limit set. For each one it suggests a new limit: their busiest month plus 25%, rounded up to the nearest 100 and never below the 500 credits a seat adds to the pool. It only lowers limits for people active in every month of the lookback, so a new joiner isn’t cut after one quiet month. Adjust the thresholds in the EDIT ME block.

WITH
-- ========================= EDIT ME =========================
inputs AS (
SELECT 3 AS lookback_months, -- closed months to look back over
0.80 AS raise_at, -- raise if the busiest month reached 80% of the limit
0.25 AS lower_below, -- lower if every month stayed under 25% of the limit
1.25 AS headroom -- new limit = busiest month plus 25%
),
-- ======================= END EDIT ME =======================

bounds AS (
SELECT date_add('month', -i.lookback_months,
date_trunc('month', current_date)) AS since
FROM inputs i
),

-- Credits per user in each month of the window, this month so far included,
-- so a suggested limit is never below what someone has already used.
per_user_month AS (
SELECT a.user_id,
substr(a.report_date, 1, 7) AS month,
ROUND(SUM(CAST(a.credits_used AS DOUBLE)), 2) AS credits
FROM kiro_user_activity a
CROSS JOIN bounds b
WHERE date(a.report_date) >= b.since
GROUP BY a.user_id, substr(a.report_date, 1, 7)
),

-- Each user's plan, limit and email from their most recent report. On a pool,
-- Usage_Limit is the pool limit (999999 means none is set). On a subscription
-- (Pro, Pro+, Pro Max, Power), it's the tier's monthly credit allowance.
-- If one day has both, the pool row wins. Older reports have no limit
-- column, so the view returns NULL and they're skipped.
latest AS (
SELECT a.user_id,
max_by(a.user_email, a.report_date || IF(upper(a.subscription_tier) = 'POOLING', '1', '0')) AS user_email,
max_by(replace(upper(a.subscription_tier), '_', ''),
a.report_date || IF(upper(a.subscription_tier) = 'POOLING', '1', '0')) AS plan,
max_by(TRY_CAST(a.usage_limit AS DOUBLE),
a.report_date || IF(upper(a.subscription_tier) = 'POOLING', '1', '0')) AS lim
FROM kiro_user_activity a
CROSS JOIN bounds b
WHERE date(a.report_date) >= b.since
AND a.usage_limit IS NOT NULL
AND COALESCE(a.subscription_tier, '') <> ''
GROUP BY a.user_id
),

-- Suggested limit: the busiest month plus headroom, rounded up to the
-- nearest 100, and never below the 500 credits one seat brings to the pool.
-- months_active counts the closed months in the lookback with any use.
scored AS (
SELECT l.user_email,
l.plan,
COALESCE(l.lim, 999999) AS lim,
MAX(m.credits) AS busiest,
COUNT_IF(m.month < date_format(current_date, '%Y-%m')) AS months_active,
GREATEST(ceiling(MAX(m.credits) * i.headroom / 100) * 100, 500) AS new_limit,
i.lookback_months,
i.raise_at,
i.lower_below
FROM per_user_month m
JOIN latest l ON m.user_id = l.user_id
CROSS JOIN inputs i
GROUP BY l.user_id, l.user_email, l.plan, l.lim,
i.lookback_months, i.headroom, i.raise_at, i.lower_below
),

-- Lower a limit only for someone who used Kiro in every closed month of the
-- lookback, so a new joiner or someone back from leave isn't cut after one
-- quiet month.
flagged AS (
SELECT *,
CASE
WHEN plan <> 'POOLING' THEN 'limit when pooled'
WHEN lim >= 999999 THEN 'set limit'
WHEN busiest >= raise_at * lim THEN 'raise'
WHEN busiest < lower_below * lim
AND new_limit < lim
AND months_active = lookback_months THEN 'lower'
END AS action
FROM scored
)

SELECT user_email,
CASE plan WHEN 'POOLING' THEN 'Pool' WHEN 'PRO' THEN 'Pro' WHEN 'PROPLUS' THEN 'Pro+'
WHEN 'PROMAX' THEN 'Pro Max' WHEN 'POWER' THEN 'Power' ELSE plan END AS plan,
CAST(ROUND(busiest) AS BIGINT) AS busiest_month,
IF(lim >= 999999, 'none',
CAST(CAST(lim AS BIGINT) AS VARCHAR)) AS usage_limit,
IF(lim >= 999999, NULL,
ROUND(100.0 * busiest / lim, 0)) AS pct_of_limit,
action,
CAST(new_limit AS BIGINT) AS new_limit
FROM flagged
WHERE action IS NOT NULL
ORDER BY CASE action WHEN 'raise' THEN 1 WHEN 'set limit' THEN 2 WHEN 'lower' THEN 3 ELSE 4 END,

user_email;

Sample output for the same team, looking back over July through October so far:

user_email | plan | busiest_month | usage_limit | pct_of_limit | action | new_limit
---------------------+------+---------------+-------------+--------------+-------------------+-----------
[email protected] | Pool | 2768 | 3000 | 92.0 | raise | 3500
[email protected] | Pool | 994 | 1000 | 99.0 | raise | 1300
[email protected] | Pool | 913 | 1000 | 91.0 | raise | 1200
[email protected] | Pool | 838 | 1000 | 84.0 | raise | 1100
[email protected] | Pool | 471 | 500 | 94.0 | raise | 600
[email protected] | Pool | 513 | 3000 | 17.0 | lower | 700
[email protected] | Pool | 372 | 3000 | 12.0 | lower | 500
[email protected] | Pool | 144 | 1000 | 14.0 | lower | 500
[email protected] | Pool | 96 | 1000 | 10.0 | lower | 500
[email protected] | Pro | 1210 | 1000 | 121.0 | limit when pooled | 1600

The raise rows are the people closest to being blocked. In their busiest month, user021 used 994 of their 1,000 credits, so one heavy week might stop them. Raising it to 1,300 gives them room. A higher limit adds no cost until the credits are used.

The lower rows are people who use a small share of their limit, like user006, whose busiest month was 513 credits against a 3,000-credit limit. Lowering a limit doesn’t save money, because a credit costs the same whoever uses it. It limits the impact of a runaway automation job, so one person is less likely to drain the pool and block everyone. new_limit is never below what the user has already used this month, so lowering it doesn’t block them right away.

The limit when pooled rows are people still on a Pro, Pro+, Pro Max, or Power subscription. Their usage_limit is the tier’s monthly allowance, so above 100% means they need more than their tier includes, like user091. new_limit is the individual limit to allocate when you add them to the pool. Their usage is already counted in Step 3’s additional_credits_to_keep, so the buffer covers them too.

If several people in one group need the same change, change the group’s limit.

For the exceptions, set new_limit as an individual limit in the Kiro console. It takes priority over group and profile limits (best practice 2). Re-run this query each cycle to catch limits that need to move again.

Best practices for making credit pooling effective

These practices build on the numbers from the walkthrough and help you keep the pool sized without blocking anyone.

1. Learn your usage pattern first

Collect several months of data before you fine-tune anything. A couple of billing cycles show you who your heavy and light users are, how usage rises and falls through a sprint, and how quickly the pool draws down. Once you can see the trend, use the preceding analysis to size the pool and set limits.

2. Use the limit hierarchy strategically

With credit pooling, you can set per-user limits at three levels:

Level Priority Use it for
Individual Highest Setting a per-user limit that applies to a specific user (for example, a user that runs automations, or someone testing heavily)
Group Medium Setting a per-user limit that applies to all members of a group
Profile Lowest Setting a default limit applicable to all users

All limits are per-user. There are no aggregate caps at the group or profile level. A group limit sets the per-user cap for everyone in that group.

Where to start: If your team already uses Kiro, start from the limits Step 4 suggests. If you are new to Kiro, start with generous group and profile limits and tighten them after your first billing cycle, only where the data shows you need to. Over-constraining on day one creates friction and support tickets.

3. Group users by usage pattern

Consider grouping users by how they consume credits rather than only by org chart. For example, put heavy users (senior developers, machine learning engineers) in a group with a higher per-user limit, and light users (managers, reviewers) in a group with a lower one.

Grouping users by usage pattern: heavy users in a group with a higher per-user limit and light users in a group with a lower per-user limit, each drawing from the shared pool

Figure 2: Grouping users by usage pattern to apply different per-user limits

If you sync groups from your identity provider: Your existing synced groups likely mirror your org chart. Create groups for credit pooling. For example, keep your synced “Engineering” group for access management, but create separate “Kiro-Heavy-Users” and “Kiro-Standard-Users” groups to apply different per-user limits. Users can belong to multiple groups, and the highest limit wins.

4. Keep a buffer of additional credits

When the pool is empty, everyone stops. Watch your pool threshold alerts and buy additional credits before the pool runs low. Because additional credits roll over for 12 months, buying early doesn’t waste them. Step 3’s additional_credits_to_keep shows how many to hold, based on your busiest month.

5. Review and adjust monthly

The Kiro dashboard gives you three views for this:

  • Daily projected consumption with run-out date predictions.
  • Credit usage breakdown (monthly compared to additional credits).
  • Users sharing credits, credits left, and additional credits at a glance.

If you exhaust the monthly pool early, buy additional credits earlier in the cycle. If credits go unused, check whether some seats are inactive (best practice 7).

6. Use notifications to stay ahead

Credit pooling includes built-in alerts that notify admins at 80% and 100% by default:

  • Pool threshold alerts: Get notified when the pool drops below configured levels.
  • User usage alerts: Know when individual users approach their limits.
  • Seat utilization alerts: Know when assigned seats near the number you bought.

Send these to the people who can act on them.

7. Right-size seats, and use credits rather than seats for headroom

A seat is an access license first and a credit contribution second. Treat them as two separate questions.

Seats with zero usage are the first place to look. You pay $20/month for a seat whether anyone signs in or not, and the seats_to_reclaim figure from Step 3 shows how many have gone unused for the whole lookback. Reclaim those from people who no longer need access.

Lightly used seats are a different matter. Don’t cut a license from someone who uses Kiro occasionally because their consumption is low. Their unused credits already go to the pool.

For headroom, buy credits rather than seats. If demand runs ahead of your pool, buy additional credits. Monthly credits reset at the end of the cycle. Additional credits last 12 months.

Things to keep in mind

  • When the pool runs out, usage stops for everyone in it. Kiro blocks further usage, whatever each user’s limit, until you add credits.
  • Mid-cycle limit changes take effect immediately. If you lower a user’s limit below their current consumption, they’re blocked right away. If you increase their limit, they can immediately resume their AI use. Plan limit changes at the start of a billing cycle when possible.
  • In a prepaid pool, seats are billed whether occupied or not. Every seat contributes credits and costs $20/month. Factor in your idle seats when calculating return on investment.

Getting started

If you have a Kiro profile with users signing in through single sign-on (SSO), you’re ready to go:

  1. In the Kiro console, go to Access management.
  2. On the Subscriptions tab, choose Switch to credit sharing.
  3. Follow the wizard to select users or groups.

Switching is irreversible: a user you move can’t go back to an individual subscription. Have each user’s Step 4 limit ready to apply once they’re in the pool.

Key details at a glance

The following table summarizes the numbers and rules covered in this post.

Item Detail
Credits per seat 500/month (shared)
Cost per seat $20/month
Additional credits $0.04 per credit, good for 12 months
Monthly credit reset End of billing cycle
Consumption order Monthly → Additional (oldest purchase first)
Limit hierarchy Individual > Group > Profile

Start sharing

Credit pooling turns unused individual capacity into a shared resource. Teams with uneven usage can get more from the same spend, and limits at every level help you stay in control.

Ready to try it? Head to the Kiro console and turn on credit sharing under Access management. For details on seats, limits, and monitoring, see Credit pooling in the Kiro documentation.

 


About the authors

Kirankumar Chandrashekar

Kirankumar Chandrashekar

Kirankumar Chandrashekar is a Generative AI Specialist Solutions Architect at AWS, focusing on Kiro. Bringing deep expertise in AWS cloud services, DevOps, modernization, and infrastructure as code, he helps customers accelerate their development cycles and elevate developer productivity through innovative AI-powered solutions. By leveraging Kiro, he enables teams to build applications faster, automate routine tasks, and streamline development workflows. Kirankumar is dedicated to enhancing developer efficiency while solving complex customer challenges, and enjoys music, cooking, and traveling.

Austin Butler

Austin Butler

Austin is a Senior Go-To-Market Specialist at Amazon Web Services (AWS) focusing on generative AI across the software development lifecycle. He works with strategic customers and partners to understand their software development practices and how AWS services like Kiro can deliver value in their SDLC. Prior to joining AWS, Austin spent 10 years working in Finance & Accounting.

Step-up authentication: how to right-size authentication to risk

Post Syndicated from Abrom Douglas original https://aws.amazon.com/blogs/security/step-up-authentication-how-to-right-size-authentication-to-risk/

Not every action a user takes in an application carries the same risk. Viewing an account balance in a banking application isn’t the same as wiring several thousand dollars to a new payee. In practice, though, many applications ask users to prove their identity once at sign-in and then treat every action the same from that point on, whether that sign-in used a password alone or included multi-factor authentication (MFA). That creates a tension: if the sign-in is strict enough for the most sensitive operation, everyday tasks carry unnecessary friction. If it’s easy enough for everyday tasks, the most sensitive operations might not be protected well enough. Even a strong sign-in from hours earlier says little about who is at the keyboard when a high-risk request arrives.

Amazon Cognito now resolves that trade-off by supporting step-up authentication, which records the authentication assurance level and the methods used, and including both in the JSON web tokens (JWTs) it issues. You ask for a target assurance level when a user signs in. Amazon Cognito returns the level the user reached in an acr claim (authentication context class reference) and the methods they completed in an amr claim (authentication methods reference). These claims are part of the OpenID Connect Core specification, so your application can reason about authentication strength in a standard way and match it to the potential risk of what the user is trying to do. In this post, I explain how the claims support step-up authentication and walk through four patterns that put them to use: transaction-level step-up in a banking app, varying risk postures across a portfolio of applications, step-up enforced on API and SDK sign-in, and authentication assurance carried across a federated third-party OpenID Connect (OIDC) identity provider.

You can request authentication levels through Amazon Cognito managed login using the standard OIDC acr_values and max_age parameters, and through the SDK and API using the USER_AUTH flow with TARGET_ACR_VALUES and MAX_AGE. Requesting step-up authentication requires the Essentials or Plus feature plan. ; For the complete list of features, behaviors, and limitations, see the Authentication levels with ACR and AMR claims.

What ACR and AMR tell your application

Amazon Cognito defines four assurance levels, and the factor combinations that satisfy each one are fixed. You can use the default names as is or rename the level URIs to fit your organization’s own naming scheme. Renaming changes only the label. If you need to relate Amazon Cognito levels to a framework such as NIST SP 800-63 or eIDAS, make that mapping in your application. The following are the default Amazon Cognito defined levels.

  • Level 1 (urn:cognito:loa:1) is password only.
  • Level 2 (urn:cognito:loa:2) is a single one-time password (OTP) over SMS or email.
  • Level 3 (urn:cognito:loa:3) is a passkey on its own, or a password combined with an SMS or email OTP.
  • Level 4 (urn:cognito:loa:4) is the highest: a password with a time-based one-time password (TOTP) code from an authenticator app.

Amazon Cognito assigns the highest level the user’s completed factors fully satisfy, so a user who signs in with a password and a TOTP code lands at level 4, even though they also met the assurance requirements for every level below it.

Four claims in the token facilitate a step-up decision. The acr claim is the level the sign-in reached and is what your application compares against what the operation requires. The amr claim lists the methods behind that level, so you can confirm a specific factor was used. The auth_time claim records when the user last authenticated interactively and is what max_age is measured against. The iat claim only records when the token was issued, so a refreshed token carries a new iat but keeps its old auth_time. Finally, send a nonce in the request and verify it on the returned ID token, so the result is tied to the request you made.

The following is an example access token for a user completing a level 4 authentication. Notice the four claims I’ve discussed: acr, amr, auth_time, and iat.

{ 
    "sub": "387173a0-60c1-700a-4a02-e84b49bcc7a9", 
    "iss": "https://cognito-idp.<region>.amazonaws.com/<region>_123abc", 
    "aud": "123abcn2ci4a99a4ieno123abc", 
    "exp": 1445470140, 
    "iat": 499163700, 
    "auth_time": -446666160, 
    "token_use": "access", 
    "acr": "urn:cognito:loa:4", 
    "amr": ["pwd", "otp", "mfa"], 
    "email": "[email protected]", 
    "cognito:username": "387173a0-60c1-700a-4a02-e84b49bcc7a9" 
}

Two important behaviors are worth understanding before you build on this. First, a token refresh preserves the acr and amr values, so a user who reached level 4 keeps level 4 across refreshes and isn’t asked to prove it again on every rotation. Second, a refresh doesn’t reset the auth_time claim. That field records when the user interactively authenticated, not from a non-interactive token refresh. This is what lets you reason about freshness of authentication separately from assurance strength.

At a high level, every step-up interaction in this post follows the same loop: the application checks the token it already holds, redirects for a stronger level only when the operation requires more than the user has, and re-validates the acr claim on the freshly issued token before it proceeds. The following diagram provides a general step-up authentication flow.

Figure 1: General step-up authentication flow to access a sensitive operation

Figure 1: General step-up authentication flow to access a sensitive operation

How you request a level, and what stays your responsibility

The request side is deliberately straightforward. On managed login you add acr_values and optionally max_age to the or endpoint. In the SDK and API, you pass TARGET_ACR_VALUES and MAX_AGE in the USER_AUTH flow of the API. Both acr_values and TARGET_ACR_VALUES accept an ordered list of target levels. The same parameters work whether you’re setting the level for an initial sign-in or raising the level of a user who is already signed in; the patterns later in this post show both. Amazon Cognito acts only on what you send. It doesn’t infer the level you meant, so if you omit the parameter or request the wrong level, the user might not be stepped up the way you intended.

That points to the part your application and API owns: what assurance authentication level is needed. Amazon Cognito issues a token that honestly reports the level the user reached based on what your application requested. For example, deciding that a given operation requires an assurance level 3, checking the token’s acr against that requirement, and refusing the operation when it falls short is enforcement your application and API performs. Amazon Cognito produces the evidence; your code acts on it. In practice, that means checking the token you already hold before you redirect, so you don’t send a user to re-authenticate who already meets the bar, and validating the acr and auth_time claims on the tokens Amazon Cognito returns before you grant access. Amazon Cognito computes these claims itself, so you can’t customize, add to, or suppress them with a pre-token-generation Lambda trigger.

There is one more detail that saves debugging time later. If you rename your acr level URIs after tokens have already been issued, an older token might carry an acr value that no longer matches any configured level. Amazon Cognito treats that as an unrecognized level rather than an error. It still honors the token’s amr values and prompts only for factors not already present, without crediting any particular level. The amr list, in other words, remains meaningful even when a renamed level string goes stale. See Configuring ACR level names to learn how to configure this.

With the claims and the division of responsibility in place, the following four patterns show how they work in practice. Each one applies the same loop from Figure 1 to a different situation: a single application, a portfolio of applications, API-driven sign-in, and federation.

Pattern 1: Transaction-level step-up in a banking app

Consider a retail banking application. Signing in and viewing balances is routine, and the bank is comfortable requiring a moderate assurance level for it. Moving money is considered a privileged action, and a large transfer deserves stronger proof that the person at the keyboard is really the account holder.

The bank sets its baseline at level 2, so a user signs in with a one-time code over SMS or email and can see balances, statements, and pending transactions. When that same user initiates a transfer above $1,000, the application’s own policy says the operation requires level 4. Before it shows the transfer initiation screen, the application inspects the acr claim in the token it already holds. The user authenticated at level 2, level 2 is below the required level 4, so the application redirects the user to managed login with acr_values=urn:cognito:loa:4.

GET https://auth.example-bank.com/oauth2/authorize 
    ?response_type=code 
    &client_id=abc123def456 
    &redirect_uri=https://app.example-bank.com/callback 
    &scope=openid 
    &acr_values=urn:cognito:loa:4

Amazon Cognito now requires the user to complete a factor combination that satisfies level 4, for example entering their password and then a TOTP code from their authenticator app. When authentication finishes, Amazon Cognito issues fresh tokens with acr set to urn:cognito:loa:4, amr set to ["pwd", "otp", "mfa"], and a fresh updated auth_time claim. The application validates that the new token meets its requirement and only then lets the transfer proceed. A transfer under the threshold never triggers any of this, so the everyday experience stays light and the friction lands exactly where the risk is.

The application logic reads naturally, here’s a pseudo JavaScript snippet:

// Use your own URIs here, if different than defaults.
const ACR_RANK = {
  "urn:cognito:loa:1": 1,
  "urn:cognito:loa:2": 2,
  "urn:cognito:loa:3": 3,
  "urn:cognito:loa:4": 4,
};
const REQUIRED_LEVEL = "urn:cognito:loa:4";
const HIGH_VALUE_THRESHOLD = 1000;

function canAuthorizeTransfer(accessTokenClaims, amount) {
  if (amount < HIGH_VALUE_THRESHOLD) {
    return true; // baseline session is sufficient
  }
  // High-value transfer: require level 4.
  // An unrecognized acr ranks 0, so it never passes.
  const achieved = ACR_RANK[accessTokenClaims.acr] ?? 0;
  return achieved >= ACR_RANK[REQUIRED_LEVEL];
}

You can extend the same idea to freshness. A bank might accept a level 4 session for a high-value transfer only if the user authenticated within the last 5 minutes, which you express by adding max_age=300 to the request. Amazon Cognito compares that window against the auth_time claim in the access token and reauthenticates the user if the window has passed, even if the token was refreshed seconds ago.

Pattern 2: A portfolio of applications with different risk postures

Assurance levels are just as useful across a set of applications as they are within one. Suppose an organization runs five applications from a single Amazon Cognito user pool using managed login, and each one carries a different risk posture.

An internal cafeteria menu is low risk, so it’s fine with level 1, password only. An employee directory and an expense viewer hold personal data but nothing that moves money, so they require level 2: a one-time code over SMS or email on top of the password. A source code portal warrants a passkey or a password plus a one-time code, which is level 3. The production financial console is the crown jewel, so it demands level 4: a password with a TOTP code.

Each application requests its own floor by setting acr_values to the level that matches its risk, and each validates the acr claim on the returned token before granting access. Because the applications share a user pool, managed login keeps a single sign-on (SSO) session across them. A user who has already reached level 4 for the financial console is redirected to managed login when they open another application, finds the existing session, and receives tokens for that application without another prompt, provided the application doesn’t send a max_age that the session has outlived. Each application then compares levels by rank, so a level 4 token satisfies a level 2 floor. Someone who signed in at level 1 for the cafeteria menu, on the other hand, is stepped up the first time they open the expense viewer, because level 1 doesn’t meet the level 2 floor that the application enforces. The user pool stays single and central; the assurance requirement travels with each application’s own policy.

Renaming the level URIs helps here. If the organization already classifies systems against an internal assurance standard, it can set AcrConfiguration on the user pool so that, say, level 3 reports as urn:example-corp:assurance:standard and level 4 as urn:example-corp:assurance:high. The factor combinations behind each level stay fixed; only the names change, so every application validates against strings its developers already recognize.

Pattern 3: Step-up on API and SDK sign-in

Managed login covers browser-based flows, including federation, but plenty of clients authenticate directly against the Amazon Cognito API, and the same assurance model applies there, such as using the USER_AUTH flow with the InitiateAuth API. This matters for a mobile app, a desktop client, or a service that drives sign-in programmatically and needs to raise assurance before a sensitive call.

Take a mobile trading app that signs its users in with the SDK. A user opens the app with a password and reaches level 1, which is enough to browse watchlists and market data. When they place a trade, the app’s policy requires level 4. Because the app authenticates through the API rather than a browser redirect, it starts a new USER_AUTH flow and passes the access token it already holds along with TARGET_ACR_VALUES, requesting the level it needs. Amazon Cognito drives the user through a factor combination that satisfies level 4, then returns tokens whose acr claim the app validates before it submits the order. The InitiateAuth request would look similar to the following API call.

{
  "AuthFlow": "USER_AUTH",
  "ClientId": "abc123def456",
  "AuthParameters": {
    "USERNAME": "[email protected]",
    "ACCESS_TOKEN": "eyJraWQiOi...",
    "TARGET_ACR_VALUES": "urn:cognito:loa:4",
    "MAX_AGE": "300"
  }
}

Passing the access token the app already holds lets Amazon Cognito step the user up from the factors in that token; without it, Amazon Cognito authenticates the user from scratch. The MAX_AGE parameter behaves the same way it does on managed login. It ties the requirement to auth_time, so a trade placed after the window elapses forces a fresh authentication even if the app refreshed its tokens in the meantime. One behavior specific to the API path is worth knowing when you test on a lower Cognito feature plan. If you request step-up through InitiateAuth on a user pool that isn’t on the Essentials or Plus plan, the API returns a FeatureUnavailableInTierException. Managed login handles the same situation differently: the authorize endpoint silently ignores acr_values and proceeds with normal authentication rather than raising an error.

Pattern 4: Carrying assurance across a federated OIDC identity provider

The three patterns so far assume Amazon Cognito is where the user authenticates and the authoritative source for the identity. Many organizations federate sign-in to a third-party OIDC provider, so the person proving who they are is doing it against an external identity provider (IdP), while Amazon Cognito brokers the session. The assurance model follows them there.

When your application requests a level, it sends acr_values and optionally max_age to the Amazon Cognito authorize endpoint exactly as before. If that user is configured to federate through an OIDC IdP, Amazon Cognito sends the authorization request to that IdP on the user’s behalf. It translates the level you requested into the acr value the IdP expects, using the mapping you configured, and passes max_age along with it. A standards-compliant OIDC IdP honors acr_values the same way Amazon Cognito does: it drives the user through an authentication that satisfies the requested level, and it returns its own acr value describing what the user reached. max_age carries forward in the same way, so a freshness requirement is enforced at the provider that actually authenticates the user rather than being lost at the broker. Keep in mind that this is only supported with OIDC identity providers.

The request is unchanged from the application’s point of view. It still directs to Amazon Cognito:

GET https://auth.example.com/oauth2/authorize
  ?response_type=code
  &client_id=abc123def456
  &redirect_uri=https://app.example.com/callback
  &scope=openid
  &identity_provider=PartnerOIDC
  &acr_values=urn:cognito:loa:3
  &max_age=300

The interaction gains a third participant, the downstream IdP, but the assurance requirement is persisted through the entire federated authentication flow as shown in figure 2.

Figure 2: Federation with an OIDC third-party IdP, persisting the acr_values and max_age request parameters

Figure 2: Federation with an OIDC third-party IdP, persisting the acr_values and max_age request parameters

The value that comes back from a partner IdP won’t use Amazon Cognito’s level URIs, so this lets you map the provider’s acr values onto its own levels with the AcrMapping field on the OIDC IdP configuration. A partner IdP that reports, say, https://partner.example/assurance/strong can be mapped to Amazon Cognito level 3 (urn:cognito:loa:3), so that by the time the token reaches your application the acr claim speaks the same vocabulary regardless of whether the user authenticated locally or through a federated provider. Your resource server keeps a single enforcement rule and authorization logic and doesn’t need to have special handling depending on where the user ultimately authenticated. See Step-up authentication for federated users to learn how to map external OIDC IdP acr levels to Cognito.

This is the same pattern that RFC 9470, the OAuth 2.0 Step Up Authentication Challenge Protocol, describes: the assurance level is requested at the edge of your application, travels through Amazon Cognito to whatever provider authenticates the user, and returns normalized to a vocabulary your code already understands. A user federating from a corporate IdP and a user signing in against the same user pool directly both arrive at your resource server carrying an acr claim that means the same thing.

Conclusion

In this post, I showed you how the acr and amr claims in Amazon Cognito let you match authentication strength to the risk of what a user is doing, instead of settling for one bar at the front door. Your application requests a target level with acr_values and max_age (or TARGET_ACR_VALUES and MAX_AGE in the USER_AUTH flow), Amazon Cognito reports the level reached and the methods used, and your application enforces what each operation requires. The four patterns, from a banking transfer to a federated third-party IdP, follow that same loop, and one enforcement rule at your resource server covers every sign-in path.

The larger shift is that assurance is now something Amazon Cognito expresses in a standard way and your application reasons about directly, without building your own step-up tracking. To get started, move your user pool to the Essentials or Plus feature plan, decide the level each operation requires, and add acr_values to your existing authorize requests. For the complete parameter reference and federated behavior, see the Amazon Cognito Developer Guide.

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


Abrom Douglas III

Abrom is a Senior Solutions Architect within AWS Identity with over 20 years of software engineering and security experience, specializing in identity and access management. He loves speaking with customers about how identity and access management can provide secure outcomes that enable both business and technology initiatives. In his free time, he enjoys cheering for Arsenal FC, photography, travel, volunteering, and competing in duathlons.

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.

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.

Reducing database incident MTTR by 73% with a custom AWS DevOps Agent Skill

Post Syndicated from Chetan Suri original https://aws.amazon.com/blogs/devops/reducing-database-incident-mttr-by-73-with-a-custom-aws-devops-agent-skill/

Database incidents are among the most time-consuming operational events for Site Reliability Engineering (SRE) teams. When an Amazon Aurora PostgreSQL cluster experiences performance degradation, SRE engineers must correlate metrics across connection pools, replication topology, query performance, storage subsystems, and parameter configurations. These troubleshooting steps routinely take 45–60 minutes even for experienced engineers.

AWS DevOps Agent is an operations teammate that resolves and proactively helps prevent incidents, and optimizes application reliability and performance. It also handles on-demand SRE tasks across AWS, multicloud, and on-premises environments. Although its built-in capabilities handle common scenarios well, most organizations have unique database configurations, connection pooling patterns, and performance baselines. That knowledge lives in the heads of senior database reliability engineers (DBREs).

With Custom Skills, you can codify that expertise and make it available to the agent 24/7. In this post, we walk through building a custom Aurora PostgreSQL performance degradation investigation Skill. This multi-fault procedural Skill uses decision-tree logic that covers five distinct failure modes. We then show how it reduces Mean Time to Resolution (MTTR) from a baseline of 52 minutes to 14 minutes. That’s a 73 percent reduction, measured in a controlled internal test of three simulated incidents.

Prerequisites

Before getting started, make sure you have:

  • An active AWS account with access to AWS DevOps Agent.
  • An Agent Space configured with access to your Aurora PostgreSQL cluster’s account.
  • Amazon CloudWatch metrics and Performance Insights enabled on your Aurora cluster.
  • Access to the Operator Web App for Skill deployment.
  • Familiarity with Aurora PostgreSQL operational metrics (DatabaseConnections, ReplicaLag, db.load).

The problem: Database incidents require deep tribal knowledge

Consider a typical Aurora PostgreSQL performance degradation incident. The on-call engineer receives a page indicating elevated read latency. From here, the investigation branches into multiple possible root causes:

  • Is the connection pool exhausted, starving the application of database connections?
  • Is replication lag causing stale reads that trigger application retries?
  • Did a recent deployment introduce a slow query that’s consuming all available CPU?
  • Is the storage subsystem under pressure from table bloat or excessive write amplification?
  • Did someone modify the parameter group, introducing a misconfiguration that degrades performance?

Each branch requires checking different metrics, correlating with different timelines, and applying different remediation strategies. A senior DBRE knows which branch to explore first based on subtle signal combinations. However, that knowledge is rarely documented in a way that’s actionable at 2 AM.

Additionally, parameter drift is particularly insidious because its symptoms mimic other failure modes. It occurs when someone modifies the cluster parameter group and introduces a misconfiguration. Without domain-specific guidance, the agent chases symptoms rather than tracing back to the configuration change.

Solution overview: A multi-fault procedural Skill

Rather than building five separate Skills (one per failure mode), we build a single procedural Skill with decision-tree logic that mirrors how an expert DBRE triages Aurora PostgreSQL issues. The Skill evaluates initial signals to determine which investigation branch to follow, then executes a structured procedure for that specific failure mode.

What makes this different from the workshop examples

The AWS DevOps Agent workshop covers two Skill types: (1) a single-file UI-created checklist (AWS Lambda cold starts) and (2) a multi-file architecture-context Skill (EKS Retail Store). Both are effective for their scope, but neither demonstrates a procedural investigation Skill with decision-tree logic that proves measurable MTTR reduction.

Our Skill differs in three key ways:

  • Decision-tree branching: “If metric X exceeds threshold Y, check Z before proceeding to W,” not a linear checklist.
  • Multi-fault coverage: five failure modes in one Skill with explicit priority ordering.
  • Measurable outcome: Controlled before and after MTTR comparison proving 73 percent reduction.

Skill anatomy

Skills are modular instruction sets. Each is a self-contained directory of Markdown files that provides specialized domain knowledge and investigation methodologies to AWS DevOps Agent. Each Skill contains:

  • SKILL.md (required) – Core instructions with investigation procedures, frontmatter metadata, and decision logic.
  • references/ (optional) – Supporting documentation, threshold tables, query templates.
  • assets/ (optional) – Architecture diagrams, flowcharts, data files.

The agent evaluates a Skill’s description field in the frontmatter to determine relevance, then loads and follows the instructions during investigations. Skills follow the open Agent Skills specification (agentskills.io), supporting non-executable documents: Markdown, PDFs, images, and data files.

Directory structure

aurora-pg-performance-degradation/
├── SKILL.md
├── references/
│   ├── aurora-pg-metric-thresholds.md
│   ├── connection-pool-sizing-guide.md
│   ├── replication-lag-decision-tree.md
│   ├── performance-insights-queries.md
│   └── vacuum-tuning-reference.md
└── assets/
    └── investigation-decision-tree.png

Walkthrough: Building the Skill

The following steps walk through building the Skill end to end, from documenting the investigation pattern to deploying it. We start by capturing how an expert triages the incident.

Step 1: Document the expert investigation pattern

Before writing any Markdown, we interviewed three senior DBREs and documented their mental model for Aurora PostgreSQL performance triage. The common pattern:

  • Initial signal classification – What metric triggered the alarm?
  • Impact scope assessment – Writer instance only, reader instances only, or cluster-wide?
  • Timeline correlation – Did this start after a deployment, scaling event, or traffic pattern change?
  • Branch into specific failure mode – Based on signals from steps 1–3.
  • Deep investigation – Follow the procedure for that failure mode.
  • Root cause and remediation – Structured output with immediate, short-term, and long-term actions.

Step 2: Write the SKILL.md with decision-tree logic

The SKILL.md begins with frontmatter that tells the agent when to activate, followed by initial signal classification that routes to the correct branch:

Frontmatter

---
name: aurora-pg-performance-degradation
description: Investigation procedures for Aurora PostgreSQL performance
degradation including connection pool exhaustion, replication lag, slow
query regression, storage pressure, and parameter drift. Use this skill
when investigating Aurora PostgreSQL latency spikes, connection errors,
read/write degradation, or unexplained performance changes.
---

Signal classification table

Primary Signal Likely Branch Go To
DatabaseConnections near max or connection errors Connection Pool Exhaustion Branch A
ReplicaLag > 20 ms or stale read complaints Replication Lag Branch B
Latency spike with high db.load in Performance Insights Slow Query Regression Branch C
FreeLocalStorage declining or VolumeBytesUsed alert Storage Pressure Branch D
Parameter group change in AWS CloudTrail within past 7 days Parameter Drift Branch E

Critical rule: If multiple signals are present, prioritize A → B → C → D → E. Connection exhaustion masks other symptoms, so it must be checked first.

Branch A: Connection pool exhaustion

Investigation procedure. Connection pool exhaustion is the highest-priority branch because it masks every other symptom, so the agent checks it first. It works through four checks in order, moving from the raw connection count to the behavior behind it:

  • Compare active connections to the limit. Check DatabaseConnections against max_connections. If connections exceed 85 percent of the maximum, pool exhaustion is confirmed.
  • Identify where the connections originate. Distinguish RDS Proxy pinned sessions from the direct application pool, since each points to a different fix.
  • Correlate with deployment history. A service that deployed recently and opened connections without releasing them is a common trigger, so the agent checks whether a rollout preceded the spike.
  • Check for long-running transactions. Sessions stuck in idle_in_transaction hold connection slots open and starve the pool.

Interpreting the findings. The preceding checks establish what is happening. This is where the agent decides why. Each pattern maps to a distinct root cause:

  • If connections rise monotonically, the application has a connection leak in its code.
  • If connections spike with traffic, the pool is sized too small for the load.
  • If connections spike right after a deployment, a new code path is not releasing connections.
  • If the spike is in pinned RDS Proxy sessions, session state is reducing connection reuse (multiplexing).

Branch B: Replication lag

Investigation procedure. When readers fall behind the writer, the agent needs to know whether the cause is write pressure, reader capacity, or a transient backlog. It gathers four signals before drawing a conclusion:

  • Quantify the lag. Read AuroraReplicaLag for each reader (normal is under 20 ms, critical is over 100 ms).
  • Evaluate write pressure on the writer. Look at WriteIOPS, WriteThroughput, and WriteLatency to see how hard the writer is working.
  • Check reader resource utilization. Review CPUUtilization and FreeableMemory per reader to spot an overwhelmed instance.
  • Find write-heavy queries blocking replication. Identify the top SQL by db.load with write wait events.

Interpreting the findings. The combination of writer pressure and reader health tells the agent which of four situations it is in:

  • If the writer’s write volume spiked, a bulk operation or traffic surge is driving the lag.
  • If a reader’s CPU is saturated, that reader’s instance class is too small.
  • If lag is increasing with no write spike, the reader is working through a backlog and will self-resolve.
  • If lag is stable but persistently high, there is a structural mismatch between the write rate and reader capacity.

Branch C: Slow query regression

Investigation procedure. A query regression can come from new code, a changed plan, or simply more volume, so the agent compares the current workload against a known-good baseline:

  • Find the heaviest queries. Use Performance Insights to identify the top 10 SQL statements by db.load (average active sessions).
  • Compare against the baseline. Check the current top 10 against the same list from 24 hours ago and look for new SQL IDs that have climbed into it.
  • Compare execution plans before and after deployment. Look for missing indexes, a changed JOIN order, or new full table scans.
  • Check for stale statistics. Compare the last ANALYZE to the most recent large data change.
  • Account for volume changes. The same query running 10 times more often is a regression even when each individual execution is unchanged.

Interpreting the findings. Where the change shows up tells the agent what kind of regression it is:

  • If new SQL appears in the top 10 after a deployment, it is a code regression. Review the commit.
  • If existing SQL degraded, the plan regressed because statistics went stale or the data distribution shifted.
  • If query volume increased, a caching layer failed or the traffic pattern changed.
  • If the wait events are lock-related, a schema change or a new contention pattern is to blame.

Branch D: Storage pressure

Investigation procedure. Storage problems range from benign capacity growth to a runaway process, so the agent first establishes the shape of the growth and then its source:

  • Check the storage trend. Review FreeLocalStorage over seven days to tell steady linear growth apart from a sudden spike.
  • Measure table and index bloat. Compare n_dead_tup to n_live_tup. A bloat ratio above 20 percent means vacuum is falling behind.
  • Check for write amplification. Watch for VolumeBytesUsed growing faster than the logical data being inserted.
  • Evaluate temporary file usage. Large sorts spilling to disk show up as temp_blks_written per query in pg_stat_statements.

Interpreting the findings. The growth pattern points the agent to the right response, and shows whether this is even an incident:

  • If growth is linear and matches the ingestion rate, this is a capacity-planning item, not an incident.
  • If storage spiked suddenly, suspect a bulk load, a failed cleanup job, or a runaway process.
  • If the bloat ratio is above 20 percent, autovacuum is not keeping up. Tune autovacuum, or use an online reorganization such as pg_repack on a live cluster. Avoid VACUUM FULL during an active incident. It takes an ACCESS EXCLUSIVE lock and rewrites the table, which blocks reads and writes and can extend the outage.
  • If temporary files are large, the queries need optimization or a higher work_mem.

Branch E: Parameter drift

Investigation procedure. Parameter drift is insidious because its symptoms mimic other failures, so the agent starts from the change history and works toward the specific setting at fault:

  • Pull the recent change history. Query AWS CloudTrail for ModifyDBClusterParameterGroup events in the past seven days.
  • Compare against the recommended baseline. Check current values for connection management, memory allocation, vacuum tuning, and query planning against the expected configuration.
  • Isolate misconfigurations from recent changes. For example, a work_mem set too high can cause out-of-memory errors, and an autovacuum_cost_delay set too high lets bloat accumulate.
  • Check for a default versus a custom parameter group. Reverting to a default group is common after a restore-from-snapshot operation.

Interpreting the findings. Correlating the change history with symptom onset tells the agent whether drift is the root cause and, if so, how it happened:

  • If a recent ModifyDBClusterParameterGroup lines up with when the symptom started, the parameter change is the root cause.
  • If this cluster’s parameters differ from others in the fleet, it has drifted from the standard configuration.
  • If it is on a default parameter group after a restore, the custom tuning was lost during the restore.
  • If pending-reboot parameters exist, a partial application is causing inconsistent behavior.

Step 3: Deploy the Skill

AWS DevOps Agent provides multiple deployment methods. For repeatable deployments, we recommend zip upload or GitHub import. For a quick try, use the Operator Web App UI. Choose based on your Skill’s complexity.

Option A: Using zip upload (recommended for skills with reference files)

  • Package the directory: zip -r aurora-pg-performance-degradation.zip aurora-pg-performance-degradation/.
  • Choose Knowledge, Skills, Add skill, then Upload skill.
  • Drag and drop your zip file (must be under 6 MB).
  • Select agent types: Incident RCA and On-demand.
  • Choose Upload. The system validates the zip, extracts SKILL.md frontmatter, and activates the Skill.

Option B: Import from a GitHub repository

  • Push your Skill directory to a GitHub repository connected to your Agent Space.
  • Choose Knowledge, Skills, Add skill, then Import from repository.
  • Enter the GitHub directory URL (for example, https://github.com/my-org/devops-skills/tree/main/aurora-pg-performance-degradation).
  • Select agent types and choose Import skill.
  • Choose Sync to pull updates when you modify the Skill in your repository.

Option C: Using the Operator Web App UI (skills without reference files)

  • Navigate to the Knowledge page in your Agent Space Operator Web App and choose the Skills tab.
  • Choose Add skill, then Create skill.
  • Enter the name (aurora-pg-performance-degradation), description, and instructions from SKILL.md.
  • Set Status to Active.
  • For Agent Type, clear Generic and select Incident RCA and On-demand.
  • Choose Create to save the Skill.

Option D: Create with Chat

  • Choose Knowledge, Skills, Add skill, then Create skill with Chat.
  • Describe your investigation procedure in natural language.
  • The agent generates the SKILL.md structure, frontmatter, and instructions for you.
  • Review, edit if needed, and save.

Why we chose Incident RCA and On-demand:

Targeting specific agent types helps prevent the Skill from loading when it’s not relevant. Our Skill is designed for deep root cause analysis (Incident RCA) and ad hoc queries (“Why is my Aurora cluster slow?” through On-demand). We deliberately exclude Incident Triage because triage should be fast (under 2 minutes). Our Skill is thorough, not lightweight.

Measuring the impact: 73 percent MTTR reduction

To validate the Skill’s effectiveness, we ran a controlled before and after comparison using three real-world incident scenarios on a test Aurora PostgreSQL cluster.

Methodology

We simulated three distinct failure modes on an Aurora PostgreSQL cluster with realistic production-like workloads:

  • Connection pool exhaustion – Introduced connection leak through an application code change.
  • Slow query regression – Deployed a new query missing a critical index.
  • Parameter drift – Modified shared_buffers and work_mem to suboptimal values through a parameter group change.

For each incident, we measured: (1) total investigation duration from alert to root cause identification, (2) number of wrong hypotheses explored before finding root cause, and (3) whether the structured output included immediate, short-term, and long-term remediation actions.

Results without the Skill (baseline)

We triggered three incident types and measured how the agent investigated using only its built-in knowledge:

Incident Type Duration Wrong Hypotheses explored Root Cause Found?
Connection pool exhaustion 48 min 3 Yes, eventually
Slow query regression 55 min 2 Yes, eventually
Parameter drift 53 min 4 Partial – symptoms identified but not traced to parameter change

Average without Skill: 52 minutes, 3.0 wrong hypotheses per incident

Without domain-specific guidance, the agent explored metrics in an unpredictable order. For connection exhaustion, it checked CPU, then storage, then replication lag before eventually examining connection counts. For parameter drift, it identified symptoms (slow queries, bloat) but never correlated with the AWS CloudTrail ModifyDBClusterParameterGroup event.

Results with the Skill

We triggered the same three incidents and confirmed the agent loaded and followed the decision tree:

Incident Type Duration Decision Tree Followed? Wrong Hypotheses
Connection pool exhaustion 11 min Yes – Branch A first (priority order) 0
Slow query regression 16 min Yes – Timeline correlation → Branch C 0
Parameter drift 15 min Yes – CloudTrail correlation → Branch E 1

Average with Skill: 14 minutes, 0.3 wrong hypotheses per incident

Results summary

Metric Before Skill After Skill Improvement
Mean time to resolution (MTTR) 52 min 14 min 73% reduction
Wrong hypotheses per incident 3.0 0.3 90% fewer dead ends
Correct root cause on first branch 0/3 (0%) 2/3 (67%) First-time accuracy
Complete structured output 1/3 3/3 Consistent remediation quality
Escalation to senior DBRE required 2/3 0/3 Self-sufficient investigation

Why the improvement is so large

The 73 percent reduction comes from two compounding factors:

  • Alleviation of wrong hypotheses: Without the Skill, the agent spent 15–20 minutes per wrong hypothesis before pivoting. The decision tree’s priority order (A → B → C → D → E) avoids dead ends by checking upstream causes first.
  • Direct routing through signal classification: The Skill’s initial signal table routes the agent to the correct branch immediately when the primary signal is clear. For connection exhaustion, the agent goes straight to Branch A without exploring storage or replication.

The compounding effect: Memories

Your custom Skill works alongside the knowledge AWS DevOps Agent builds about your environment as it works. The agent maintains memories of your topology, code dependencies, pipeline structure and tool-use patterns, which you can view and manage on the Memories tab of the Knowledge page. As this context grows, the agent can apply your Skill’s decision tree with a better understanding of how your Aurora PostgreSQL clusters connect to the rest of your environment. This can help investigations stay fast and accurate as your environment changes.

Best practices for procedural Skills

1. Use decision trees, not linear checklists

Procedural Skills with branching logic deliver measurably better outcomes for complex, multi-fault scenarios. Tell the agent when to follow each branch based on observable signals. A linear checklist forces the agent through every step regardless of relevance.

2. Define the priority order explicitly

“If multiple signals are present, prioritize: A → B → C → D → E.” This single line helps prevent the agent from spending time on downstream symptoms when the root cause is upstream.

3. Include decision points at each branch

After the investigation steps, explicitly state what each finding means and where to go next. Without decision points, the agent might collect data but not draw the correct conclusion.

4. Add metric thresholds in reference files

Don’t embed thresholds in the main SKILL.md. Put them in reference files (for example, references/aurora-pg-metric-thresholds.md). This keeps instructions focused on the investigation workflow while giving the agent concrete numbers to work with. It also makes thresholds straightforward to update as your environment scales.

5. Target specific agent types

This Skill targets “Incident RCA” and “On-demand,” not “Incident Triage.” RCA Skills can be thorough. Triage Skills should be lightweight (under 2 minutes). Targeting reduces context consumption and improves agent focus.

6. Measure before and after

Without baseline MTTR data, you cannot prove the Skill’s value. Track investigation duration and hypothesis count for the specific incident class before deploying the Skill, then run the same scenarios after deployment and compare.

Clean up

To deactivate or remove the Skill:

  • Choose Knowledge, then Skills in the Operator Web App.
  • Select the aurora-pg-performance-degradation Skill.
  • To temporarily disable, set Status to Inactive. This preserves the Skill for future use, and in-progress investigations continue using it.
  • To permanently remove, choose the more options menu (⋮), choose Delete, enter the skill name to confirm, and choose Delete Skill.

Consider downloading your Skill as a zip file before deletion as a backup. Deactivating is preferred over deleting if you may need the Skill again.

Conclusion

Custom Skills transform AWS DevOps Agent from a general-purpose operations assistant into a specialist that knows your database infrastructure as well as your best DBRE. By encoding multi-fault decision-tree logic into a procedural Skill, we achieved a 73 percent reduction in MTTR for simulated Aurora PostgreSQL performance incidents, from 52 minutes to 14 minutes.

The key insight: The value of a custom Skill is not in listing what to check (any runbook does that), but in encoding when to check it and what the findings mean. Decision-tree logic that prioritizes investigation branches based on observable signals is what separates a Skill that delivers measurable MTTR reduction from a Skill that’s merely a formatted checklist.

Start with your most common database incident type, document how your best engineer triages it, encode the decision logic into a Skill, and measure the before and after. Your on-call team will thank you, especially at 2 AM.

Resources


About the authors

Chetan Suri

Chetan Suri

Chetan is a Senior Specialist Technical Account Manager at AWS, focused on Cloud and AI Operations. He works with Enterprise Support customers to improve operational excellence through AI-driven incident response and proactive operational strategies.

Rizwan Khan

Rizwan Khan

Rizwan is an Enterprise Account Engineer specializing in Amazon CloudFront at AWS. He works with media streaming customers across the Asia-Pacific region to optimize content delivery architecture for performance, resilience, and cost efficiency at scale.

Antony Wanyugi

Antony Wanyugi

Antony is a Technical Account Manager at AWS, helping customers optimize their cloud operations and adopt modern DevOps practices including proactive incident prevention and automated root cause analysis.

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.

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.

A governed AI-driven development lifecycle for financial services with Kiro and AWS Frontier Agents

Post Syndicated from Qingwei Li original https://aws.amazon.com/blogs/devops/a-governed-ai-driven-development-lifecycle-for-financial-services-with-kiro-and-aws-frontier-agents/

The FSI challenge: Faster delivery with stronger controls

Financial institutions face a difficult asymmetry. Frontier models can help defenders find and remediate weaknesses faster, but regulators are also warning that the same capabilities might accelerate vulnerability discovery and exploitation. The supervisory response is raising expectations for prioritized vulnerability management, continuous monitoring, operational resilience, supply-chain assurance, and the use of AI-based defensive tools under safeguards, human oversight, and robust risk management.

Traditional software delivery makes that harder. Build, security, risk, and operations often work in separate tools and review cycles, with context passed through tickets and manual handoffs. Security checks might occur late, evidence is assembled after the fact, and incident responders must reconstruct what changed across multiple systems. For regulated teams, this creates more than delay: it makes controls harder to apply consistently and decisions harder to evidence.

Under the Digital Operational Resilience Act (DORA), accountability for Information and Communication Technology (ICT) risk remains with the financial institution, including its use of cloud and other third-party providers. Fast development speed alone isn’t enough. Teams need a delivery model that shortens the cycle from discovery to remediation while retaining approval points, traceable evidence, and human accountability.

A governed AI-DLC with three Frontier Agents

The AI-Driven Development Lifecycle (AI-DLC) provides a practical pattern: an AI agent drafts or analyzes, a human evaluates, and the cycle repeats in short iterations. Applied across the lifecycle, agents can help author code, assess release readiness, identify security weaknesses, and investigate production failures. Humans continue to set policy, evaluate findings, authorize material changes, and own the production decision.

In this hands-on walkthrough, Kiro, AWS Security Agent, and AWS DevOps Agent work across a shared GitHub-based workflow. Kiro authors and revises code. AWS DevOps Agent reviews release readiness before and during the pull request. AWS Security Agent performs a deeper security review. A human approves the merge, and AWS DevOps Agent investigates production failures.

Under DORA, accountability for ICT risk stays with the financial institution regardless of which cloud or tooling it uses. Showing that every change was scanned, reviewed, and approved before it reached production, with evidence captured in the delivery toolchain itself, is what turns a good engineering practice into a defensible compliance posture. The institution moves faster without weakening the governance chain, because the agents handle the analysis while humans retain the authority over what gets deployed. This reference implementation doesn’t provide compliance by itself. Each institution must map it to its policies, segregation-of-duties requirements, model risk controls, risk appetite, and DORA obligations.

The three agents — role mapping across the SDLC

SDLC Phase Agent What it does
Plan → Build → Test Kiro (autonomous agent) Virtual developer. Maintains persistent context across sessions, learns from PRs and feedback. Handles multi-repo tasks: bug triage, code coverage, feature implementation. Connects to Jira, GitHub, Slack.
Security AWS Security Agent Virtual security engineer. Reviews design docs, scans PRs against org-specific security requirements, runs autonomous penetration testing. Returns validated findings with remediation code.
Review → Operate → Improve AWS DevOps Agent Virtual site reliability engineer (SRE), and now code reviewer. Release readiness code reviews on every change (cross-repo dependency risks, standards compliance, access control, automated verification testing), plus always-on incident triage, root cause identification and proactive reliability recommendations. Works with Amazon CloudWatch, Datadog, Dynatrace, Splunk, New Relic, Grafana, ServiceNow, Jenkins, GitHub.

Integration model: Workflow-level orchestration

The three agents operate as complementary autonomous systems that share the same software development lifecycle (SDLC) context through common tooling (repos, continuous integration and continuous delivery (CI/CD) pipelines, ticketing systems). The AWS DevOps Agent pulls double duty in this pipeline. Its release readiness code reviews capability makes it the first reviewer on every change: inside Kiro while the code is being written, and again on the PR, before it switches hats to incident response in production.

Agent workflow from Kiro code authoring through AWS DevOps Agent and AWS Security Agent reviews to AWS Lambda deploy and production monitoring

Figure 1: End-to-end workflow across Kiro, AWS DevOps Agent, and AWS Security Agent in a shared GitHub-based pipeline

  • Developer prompts Kiro on what to build. Kiro authors the code.
  • With the AWS DevOps Agent Kiro Power installed in Kiro, you can request a code release readiness review from AWS DevOps Agent right in the Kiro IDE. The release readiness review covers cross-repo dependency risks, standards compliance, access-control correctness, and automated verification testing.
  • After we pass the AWS DevOps Agent code readiness review, we push the code to GitHub from Kiro. The GitHub workflow is designed in a way that a Pull Request (PR) is automatically created.
  • AWS Security Agent runs the deeper OWASP / AWS Identity and Access Management (IAM) / secrets pass on the PR.
  • The developer might incorporate the output from AWS Security Agent and further revise the code. If all looks good, the developer merges the PR.
  • On merge, GitHub Actions deploys.
  • AWS DevOps Agent watches production and, the moment something breaks, opens an investigation, finds the root cause and ties back to the same GitHub repo Kiro is working in.

The rest of this post is the hands-on version of that loop: the exact wiring you need to make it run against a real repo.

Step-by-step setup

This section walks through the setup end to end, from a quick primer on GitHub Actions through the prerequisites and the six steps that wire the agents together.

A quick primer on GitHub Actions

GitHub Actions is GitHub’s built-in automation system. You drop YAML files into .github/workflows/ in your repo, and GitHub runs them on events you care about, such as a push, a PR being opened, a label being added, or a merge to main. Each workflow spins up a fresh Linux VM (“runner”), checks out your code, and executes a series of steps. Steps can be shell commands or reusable packages called actions. We use GitHub Actions as our CI/CD pipeline manager for demonstration purposes.

Prerequisite 1 — What you’ll need

  • A GitHub repo. In this demo example, we deploy a Python application to AWS Lambda using GitHub Actions.
  • An AWS account with permission to create IAM roles, Lambda functions, and an OpenID Connect (OIDC) identity provider.
  • Kiro installed locally.
  • A Slack workspace (for AWS DevOps Agent notifications).

Prerequisite 2 — Install the GitHub Apps and connect the agents

GitHub Apps are the modern way to give automation identity and scoped permissions. For the general model, see About using GitHub Apps. For this demo, install the following on your repo:

Step 1 — Author code in Kiro and push to GitHub

Kiro is an agentic IDE: you describe what you want to build, it writes and edits files, and you commit the result. Open your repo in Kiro, iterate until the feature works, then push a feature branch.

For demonstration purposes, we intentionally started with a flawed .py file with a hard-coded credential and a SQL injection vulnerability so the AWS DevOps Agent and AWS Security Agent have something to catch downstream. This is only to exercise the review agents end-to-end.

Because we installed the AWS DevOps Agent Kiro Power in Prerequisite 2, the review actually starts here, before anything is pushed. The Power includes Skills that tell Kiro to invoke a release readiness review after significant code changes and before creating a PR. Findings surface directly in the IDE, and Kiro offers to fix them on the spot. For this demo, we let the flawed file through so you can see the PR-side review catch it too.

Step 2 — Let the AWS DevOps Agent review the code

This is where the AWS DevOps Agent takes the first review pass. In this post, we use Kiro’s AWS DevOps Agent Power and chat directly with Kiro to kick off the review. This is convenient because you can download the review report and incorporate it into your code. Note that the AWS DevOps Agent can be configured to automatically run a release readiness code review every time a PR is opened or updated.

Prompt: Starting a release readiness review on DevOps-agent-demo @ update-lambda-import. Run it as static analysis.

AWS DevOps Agent release readiness review results shown in the Kiro IDE

Figure 2: AWS DevOps Agent release readiness review results in the Kiro IDE

Each review evaluates the change for cross-repository dependency risks, internal standards compliance, and access-control correctness. With automated verification testing enabled, the agent goes further than static analysis. It clones the change into an AWS-managed verification environment, figures out the build tools from your project files, builds the code, generates a test plan, and runs it. This surfaces functional risks like edge cases that would fail at runtime.

Step 3 — Auto-create the PR

We don’t want to context-switch to the GitHub UI only to open a PR. A tiny workflow does it for us. On every push to a non-main branch, it opens a PR against main if one doesn’t already exist. Put this in .github/workflows/auto-create-pr.yml:

# .github/workflows/auto-create-pr.yml (gist)
on: push to any non-main branch
steps:
- checkout repo
- mint a GitHub App token (APP_ID + APP_PRIVATE_KEY)
- if no PR exists for this branch:
gh pr create --base main --head <branch>

The workflow runs on push to any non-main branch and opens a PR against main if one doesn’t already exist.

Step 4 — Wire up the AWS Security Agent review

The AWS Security Agent was also connected to the repo in Prerequisite 2. This workflow is narrower and stricter than the AWS DevOps Agent’s release readiness pass: OWASP Top 10, hardcoded secrets, IAM misuse, and dependency risk. It gates on the needs-security-review label, so it only runs after the AWS DevOps Agent has cleared the PR.

Create .github/workflows/security-review.yml:

# .github/workflows/security-review.yml (gist)
on: pull_request [opened, labeled]
if: label 'needs-security-review' is present
steps:
- checkout repo
- assume AWS_ROLE_TO_ASSUME via OIDC
- run the Security Agent with:
prompt: "Security review: injection, secrets,
dependencies, IAM, input validation, OWASP Top 10.
Approve if secure; request changes if not."

Two agents now gate every merge. If either requests changes, you fix the code in Kiro and push again, and the whole review cycle restarts automatically.

Here’s what the output looks like in practice:

AWS DevOps Agent release readiness finding posted as a PR comment

AWS Security Agent finding posted as a comment on a GitHub pull request

Figure 3: AWS Security Agent finding posted as a pull request comment

Step 5 — Deploy to Lambda on merge

This demo keeps a human approval before production. After both agents have completed their reviews, an authorized reviewer evaluates the findings and chooses Merge. Financial institutions can add the approvals, separation of duties, change records, and policy checks required by their control framework. The moment the merge lands on main, the deploy workflow takes over.

Create .github/workflows/deploy.yml:

# .github/workflows/deploy.yml (gist)
on: pull_request closed against main
if: PR was merged (not just closed)
steps:
- checkout repo
- assume AWS_ROLE_TO_ASSUME via OIDC
- zip the repo into function.zip
- aws-lambda-deploy --function-name <LAMBDA_FUNCTION_NAME> --zip function.zip

At this point the PR has gone from Kiro push to auto-created PR, AWS DevOps Agent release readiness review, AWS Security Agent review, human approval, and Lambda update. The agents automate analysis and workflow steps, while the authorized reviewer remains accountable for the production decision.

Step 6 — Let the AWS DevOps Agent handle incidents

Deployments fail. Functions throw. Latency spikes. This is where the AWS DevOps Agent earns its keep. It’s an incident-response teammate that investigates on its own, finds root causes, and reports to Slack.

The AWS DevOps Agent is already wired up from Prerequisite 2. It’s connected to this repo (so it can read workflow runs, commits, and IAM policy references) and to Slack (so investigations post to your channel). The only thing left is to point an alert source at it. Follow the webhook configuration guide to grab a webhook URL, then aim your alerts at it, whether GitHub Actions failure notifications, Amazon CloudWatch alarms, or both. An event that hits the webhook kicks off a new investigation.

What an investigation looks like:

Here’s a real run from this demo. A Lambda deploy failed because the OIDC role was missing one IAM permission. The agent walks through it as a timeline:

4:22 PM — Investigation started: Lambda deployment failed. [Symptom] Deploy to Lambda workflow failed on main. [Observation] Workflow assumed the github-action-lambda role, then got AccessDenied calling GetFunctionConfiguration. [Finding] IAM policy frontier-agent-deploy-lambda is missing lambda:GetFunctionConfiguration. Investigation complete — root cause: that one missing IAM permission.

In the AWS DevOps Agent console you see the full timeline and the identified root cause, and you can ask the agent to generate a mitigation plan from there. It proposes the IAM policy change and the steps to apply it.

You’ll also get a Slack ping the moment the investigation kicks off, because we connected the Slack integration in Prerequisite 2:

Slack notification of an AWS DevOps Agent investigation for a failed Lambda deployment

Figure 4: AWS DevOps Agent investigation notification in Slack

Conclusion

In this post we walked end-to-end through an AI-DLC pipeline. Kiro authors the code, with the AWS DevOps Agent Kiro Power reviewing changes in the IDE as they’re written, and opens the PR. The AWS DevOps Agent runs a release readiness review and the AWS Security Agent runs a security review, both posting their findings as PR comments. A human merges, GitHub Actions deploys to Lambda, and the AWS DevOps Agent watches production, investigating failures, surfacing root causes in its console, and pinging Slack the moment something goes wrong.

The value isn’t in any single agent. It’s in what happens when you put them together. Kiro gives you a virtual developer that carries context across sessions. The AWS Security Agent gives you a security engineer on every PR instead of once a quarter. The AWS DevOps Agent gives you a release readiness reviewer on every change, from the IDE to the PR, and an always-on SRE that triages before a human is even paged. Each phase of the SDLC (build, review, secure, operate) gets its own frontier agent, and the handoffs between them are automatic. They pass the baton through GitHub, AWS, and Slack, and the feature moves forward.

Financial services institutions adopt development tooling to deliver better software while meeting their security, resilience, and governance obligations. The workflow demonstrated here brings build, security, and operations into a shared delivery loop, helping teams identify issues earlier and reduce the time from development to production. It also retains review findings and human approvals within the delivery workflow, providing evidence that controls were applied before code reached customers. For financial services industry (FSI) teams, this combination can make software delivery faster, safer, and more straightforward to defend during governance and regulatory reviews.

Ready to explore this approach? You can start with a low-risk workload in a non-production environment. Connect Kiro, AWS DevOps Agent, and AWS Security Agent, then map each automated step to your organization’s approval, segregation-of-duties, and evidence requirements.


About the authors

Qingwei Li

Qingwei Li

Qingwei is a Machine Learning Specialist at Amazon Web Services. He received his Ph.D. in Operations Research after he broke his advisor’s research grant account and failed to deliver the Nobel Prize he promised. Currently he helps customers in the financial service and insurance industry build machine learning solutions on AWS. In his spare time, he likes reading and teaching.

Suheel Farooq

Suheel Farooq

Suheel is a Principal GenAI/ML Specialist Solutions Architect at AWS, specializing in artificial intelligence, machine learning, and generative AI. He helps Foundation Model Provider customers design, build, modernize, and scale their AI/ML and generative AI workloads on AWS — from bringing foundation models to Amazon Bedrock to optimizing training and inference and building Agentic AI solutions. His experience spans the AWS AI/ML and generative AI portfolio, particularly Amazon Bedrock, Amazon Bedrock AgentCore, and Amazon SageMaker AI. In his free time, Suheel enjoys working out and hiking.

Aastha Bhardwaj

Aastha Bhardwaj

Aastha is a Security Specialist at AWS who works with Global Financial Services customers. She helps leading financial institutions prepare for the agentic era so they can adopt AI and autonomous agents safely and at scale. She partners with CISOs and security leaders to build security into migrations and modernizations from day one, protect the AI applications and agents their teams build and use, and defend against AI-powered threats. Outside of work, Aastha loves to travel, dance, and spend time with friends.

How Thermo Fisher Scientific built AI-powered patient matching on AWS

Post Syndicated from Kaushal Patel original https://aws.amazon.com/blogs/architecture/how-thermo-fisher-scientific-built-ai-powered-patient-matching-on-aws/

Clinical trial recruitment is often described as a patient-matching challenge. In practice, it is much broader. Patient Recruitment teams need to understand where potential participants are in the recruitment journey, how sites are performing, which geographies may offer the strongest opportunities, and whether enough patients may meet increasingly complex study criteria. The answers often sit across different systems, datasets, surveys, questionnaires, consent records, marketing interactions, and operational workflows.

For Thermo Fisher Scientific, improving that experience required more than introducing a new application. It required rethinking the data foundation supporting patient recruitment and creating a more scalable way to turn recruitment data into actionable insights.

Using AWS, Thermo Fisher Scientific established a modern patient recruitment data foundation which brings together and curates data for analytics and AI-enabled use cases. Built on this foundation are complementary capabilities including Patient Recruitment’s Central Insights Hub (CIH), which provides recruitment analytics and operational visibility, and Patient Match AI, Thermo Fisher Scientific’s proprietary tool, that supports self-service patient search, feasibility assessment, and cohort discovery through natural-language interaction.

The impact is particularly visible in cohort discovery. Questions that could previously involve days or even weeks of analysis and back-and-forth with technical teams can now be explored and refined in minutes, giving recruitment teams a faster path from a question to an actionable patient population.

As these capabilities moved toward production, Thermo Fisher Scientific also worked with AWS Countdown Premium to strengthen operational readiness, support launch activities, and reduce risk during a critical stage of the transformation.

The challenge

Over time, patient recruitment data had grown across multiple systems and use cases. Patient information, surveys and questionnaires, recruitment funnel activity, marketing interactions, consent information, site data, and other operational datasets did not always exist in a single, consistent form.

That fragmentation created several challenges.

Recruitment teams needed faster ways to identify and refine relevant patient populations across large volumes of records. They also needed a clearer view of recruitment performance across studies, sites, and geographies. At the same time, the organization wanted to introduce AI-enabled capabilities without compromising data quality, privacy, governance, or compliance.

Existing processes often depended on specialized technical teams to translate business or clinical questions into database queries, retrieve the appropriate data, validate the results, and then repeat the process as criteria changed.

For a simple question, that approach could be manageable. For complex cohort discovery involving multiple clinical, demographic, geographic, or consent-related criteria, it could become a lengthy iterative process.

Thermo Fisher Scientific therefore faced two connected challenges: modernizing the patient recruitment data environment and making that data easier for business users to explore and act on.

Building the data foundation first

Rather than treating AI as a layer that could simply be added to existing systems, the team started with the data. Thermo Fisher Scientific established a modern patient recruitment data foundation on AWS to bring together information from previously disconnected sources and prepare it for downstream analytics and intelligent applications.

The new foundation standardizes and curates data from sources such as patient profiles, surveys, questionnaires, recruitment funnel activity, marketing information, consent data, and other recruitment datasets. Data transformations help create more consistent structures and reusable datasets for applications that depend on them.

This approach provides an important separation of concerns: source systems continue to serve their operational purposes, while curated datasets are prepared specifically for analytics, reporting, and AI-driven workloads.

For the business, the result is a more trusted and reusable source of recruitment information. For technology teams, it creates a scalable foundation that can support multiple products instead of building separate data pipelines for every new use case.

Turning recruitment data into operational insight with Central Insights Hub

One of the capabilities supported by this broader modernization is Central Insights Hub (CIH), Thermo Fisher’s in-house custom UI layer built using open-source technologies.

CIH is a centralized clinical trial recruitment analytics platform that helps teams understand how recruitment efforts are performing across studies.

Through interactive dashboards and visualizations, users can follow the recruitment journey from initial patient engagement through milestones such as pre-screening, referral to a study site, consent, enrollment, and randomization.

The platform brings together views of patient progression, site activity, recruitment timelines, geographic performance, and other operational measures. As CIH has evolved, additional capabilities have expanded visibility into areas such as recruitment costs, participant demographics, disqualification trends, site-patient engagement, and marketing-channel performance.

This gives recruitment teams a common place to identify bottlenecks, compare activity across sites and countries, understand where additional attention may be required, and make more timely decisions.

CIH shows how recruitment is performing and where teams should focus.

Making cohort discovery self-service with Patient Match AI

Patient Match AI, an internal tool within Thermo Fisher, addresses a different, but complementary, challenge: helping users quickly determine which patient populations may be relevant to a recruitment need.

Instead of asking a technical team to manually construct database queries, users can describe what they are looking for in natural language.

For example, a user may begin by asking for the number of patients who meet a broad clinical condition. They can then progressively refine that population by age, geography, diagnosis, treatment history, demographic characteristics, consent or contactability criteria, and other available attributes.

The intended experience follows a straightforward progression:

COUNT → REFINE → TARGETED LIST → EXPORT

Users can start by understanding the size of a potential population, refine the criteria as they learn more, and then move toward a targeted patient cohort when appropriate.

This changes the working model from a series of handoffs to a more interactive, self-service experience.

Tasks that previously could require several rounds of analysis over days or weeks can, for many common feasibility workflows, now be explored in minutes. Recruitment teams can test assumptions, adjust criteria, and understand how those changes affect the potential population without restarting the process each time.

Patient Match AI also supports aggregate insights and visualizations, helping users better understand the composition of a cohort before progressing to governed workflows when patient identity information is required.

Privacy, governance, consent, contactability, and personally identifiable information (PII) controls, consistent with applicable regulatory requirements, remain an important part of the design. The objective is not unrestricted access to patient data, but a faster and more intuitive way to work within established recruitment and governance processes.

Architecture overview

The following diagram shows how data moves from source systems through the curated data foundation into Patient Match AI and Central Insights Hub, and the key AWS services involved at each stage.

Data flowing from source systems through the curated AWS data foundation into Patient Match AI and Central Insights Hub

Figure 1: How data moves from source systems through the curated data foundation into Patient Match AI and Central Insights Hub

The solution uses a cloud-native architecture on AWS that combines managed services for data storage, transformation, orchestration, analytics, AI workloads, and application delivery.

Amazon Simple Storage Service (Amazon S3) provides scalable storage for recruitment data, while AWS Glue supports data transformation and cataloging. AWS Step Functions orchestrates multi-stage data processing workflows, and Amazon Athena runs analytical queries across curated datasets.

The analytics layer uses Apache Iceberg tables on Amazon S3, providing a flexible foundation for large-scale analytical workloads and supporting continued growth in both data volume and use cases.

A key architectural principle is the separation of operational application workloads from analytical processing. Complex cohort and eligibility queries can therefore run across large volumes of patient profiles without placing the same workload on transactional application databases.

Thermo Fisher’s identity resolution and profile consolidation processes also help bring together records originating from multiple systems, reducing duplication and establishing a more consistent view for downstream recruitment use cases.

The outcome is not simply a collection of cloud services. It is an architecture designed so that data can be ingested, curated, queried, and reused across analytics and AI capabilities without rebuilding the underlying foundation for every product.

Source systems include patient profiles, surveys and questionnaires, recruitment funnel activity, marketing and consent data, and site and operational data. These sources are ingested into the data foundation. There, AWS Step Functions orchestrates multi-stage processing, Amazon S3 provides storage, and AWS Glue handles transformation and cataloging. An identity resolution step consolidates profiles and reduces duplication.

Curated data then flows into two separated stores. Amazon DocumentDB (with MongoDB compatibility) holds identity, health, and operations data. The team selected it as the closest managed equivalent to the MongoDB database they had previously relied on. Amazon S3 with Apache Iceberg tables, queried through Amazon Athena, holds the analytics data.

These curated datasets feed the intelligence layer. Central Insights Hub provides recruitment analytics, and Patient Match AI supports natural-language cohort discovery through a COUNT, REFINE, TARGETED LIST, and EXPORT workflow. Amazon Elastic Container Service (Amazon ECS) hosts the API layer, and AWS Lambda performs patient match scoring. Results reach recruitment teams for feasibility, cohort discovery, and site, geographic, and funnel performance analysis. Throughout, privacy, governance, consent, contactability, and PII controls remain part of the design.

Preparing for production with AWS Countdown Premium

Building technology was only part of the journey. Moving a large-scale recruitment capability into production required confidence that the architecture, capacity, operating procedures, and support model were ready for launch.

Thermo Fisher Scientific engaged AWS Countdown Premium from the testing phase onward.

AWS Countdown Premium is an engineer-led support service that provides designated expertise and guidance across critical phases of cloud projects. For this engagement, that support helped the team prepare for launch in four key areas.

Designated engineering expertise

A specialist engineer selected from a team of AWS experts served as a consistent technical point of contact and developed a deeper understanding of the Patient Match AI architecture.

That continuity was valuable when working through complex technical issues. Rather than rebuilding context for each support interaction, the team could work with an engineer who was already familiar with the system and could coordinate access to additional AWS subject matter experts when needed.

One example from the engagement:
Pipeline design review: An AWS specialist engineer reviewed key design decisions ahead of launch. The patient scoring logic moved away from retrieving every record before ranking, and the pipeline was parallelized before sorting and querying. For long-running external calls in AWS Step Functions, the team adopted the wait-for-callback pattern, so they pay only for state transitions and not for idle wait time.

Operational readiness and proactive planning

The engagement focused on identifying potential issues before production rather than waiting for them to appear during launch.

Pre-event reviews, capacity planning, operational runbooks, and decision frameworks helped the team validate that the environment was prepared to support large-scale patient recruitment workloads.

Another example from the engagement:
AWS Glue readiness review: An AWS Glue specialist reviewed the team’s extract, transform, and load (ETL) jobs in non-production and shared written recommendations before launch. The team also received guidance on reading Apache Iceberg tables through the AWS Glue Iceberg REST endpoint and on putting AWS Glue Studio visual jobs under source control.

Support during go-live

During launch, coordinated AWS support provided another layer of technical coverage for troubleshooting and issue resolution.

For a production system supporting clinical recruitment workflows, this helped the team move through go-live with greater confidence and a clear escalation path for issues requiring AWS expertise.

Post-launch stabilization

Support continued beyond the initial deployment.

This provided continuity as the team monitored production behavior, addressed early issues, and transitioned from launch activities into normal operations.

Results

By combining a modern cloud architecture with support from AWS Countdown Premium, Thermo Fisher Scientific achieved several key outcomes:

  • Unified patient data – More than 20 million patient profile records, about 1.6 TB, were brought together from previously separate sources, including patient profiles, surveys, questionnaires, recruitment funnel data, marketing information and consent data.
  • Self-service cohort discovery – With Patient Match AI, recruitment teams can find and refine patient populations by asking questions in plain language, and the shared test queries run in under six seconds against the full dataset.
  • Faster feasibility analysis – Cohort analysis now takes minutes as opposed to days for many common feasibility and patient discovery workflows.
  • More timely insights – Recruitment data is kept up to date continuously, so it is available right away for AI-driven patient search and shortly afterward for analytics dashboards.
  • Modernized data foundation – The move to a data foundation built on AWS reduces reliance on the earlier Snowflake-backed dashboard environment.
  • Successful production launch – Patient Match AI went live in production in Q2 FY26. AWS Countdown Premium supported the launch through an architecture review, readiness reviews for Amazon DocumentDB and AWS Glue, and expert guidance on workflow design and query optimization over a four-month engagement.
  • Designated engineering support – A dedicated Countdown Premium engineer worked with the Amazon DocumentDB service team and specialists to tune the database, cutting estimated processing time by more than 3x.
  • Lower launch risk – Testing at full scale against the complete 20 million record dataset exposed query performance problems early, so they could be fixed before go-live.

Looking ahead

The broader value of this transformation goes beyond any single application. Thermo Fisher Scientific has established a modern, curated patient recruitment data foundation that can support different types of experiences, from operational analytics in Central Insights Hub to AI-powered cohort discovery through Patient Match AI, and that shared foundation creates an opportunity to continue evolving recruitment capabilities without repeatedly rebuilding the underlying data infrastructure.

More importantly, it changes how recruitment teams can work with data.

Instead of waiting for information to move through multiple technical handoffs, teams can increasingly interact with trusted recruitment data directly, using dashboards to understand what is happening and natural-language tools to explore what may be possible.

Conclusion

Thermo Fisher Scientific’s modernization of its patient recruitment environment, including a modern, curated patient recruitment data foundation, Central Insights Hub (CIH), and Patient Match AI, demonstrates how organizations can combine modern data architecture, analytics, and AI capabilities to solve complex, high-stakes business problems.

By using AWS services for data management, orchestration, analytics, and AI, the team created an environment that makes recruitment information easier to access, understand, and act on. Processes that once required substantial manual analysis can now be more timely, interactive, and self-service.

AWS Countdown Premium played an important role in de-risking the transition to production. Designated engineering support, proactive planning, launch assistance, and post-launch stabilization helped the team move these capabilities into production with greater confidence and operational readiness.

For Thermo Fisher Scientific, the result is more than a technology modernization. It is a foundation for helping recruitment teams move from data to insight, and from insight to action, faster.

Other organizations have used AWS Countdown Premium for similar initiatives, from improving manufacturing operations to seamless website migration and accelerating critical cloud migrations.

To learn more about how AWS Countdown Premium can support your next critical cloud initiative, reach out to your AWS account team.

Acknowledgements

Special thanks to everyone who contributed to this launch:

  • Patient Recruitment Engineering Team: Prameela Yasa, Madhurendra Singh, Prakash Singh, Karthik Tirumalasetti, Thanmay Jasti Naga Chowdry, Pawan Shah, Arnab Ghosh, Denys Martsynko, Maria Ozirskaya, Daniel Petko.
  • AWS Leadership: Kwesi Edwards, Mary Marzak.

 


About the authors

Kaushal Patel

Kaushal Patel

Kaushal is Director of Engineering within CRG Digital at Thermo Fisher Scientific, where he leads the CRG Digital Engineering Team and drives the architecture and delivery of next-generation digital recruitment solutions.

Venu Rapolu

Venu Rapolu

Venu is a Technical Account Manager (TAM) at Amazon Web Services, based in Seattle, WA. He specializes in Cloud Operations, with a primary focus on Cloud Financial Management (CFM) and FinOps. Venu partners with enterprise customers to accelerate cloud adoption, optimize cost, and drive operational excellence at scale. Away from the keyboard, Venu is passionate about community volunteering and spending quality time with his family.

Ram Pathangi

Ram Pathangi

Ram is a Senior Solutions Architect at AWS supporting healthcare and life sciences customers in the San Francisco Bay Area. He has helped customers in Finance, Healthcare, Life Sciences, and Hi-Tech verticals run their business successfully on the AWS Cloud. He specializes in Databases, Analytics, and Machine Learning. Outside of work, he enjoys traveling and meditating.

AWS Graviton support for Java in AWS Transform continuous modernization

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

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

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

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

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

Solution overview

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

Two skills cover the Graviton migration:

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

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

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

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

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

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

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

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

The walkthrough covers these steps:

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

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

Prerequisites

To follow this walkthrough, you need:

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

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

The sample application

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

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

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

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

Connect your source and discover repositories

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

To connect a source and discover repositories

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

Analyze the repository for Graviton readiness

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

To run the analysis

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

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

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

To run the analysis on the console

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

Figure 2: Graviton readiness in the Analysis type list

The Run new analysis page configured for a Graviton readiness analysis

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

What the analysis found

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

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

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

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

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

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

Remediate the findings

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

To remediate the findings

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

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

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

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

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

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

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

What the remediation changed

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

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

It then verified the exclusion took effect:

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

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

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

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

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

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

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

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

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

Validate the build on Arm64

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

To validate the build

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

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

Deploy to a Graviton instance and verify

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

To deploy and verify on Graviton

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

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

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

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

Running the application on the instance:

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

matmul 512x512 best 12.47 ms | 21.53 GFLOP/s

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

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

Scale across your portfolio

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

To analyze a portfolio on a recurring schedule

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

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

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

Clean up

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

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

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

Conclusion

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

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

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

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

 


About the authors

Harvinder Nagpal

Harvinder Nagpal

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

Venugopalan Vasudevan

Venugopalan Vasudevan

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

Varun Kulkarni

Varun Kulkarni

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

Scale distributed AI workloads with Ray and Anyscale on Amazon EC2

Post Syndicated from Sindhura Palakodety original https://aws.amazon.com/blogs/architecture/scale-distributed-ai-workloads-with-ray-and-anyscale-on-amazon-ec2/

If you are building multimodal artificial intelligence and machine learning (AI/ML) pipelines on Amazon Elastic Compute Cloud (Amazon EC2) that process text, video, and audio, you have likely hit at least one of these challenges. Scaling from a single instance to distributed compute without rewriting code, managing costs across training, fine-tuning, and inference, and keeping up with an evolving network of models, frameworks, and hardware are among the biggest challenges AI engineers face today. These challenges compound when each pipeline stage has distinct compute, networking, and storage requirements, and multiple teams own separate parts of the workflow.

This post shows how the Ray-powered Anyscale application on AWS helps you tackle these challenges. You will learn how to: deploy Ray across three AWS compute options based on your operational requirements, optimize costs by matching heterogeneous instance types to each pipeline stage, and scale from prototype to production without code changes.

How Anyscale builds on Ray

Ray Core is the distributed computing foundation underlying the entire framework. It provides primitives for parallelizing Python workloads across clusters, handling task scheduling, fault tolerance, and autoscaling. Ray AI libraries are built on top of Ray Core. As a result, custom workloads that don’t fit a standard pattern can still use the same distributed infrastructure.

Ray Data ingests and transforms datasets at scale, feeding processed data into training, tuning, and inference stages. Ray Train orchestrates distributed multi-node jobs with built-in fault tolerance, supporting foundation model fine-tuning across architectures such as Llama and Mistral with automatic selection of data-parallel, model-parallel, or pipeline-parallel strategies. Ray Tune parallelizes hyperparameter experiments across large clusters. Ray Serve runs production inference endpoints with dynamic batching, automatic scaling, and multi-model deployment support. Ray RLlib supports distributed reinforcement learning workloads, including reinforcement learning from human feedback (RLHF) for large language model (LLM) alignment.

Anyscale on AWS

Many AWS customers already run self-managed Ray clusters on Amazon EC2. Anyscale builds on that foundation as a fully managed service that deploys within your AWS account, integrating with your existing Amazon Virtual Private Cloud (Amazon VPC) networks, AWS Identity and Access Management (IAM) roles, and compliance frameworks. The application handles cluster management, autoscaling, and cost controls so you can focus on workloads rather than infrastructure.

AWS and Anyscale together address three dimensions of production AI/ML: cost-efficient infrastructure spanning the full Amazon EC2 portfolio, a Ray-on-Anyscale stack that scales reliably from experimentation to production, and an integrated framework that reduces friction at every stage of development. With Anyscale, you can map each pipeline stage to the appropriate instance type. Intel and AMD-based instances handle preprocessing, tokenization, and feature extraction. AWS Graviton-based instances cover preprocessing, worker nodes, embedding generation, and lightweight inference where price-performance matters. NVIDIA GPU instances and AWS Trainium handle training and fine-tuning. AWS Inferentia serves high-throughput inference endpoints. Amazon EC2 Spot Instances run automatically for batch training, preprocessing, and hyperparameter sweeps.

Anyscale deployment architecture on AWS

Three deployment options provide flexibility based on operational requirements:

Amazon EC2 with Elastic Fabric Adapter (EFA) provides direct compute control and high-performance inter-node networking.

Amazon Elastic Kubernetes Service (Amazon EKS) with EFA supports containerized workloads.

Amazon SageMaker HyperPod delivers managed large-scale foundation model training with built-in cluster resiliency.

Regardless of the deployment path, Ray libraries handle distinct pipeline stages. Ray Data orchestrates preprocessing across CPU-only instances, AWS Graviton-based instances, GPU instances, and Spot Instances. Ray Train, Ray Serve, and Ray RLlib handle distributed training, inference serving, and reinforcement learning on NVIDIA GPU instances and AWS AI chips.

Reference architecture showing the Anyscale on AWS solution deployed across multiple AWS services

Figure 1: Anyscale on AWS architecture

Anyscale runs a hosted control plane that sends instructions to an operator deployed in your AWS environment. The data plane (Amazon EC2 instances, storage, and networking) stays in your account, and Anyscale manages Ray cluster lifecycle without direct access to your data.

Option A: Amazon EC2

Amazon EC2 supports the full pipeline without constraint. This makes it the recommended default for teams running EC2-based workloads who want to scale into AI/ML without retooling their operations. Ray Data runs preprocessing on cost-efficient instance types including Spot Instances and Graviton processors. Ray Train handles distributed training on GPU and Trainium instances with EFA. Ray Tune runs hyperparameter search across CPU and GPU instances. Ray Serve deploys inference on Inferentia or Graviton. Ray supports reinforcement learning through RLlib on GPU instances, and RLHF workflows run through frameworks such as OpenRLHF.

Anyscale manages instance lifecycle, provisioning and terminating nodes based on demand. Amazon Simple Storage Service (Amazon S3) handles datasets, checkpoints, and model artifacts. Amazon FSx for Lustre provides parallel file system throughput for training jobs with repeated large-dataset reads. EFA is available on supported instance types for multi-node training.

Option B: Amazon EKS

Amazon EKS runs the same full pipeline within a Kubernetes environment. This makes it the right choice if your organization already manages Kubernetes and wants Ray to share the same infrastructure and tooling. The Anyscale operator deploys Ray nodes as pods, and Ray libraries run identically to the Amazon EC2 path at the application layer.

Karpenter handles node autoscaling, provisioning GPU nodes for training, Graviton nodes for preprocessing and inference, and Spot Instances for batch workloads. Ray Serve benefits from Kubernetes-integrated zero-downtime upgrades for production inference deployments. The tradeoff: Amazon EKS adds container orchestration complexity and requires custom configuration for the Anyscale operator.

Option C: Amazon SageMaker HyperPod

Amazon SageMaker HyperPod is purpose-built for resilience-critical stages where multi-week runs on large GPU or Trainium clusters make node failures expensive. It continuously monitors cluster health, automatically replaces unhealthy nodes, and resumes from the last checkpoint without manual intervention. HyperPod supports both Slurm-orchestrated and Amazon EKS-based clusters, and now supports the full model development lifecycle including inference deployment. Amazon SageMaker Studio integration adds experiment tracking and model management.

Native integrations shared by EC2, EKS, and HyperPod

Networking and storage

EFA provides low-latency, high-bandwidth inter-node communication for distributed training on all three deployment paths. Amazon S3 is the primary store for datasets, checkpoints, and artifacts. Ray Data pipelines read directly from Amazon S3-based data lakes. Amazon FSx for Lustre integrates with S3 for parallel file system throughput. Amazon Elastic File System (Amazon EFS) covers shared file access for workspaces and notebooks.

Security and compliance

Amazon Virtual Private Cloud (Amazon VPC) network isolation, IAM role-based access control, and AWS Key Management Service (AWS KMS) encryption at rest and in transit apply regardless of deployment path. Data stays within your AWS account and encryption keys remain under your control. This architecture supports compliance with frameworks including HIPAA and SOC 2 without changes to Ray workload code.

Observability

Anyscale monitoring provides workload-specific dashboards covering training progress, pipeline throughput, and request latency. Grafana dashboards are accessible from the Anyscale console. Amazon CloudWatch handles AWS metrics, logs, and alarms. Prometheus supports custom metrics collection for teams with existing monitoring pipelines.

Each deployment path follows the same workflow: Ray Data feeds processed data to Anyscale Runtime, Ray Train orchestrates training, Ray Serve handles inference through Amazon API Gateway, and Ray RLlib supports reinforcement learning.

Cost optimization and provisioning

Right-sizing compute per stage

AWS Graviton-based instances deliver strong price-performance for CPU-bound Ray workloads across preprocessing, embedding generation, and lightweight inference. PyTorch inference on Graviton3 C7g instances shows up to 50% cost savings versus x86 equivalents (Tomaz Berisa, n.d.). Graviton4 adds 30% better compute per core and 75% more memory bandwidth than Graviton3 (AWS, n.d.). Graviton also runs small language models (1–7B parameters) cost-efficiently for generative AI inference.

Intel-based instances provide strong x86 price-performance for tokenization, batch transforms, and workloads requiring broad framework compatibility. AMD-based instances deliver strong performance for CPU-intensive preprocessing, feature engineering, and inference workloads requiring maximum throughput per core. NVIDIA GPU instances provide high throughput for distributed training, fine-tuning, and large-model inference.

AWS Trainium2 delivers 30–40% better price-performance than comparable GPU instances for training at scale (AWS, n.d.). AWS Inferentia2 provides up to 4x higher throughput and 10x lower latency than its predecessor for production inference. Ray auto-detects accelerator types, so Anyscale routes each workload stage to the appropriate hardware without manual configuration.

Spot Instances with Ray fault tolerance

Anyscale keeps head nodes on On-Demand and runs workers on Spot with automatic fallback. Ray Data retries failed tasks on replacement nodes. Ray Train resumes from checkpoints, achieving up to 60% savings on distributed training. Ray Serve proactively migrates replicas on the 2-minute preemption warning.

Capacity Blocks and On-Demand Capacity Reservations

For scheduled training runs requiring capacity availability, Amazon EC2 Capacity Blocks reserve 1–64 accelerated instances for up to six months, bookable eight weeks in advance. Each block supports up to 512 GPUs or 1,024 Trainium chips, placed in Amazon EC2 UltraClusters with petabit-scale networking. Anyscale machine pools reference capacity reservations directly with priority-ordered fallback: Capacity Block, then Spot, then On-Demand. On-Demand Capacity Reservations (ODCRs) provide open-ended capacity availability.

Combined provisioning strategy

Anyscale runs two-layer autoscaling: Ray Serve scales replicas on request metrics while the cluster autoscaler provisions and terminates nodes. The recommended purchasing stack starts with AWS Compute Savings Plans, saving up to 66% across Graviton, GPU, Trainium, and Inferentia. Layer on Spot for fault-tolerant batch jobs, Capacity Blocks for scheduled training, and On-Demand for burst.

Getting started: From prototype to production

Your path follows four phases, each building on the last without code changes:

Phase 1: Validate locally (1–2 days). Start with Ray on a single Amazon EC2 instance or your laptop. Build your data pipeline and training loop, and validate model quality before touching distributed infrastructure.

Phase 2: Scale data (1–2 weeks). Deploy Ray Data with AWS Graviton and Amazon EC2 Spot Instances to process your full dataset at scale, with Spot Instances reducing preprocessing costs by up to 90% (AWS, n.d.).

Phase 3: Scale training (2–4 weeks). Choose your deployment option: Amazon EC2 for maximum flexibility, Amazon EKS for Kubernetes-native environments, or Amazon SageMaker HyperPod for resilience-critical runs. Scale training across multiple GPUs or AWS Trainium instances with EFA.

Phase 4: Deploy inference (1–2 weeks). Deploy Ray Serve for model serving with autoscaling configured to your traffic patterns.

The same code runs across all four phases. Moving from a single instance to a multi-node cluster requires only configuration changes managed by Anyscale.

Conclusion

Ray and Anyscale on AWS provide a practical path from prototype to production across the full AI/ML pipeline. Three deployment options address different operational requirements: Amazon EC2 for maximum flexibility, Amazon EKS for Kubernetes-native environments, and Amazon SageMaker HyperPod for resilience-critical training. With heterogeneous clusters mixing Amazon EC2 Spot Instances, AWS Graviton, NVIDIA GPUs, AWS Trainium, and AWS Inferentia, you can match compute to each pipeline stage. The same Ray code runs from a single instance to a multi-node cluster without modification, and Anyscale handles cluster management, fault tolerance, autoscaling, and resource orchestration.

Your next steps depend on where you are today:

  • Already running Ray on AWS – deploy Anyscale through the AWS Marketplace for managed autoscaling, cost controls, and governance.
  • New to distributed ML – start with the Anyscale documentation on a single Amazon EC2 instance, then scale out.
  • Evaluating Anyscale – explore the Ray quickstart for architecture guides and tutorials.

For more on the AWS services covered in this post, see the documentation for Amazon EC2, Amazon EKS, Amazon SageMaker HyperPod, AWS Trainium, AWS Inferentia, and AWS Graviton.


About the authors

Sindhura Palakodety

Sindhura Palakodety

Sindhura is a Senior Solutions Architect at Amazon Web Services (AWS) and Single-Threaded Leader (STL) for ISV Generative AI, where she is dedicated to empowering customers in developing enterprise-scale, Well-Architected solutions. She specializes in generative AI and data analytics domains, enabling organizations to leverage innovative technologies for transformative business outcomes.

Kinnar Sen

Kinnar Sen

Kinnar Sen is a Principal Specialist Solutions Architect at AWS for the Amazon EC2 portfolio. He has more than 20 years of industry experience in research, consultancy, engineering, and architecture, including 15 years in cloud computing. He works with AWS customers worldwide to design, migrate, and scale production workloads on EC2. Kinnar leads EC2 technical strategy for generative AI, agentic, and data analytics workloads, with a focus on price performance. He sets long-term technical direction across specialist and field teams, works with EC2 product and engineering leaders to shape what AWS builds next, and mentors the next generation of builders.

Arnab Sinha

Arnab Sinha

Arnab is a Senior Solutions Architect at Amazon Web Services (AWS), where he helps independent software vendors (ISVs) and startups build world-class solutions on AWS. He has deep expertise in cloud infrastructure, machine learning (ML), and artificial intelligence (AI), and he advises organizations on how to architect, optimize, and scale their workloads on AWS to drive business outcomes.