AWS Network Firewall now supports context-aware rules, which match traffic by the AWS resources that send and receive it instead of by IP address. A rule can name a virtual private cloud (VPC), a subnet, a security group, or a transit gateway attachment. Rules that match on IP addresses have to keep up with every workload that scales out, is replaced, or moves. Short-lived workloads are the hardest to keep up with. A VPC-attached AWS Lambda function can scale out and start sending traffic before an updated IP list reaches the firewall. With context-aware rules, you can filter a function’s traffic by the security group attached to it.
With context-aware rules, you can:
Write rules that follow your workloads – A rule that names a security group applies to each new resource whose network interface has that security group attached. A rule that names a subnet or VPC applies to each new resource that you launch in it. A rule that names a transit gateway attachment applies to traffic that enters through that attachment.
Apply one policy across accounts – One context store tracks the resources in the accounts that attach to a shared transit gateway. A rule can name context from any of those accounts.
See which resources are behind each connection – Your firewall logs record the resources on each side of a flow, along with their IP addresses.
In this post, we explain how context-aware rules work, set them up across accounts, and show what the logs record.
How context-aware rules work
Context-aware rules require transit gateway-attached firewalls, and they combine a control path and a data path (Figure 1). On the control path, a context store tells the firewall which AWS resources exist. On the data path, the transit gateway adds the context of the sender to each packet. The firewall brings the two together and matches that context against your rules.
Figure 1: How context-aware rules work across accounts
A context store tracks your resources. A context store is a catalog of the AWS resources that can send and receive traffic through a transit gateway. You create it in AWS Network Manager and associate it with the transit gateway that your firewall uses. When you share the transit gateway with workload accounts through AWS Resource Access Manager (AWS RAM), those accounts create transit gateway VPC attachments to it. The context of those attachments, and of the resources behind them, then appears in the same context store. The context store is designed to keep the firewall in sync as you add and remove resources.
The transit gateway tags each packet. When traffic crosses the transit gateway, the transit gateway tags each packet with the context of the resource that sent it. That context is the sender’s VPC, subnet, transit gateway attachment, and the security groups attached to the sender. The firewall gets only the security group IDs, not their rules, so a rule that names any one of those groups matches.
The firewall matches context IDs in your rules. It reads the context on each packet and matches it against your rules. You group context IDs into a context set, a named rule variable that lists resources from the context store associated with the firewall. Then you use the set in the source or destination of a rule, in a Classic or Next Generation firewall policy.
In this example, a central networking account owns the transit gateway and the firewall, and shares the transit gateway with workload accounts through AWS RAM. You complete steps 1 and 2 once, in the account that owns the transit gateway.
1. Create a context store. In the AWS Network Manager console, select or create a global network and register your transit gateway with it. Then create a context store and associate it with the transit gateway (). Network Firewall discovers the context store on its own, so there’s nothing to configure on the firewall.
Figure 2: A context store associated with a transit gateway
3. Create a context set. In the Amazon Virtual Private Cloud (Amazon VPC) console, under Network Firewall, create a rule group. On the Rule group variables page, choose Create context set, select your context store, and select the resources for the set. One set can mix context IDs of different resource types, from the accounts in the context store.
Figure 3: Creating a context set from the resources that the context store tracks
4. Check the sync state. Before you write rules, open the firewall’s details page and check the Context store sync state section. It shows the context store that the firewall discovered and its sync state.
Figure 4: The context store sync state on the firewall’s details page
5. Use the context set in your rules. The sample rule from Writing context-aware rules blocks SSH from PROD_RESOURCES to destinations outside your home networks. In a Next Generation firewall rule group, on the Configure rules page, use the Visual rule builder. Choose Drop and TCP. For Sources, choose Match specific criteria, select Context sets, and choose PROD_RESOURCES. For Destinations, choose Match specific criteria, select Destination IP, and enter $EXTERNAL_NET. Set the destination port to 22. Then add the rule group to your firewall policy.
Figure 5: Choosing a context set as a rule’s source in the Next Generation rule builder
The same rule in Suricata-compatible syntax follows. drop:flow is the action and its scope, tcp:all the protocol and connection state, and the rest is the source, destination, and port. In raw rules, you reference a context set with $ and its name; in the console, you pick it from a list.
drop:flow tcp:all $PROD_RESOURCES any -> $EXTERNAL_NET 22 (msg:"Block SSH from production to external"; sid:2001;)
Because the rule names resources and not addresses, it covers each new resource that you launch in those VPCs or attach that security group to.
For Classic policies, the same rule looks like this:
drop tcp $PROD_RESOURCES any -> $EXTERNAL_NET 22 (msg:"Block SSH from production to external"; sid:2001; rev:1;)
What the logs record
After you associate the transit gateway with a context store, Network Firewall adds a context object to its alert log and flow log records. The following records, shortened, show one outbound TLS connection from an application instance to example.com, through a central egress VPC with a network address translation (NAT) gateway. A rule that references the application’s security group blocks the connection and writes this alert log record. The matched list names the security group that the rule matched.
The flow log record for the same flow_id lists the full context on each side. The src list holds the sender’s context IDs. Flow logs record this context for every flow, even when no rule matches it.
The dst list shows how destination context works for traffic to the internet. The firewall learns the destination from the response, and the response reaches the firewall from the NAT gateway. So the destination context is the egress VPC, the NAT gateway’s subnet, and the egress VPC’s transit gateway attachment, not the internet host. You can query these fields by context ID in Amazon CloudWatch Logs Insights. For example, you can see what an application already connects to before you write its rules. For the fields, see Context in your network firewall logs.
Availability and pricing
Context-aware rules are available at no additional charge. Standard AWS Network Firewall and AWS Transit Gateway charges apply to the resources that you use. For details, see AWS Network Firewall pricing and AWS Transit Gateway pricing. They work in the AWS Regions where both Network Firewall and Transit Gateway context sharing are available.
Conclusion
In this post, we showed how you can use context-aware rules in Network Firewall to match traffic on the context of the resources that send and receive traffic. A context store tracks those resources across the accounts that share your transit gateway, and the transit gateway tags each packet with its sender’s context. Your rules and logs then use that context, so your rules can keep up as workloads change. To learn more, see Context-aware rules in AWS Network Firewall.
If you have questions about this post, contact AWS Support or start a new thread on AWS re:Post.
When it comes to inspecting network traffic, many security teams want two things from a firewall. They want to allow only the traffic each application needs, and they want each allowed connection checked for known threats. Today, you can do both with AWS Network Firewall, a stateful, managed network firewall and intrusion detection and prevention service. In a Classic policy, your access rules and your threat rules run together in one stateful engine and share one rule capacity.
With Next Generation policies, access control and threat protection each get their own engine in the same firewall. A firewall engine allows the traffic you approve and drops the rest. An intrusion prevention system (IPS) engine checks the allowed traffic with AWS managed rule groups or with rules that you write. Each engine has its own rule capacity, so adding access rules doesn’t take capacity away from threat protection.
In this post, we walk through what Next Generation policies are, how they evaluate traffic, and the new concepts they introduce. We use sample records to cover what each engine logs and how to validate a policy with the new monitor mode. To put it all together, we walk through creating an example Next Generation policy.
How a Next Generation policy works
A Next Generation policy inspects traffic with two engines, in sequence. Traffic that the firewall engine allows moves to the IPS engine, and traffic that the firewall engine blocks goes no further. The firewall engine is drop by default, and the IPS engine is pass by default.
If you already write Suricata rules, the two engines will feel familiar. The firewall engine is built on Suricata 8 firewall mode, which follows each connection as it progresses and evaluates rules at each step. The IPS engine uses the Suricata compatible intrusion detection system (IDS) and IPS rules that you already know from the stateful engine in a Classic policy, with one difference: it evaluates rules in action order and doesn’t support Classic options such as strict order.
A Classic policy uses a stateless engine and then a stateful engine that evaluates access rules and threat rules together. In a Next Generation policy, both engines are stateful, so each rule is evaluated with full connection context, which helps keep traffic handling consistent and predictable. The firewall engine works up to the application layer. It follows each connection for its entire flow, from the first packet through the TCP handshake and application layer exchanges such as the TLS client hello, and evaluates your access rules along the way (Figure 1).
Figure 1: Classic and Next Generation policy engines and their rule capacity.
This separation changes how you design a policy. Because each engine has one job, you can plan access control and threat protection on their own, and different teams can work independently. For example, a networking team can manage access rules while a security team handles threat detection, and neither has to rewrite the other’s rules.
The firewall engine controls access
You configure access control by specifying an action for a protocol, along with a source and destination. Rules run in the order that you set. Traffic that no rule allows gets the policy’s firewall default action, which is drop unless you change it. In a Next Generation policy, the drop default action applies from the first packet, so for TCP traffic the firewall can drop the initial SYN. Unlike the drop established default action in a Classic policy, it doesn’t wait for a connection to be established.
A few terms explain how the firewall engine evaluates traffic. Connection states are the protocol states that a connection progresses through, such as the TCP handshake and the TLS client hello. A hook is the point at a connection state where your rules attach, so a rule’s hook sets when the firewall engine evaluates it. Each rule also has an action, such as accept, drop, or reject. Its action scope sets how much of the traffic the action applies to, from one packet or one transaction up to the whole connection, called the flow. For more details, see Firewall engine hooks.
When you build a rule in the console, you choose a protocol and then two settings: Connection state, which sets the rule’s hook, and Action scope. For example, to allow a domain over TLS, you match its server name at the Client Hello connection state with the This flow action scope.
Because the firewall engine is drop by default, a connection advances to the next connection state only while your rules keep accepting it. For example, a connection can pass the TCP handshake and still be dropped at the TLS client hello. That happens when its server name isn’t on your approved list (Figure 2).
Figure 2: A connection is accepted at the TCP handshake hook and dropped at the TLS client hello hook.
In Figure 2, the rule for www.amazon.com accepts the flow when it matches the server name at the TLS client hello hook. No rule accepts example.com at that hook, so the firewall default action drops it.
You don’t have to write every rule in raw Suricata syntax. You can build rules in the console rule builder, or, as in the example later in this post, enter your domains in a domain list rule group, and Network Firewall builds the rules for you.
Action scope also sets where an accepted connection goes next. An accept with the hook scope allows the connection to advance to the next connection state, where the rules at that hook evaluate it. An accept with the flow scope lets the connection skip the remaining hooks and move to the IPS engine (Figure 3). A firewall rule can also bypass the IPS engine for specific traffic when you choose. For the valid combinations of action and scope at each type of hook, see Firewall engine actions and scopes.
Figure 3: An accept with the hook scope compared with an accept with the flow scope.
The IPS engine looks for threats
Traffic that the firewall engine allows then reaches the IPS engine, which inspects it with Suricata compatible rules. The IPS engine is designed to look for specific threats, so it blocks only traffic that matches a threat rule. IPS rules evaluate in action order. Pass rules go first, then drop, reject, and alert rules, regardless of the order in which you define them. For the full path through both engines, see How Network Firewall filters traffic with a Next Generation policy.
We recommend that you start with the AWS managed rule groups. Because the IPS engine is built on the industry standard Suricata engine, you can also run Suricata compatible rule sets from specialized security providers, alongside rules that you write yourself.
Referenced rule groups and embedded rules
Each engine gets its rules from its own section of the policy. You can add rules in two ways and mix both in one section.
Referenced rule groups are separate resources, and they’re the only kind of rule group that Classic policies support. You create a rule group once and add it to as many policies as you need. You can also share it with other accounts through AWS Resource Access Manager (AWS RAM). For details, see Sharing AWS Network Firewall resources. When you update the rule group, each policy that references it picks up the change. You set a referenced rule group’s capacity when you create it, and you can’t change it afterward, so leave room for it to grow.
Embedded rules are new with Next Generation policies. You write them directly inside one policy, and they belong to that policy only, so you can’t share them with another policy. Use them to add rules quickly that are specific to that policy. They use that engine’s rule capacity, and you don’t set a capacity up front. Embedded rules in both engine sections share a combined limit. For all limits, see AWS Network Firewall quotas.
Read what each engine logs
Whichever way you add rules, both engines write to the same alert and flow logs, which you configure in the logging configuration. Each alert record carries new fields that show which engine wrote it and, for the firewall engine, the hook where the decision happened.
The following record came from a test, in enforce mode, of the example policy that you build later in this post. A host tried to reach example.com, which isn’t on the allow list.
The following table explains the key fields in this record.
Field
Value
What it tells you
alert.engine
fw
The firewall engine wrote this record.
firewall.hook
tls:client_hello
The decision happened at the TLS client hello, where the client sends the server name example.com.
alert.signature
SURICATA FW default app policy
No rule matched, so the firewall default action applied. The default action logs its drops on its own, so you don’t need an alert rule to see what it blocks.
firewall.policy
drop:flow,alert
The action and scope that applied. The default action dropped the whole flow and wrote an alert.
The policy itself is the source, because the record doesn’t come from one of your rule groups.
When a connection that the firewall engine allowed matches a threat rule, the IPS engine writes its own record. In this test, the firewall engine allowed TLS to one test server by IP address. The IPS section also held the following embedded rule, which drops TLS connections with a JA4 fingerprint that your threat intelligence flags. The fingerprint in this rule is a sample value:
drop tls $HOME_NET any -> $EXTERNAL_NET any (msg:"Example: flagged TLS client fingerprint (JA4)"; flow:to_server,established; ja4.hash; content:"t13d1516h2_aaaaaaaaaaaa_bbbbbbbbbbbb"; classtype:trojan-activity; sid:900002; rev:1;)
This is a sample rule to show the IPS engine at work. In your own policies, we recommend that you start with the AWS managed threat signature rule groups and add custom rules where you need them.
A test client with that fingerprint connected to that server without a server name, and the IPS engine wrote the following record.
The rule is embedded in the policy, so the record shows the policy ARN. A match from an AWS managed rule group or one of your referenced rule groups carries that rule group’s ARN instead.
To separate access control events from threat events in your queries, filter on the engine field. To find which rule group produced an event, use resource_arn. Embedded rules and the default action show the policy ARN.
Validate in monitor mode, then enforce
Each Next Generation policy has a policy mode, enforce or monitor. In enforce mode, the engines apply their actions. In monitor mode, both engines evaluate your traffic and log what they would do. Your rules and the default action don’t drop or reject traffic.
Monitor mode also turns on alert logging for your rules and the default action, so each firewall rule that would block traffic logs its matches. That makes monitor mode a lower-risk way to stage a rollout of a new policy or a change to an existing one. Monitor logs are close to enforce mode but can differ. When a firewall rule would block a connection, monitor mode lets the connection through but sends it past the IPS engine, just as a blocked connection never reaches the IPS engine in enforce mode. So the monitor logs don’t show IPS alerts for that connection. For the full list of differences, see Policy mode: enforce and monitor.
To validate a policy in monitor mode:
Set Policy mode to Monitor, and confirm that alert logging is on for the firewall. Amazon Route 53 Resolved IP Validation still applies its configured action in monitor mode, so if your policy uses it, set its action to Alert.
Send representative traffic for long enough to cover your normal patterns.
In your alert logs, filter on engine = fw. Check the FirewallDefaultActionApplied metric in Amazon CloudWatch. Traffic that you meant to allow shouldn’t be reaching the default action.
When the results look right, switch Policy mode to Enforce during a maintenance window. Changing the policy mode or the firewall default action restarts stateful inspection on the firewall, which interrupts established connections.
Example policy with a domain allow list and threat protection
The following example puts the engines, logs, and monitor mode together. It allows outbound traffic only to approved domains and checks that allowed traffic for known threats. The firewall engine holds the domain allow list, and the IPS engine runs the AWS active threat defense managed rule group. Figure 4 shows the policy and where each of the earlier log records comes from. Log record 2 comes from the sample embedded rule, which isn’t part of the policy that you create in the following steps.
Figure 4: The example policy, with the sample embedded rule behind log record 2.
To create the domain list rule group:
In the Network Firewall console, choose Network Firewall rule groups, and then choose Create rule group. Choose Next Generation as the rule group version, Firewall rule group as the type, and Domain list as the format.
Figure 5: Choosing the rule group version, type, and format for the domain list.
Enter one domain per line, for example .amazon.com and checkip.amazonaws.com, and under Protocols, select HTTPS only. For HTTPS, the firewall matches the TLS Server Name Indication (SNI) without decrypting traffic. SNI is the server name that a client sends at the start of a TLS connection. To include a domain and its subdomains, start the name with a dot.
For Capacity sizing, choose Allow room to grow, and then create the rule group.
To create the policy:
Choose Firewall policies, and then choose Create firewall policy. Select Next Generation as the policy version and Drop as the firewall default action, so the firewall blocks traffic that you don’t allow. Set Policy mode to Monitor. We recommend rolling out a new policy in monitor mode first, then switching to enforce after you validate it. Enable Active Threat Defense is selected by default. Active threat defense is optional. Additional charges apply; for details, see AWS Network Firewall pricing.
Figure 6: The policy details page, with Next Generation, Drop, and Monitor selected.
On the Add firewall rule groups step, add the domain list rule group that you created in the previous procedure.
On the Add IPS rule groups step, the active threat defense managed rule group, listed as AttackInfrastructure, is already added. It comes from the Enable Active Threat Defense default that Figure 6 shows. Choose Add rule group to add more AWS managed rule groups, your own rule groups, or embedded rules.
Classic Network Firewall policies remain supported, and your existing firewalls keep running as they are. Each firewall uses one policy type at a time, either a Classic policy or a Next Generation policy. For new firewalls, we recommend Next Generation policies. We’re working on migration guidance for existing policies, so you can plan a move when it suits you.
To try one now, create a test firewall with a Next Generation policy and start it in monitor mode. To compare the two policy types, see AWS Network Firewall firewall policy versions. Next Generation policies are available at no additional charge. You pay the standard Network Firewall charges for your firewall endpoints and the traffic they process. For Regions and pricing, see AWS Services by Region and AWS Network Firewall pricing.
Conclusion
In this post, we showed you how a Next Generation policy gives access control and threat protection separate engines, each with its own rule capacity, so you can grow your firewall rules and IPS rules independently. We also showed what each engine logs, how to validate a policy in monitor mode, and how to build a policy that allows only approved domains and checks the allowed traffic for threats. To learn more, see Getting started with a Next Generation policy, and to automate your policies, use the AWS Command Line Interface (AWS CLI) or the AWS SDKs.
If you have questions about this post, contact AWS Support or start a new thread on AWS re:Post.
When the Cognition team set out to give Devin, their AI software engineer, the ability to build Apple apps, they ran into a basic requirement: Devin needed a Mac. The process of building, testing, and signing apps for iPhone, iPad, and Mac requires both Apple hardware and macOS, regardless of who (or what) writes the code, which was not supported until a couple months ago. To give Devin access to a Mac development environment, Cognition now runs macOS environments on Amazon Elastic Compute Cloud (Amazon EC2) Mac instances. With access to cloud-based Macs, Devin can build an iOS app, run it in the iOS Simulator, and check how it behaves all before it hands back a merge-ready change.
Within six weeks of launch, nearly 1,000 organizations were running Devin on macOS, according to Cognition. Cognition starts a fresh macOS virtual machine (VM) for each Devin session in under a minute, using a fleet of EC2 Mac hosts across six AWS Regions. By Cognition’s estimate, that startup time puts customers into a working macOS environment 15–20 times faster than setting up a Mac host themselves.
This post explains why Devin needed its own Mac, how Cognition built Devin workspaces on EC2 Mac, and how to plan a macOS fleet for AI agents or automated testing.
Why an AI coding agent needs its own Mac
Prior to this launch, Devin Cloud ran sessions only on Linux and Windows VMs. Devin could write Swift code and syntax in those sessions, but without macOS and Xcode it couldn’t run or test the app, so it depended on a customer’s continuous integration (CI) system or the customer’s own Mac fleet to build and test. Even then, simply having a successful build doesn’t show whether the app behaves correctly. One example of testing behavior is where an iPhone game is designed to resume where the player paused it, even after the app closes; in order to check that behavior, a software development agent has to play the game, pause it, quit, relaunch, and confirm the saved state.
You can virtualize macOS, but a Devin workspace needs more than just a bootable virtual operating system environment. Cognition needed each macOS workspace to provide the same properties as its other cloud workspaces:
A disk that keeps the work of a session, so an idle session doesn’t keep a VM running.
Network access that follows the access rules of the session.
A development environment that is ready before Devin starts.
A way for both the user and Devin to see and operate the running app.
Why Cognition chose AWS
Cognition required macOS machines to scale Devin beyond Linux and Windows, but sought to avoid the overhead of buying, racking, and maintaining physical Mac computers. The following properties of EC2 Mac shaped the Cognition design:
Apple silicon hardware in the cloud: Each EC2 Mac instance is a physical Mac mini or Mac Studio attached to the AWS Nitro System, so Cognition can run the Apple Virtualization framework on EC2 Mac the same way it would on an on-premises Mac.
Capacity through an API: Cognition allocates Dedicated Hosts and launches Mac instances with the Amazon EC2 API, instead of ordering and shipping machines.
Regions around the world: EC2 Mac is available in multiple AWS Regions, and Cognition runs in six of them.
Cognition builds Devin macOS workspaces on EC2 Mac instances, which run as bare metal instances on Amazon EC2 Dedicated Hosts. Available with Apple silicon, these instances are built on Apple Mac computers and the AWS Nitro System.
Each EC2 Mac instance runs on its own Dedicated Host, which has a minimum allocation period of 24 hours, so Cognition separates the life of a Devin session from the life of a host. In Regions where they don’t have preallocated capacity, Cognition uses an Amazon EC2 Auto Scaling group to allocate and release Dedicated Hosts.
On each host in its fleet, a Cognition VM manager uses the Apple Virtualization framework to run macOS guest VMs from images that Cognition prepares and manages. Each bare metal EC2 Mac host runs two isolated Devin workspaces at a time, because the macOS Software License Agreement (SLA) (SLA) allows up to two additional copies of macOS in virtual operating system environments on each Mac, a limit macOS enforces. Idle Devin sessions release their VMs for other Devin sessions to use, so a singular host is able to serve multiple Devin sessions a day.
Figure 1 shows how one EC2 Mac Dedicated Host serves Devin sessions. The host runs a bare metal Mac instance in one of the six AWS Regions in the Cognition fleet, with one guest VM per active session. Each guest runs Xcode tools and the iOS Simulator with the app under test, plus a live view and an accessibility tree from accessibility-cli. The user’s browser exchanges video and input with the live view, and the Devin agent queries and acts on the accessibility tree.
On the host, the VM manager runs the guests with the Virtualization framework, while a snapshot process with a Network Block Device (NBD) frontend handles disk I/O for each guest and exchanges snapshots with snapshot storage. The Devin agent and snapshot storage also run on AWS as Devin Cloud services inside the same Region, with Devin sessions hosted on Amazon EC2 and snapshots stored in Amazon Simple Storage Service (Amazon S3) (Amazon S3). For networking, a user-space Ethernet gateway takes Ethernet frames from a guest and passes IP packets to macOS packet filter (pf) rules and proxies, which apply the session access rules and send allowed traffic to the internet.
Figure 1: Devin macOS sessions on an Amazon EC2 Mac Dedicated Host
Keep session state with disk snapshots
Much of the work users do with Devin Cloud is asynchronous, and an idle session doesn’t need a running VM, so Cognition leverages the same snapshot system for macOS as its Linux VMs. The snapshot system runs as a separate process on the host and handles the VM’s disk reads and writes. Because the guest operating system sees only an ordinary virtual disk, the guest doesn’t need to know about snapshots.
On Linux, Cognition connects VMs to this storage process with vhost-user. The Virtualization framework doesn’t support vhost-user, but it does support NBD attachments, so Cognition added an NBD frontend to its snapshot system and kept the same storage design behind the new frontend. When a guest shuts down, the storage process keeps running to persist pending writes and upload the updated snapshot. The VM manager waits for the upload to finish before it completes cleanup, so stopping a session doesn’t interrupt the work that saves it.
Cognition reports that about 90% of sessions give up their Mac VM when idle and resume from a snapshot in seconds. On average, a session frees and reclaims its VM multiple times, so Mac capacity goes to active work, not idle sessions.
Apply network access rules with a user-space Ethernet gateway
Devin Cloud applies the access rules of each session to outbound traffic and blocks access to protected host infrastructure. The Virtualization framework offers three ways to connect a guest to the network: bridged networking, network address translation (NAT), and a file-handle attachment, which exchanges raw Ethernet frames over a local Unix datagram socket. NAT needs the least setup, but the Apple implementation also manages rules in pf, the macOS packet filter. Because Cognition also uses pf for its network controls, the two systems raced to configure the same filter.
Cognition chose the file-handle attachment instead and built its own Ethernet gateway to run in user space on the host, giving each Mac VM a separate gateway and its own session policy enforcement. Each Mac VM has its own gateway and its own session policy enforcement. The gateway answers Address Resolution Protocol requests from the guest and validates Ethernet addressing. It also checks that the source IP address of each packet matches the address assigned to the guest. The gateway then passes accepted IP packets into a tunnel interface on the host, where pf rules and proxies route the traffic and apply the access policy of the session.
Prepare guest images before the first boot
A Devin workspace needs more than a fresh macOS install: a user account, a usable desktop, Xcode tools, and the permissions Devin needs to observe and control apps. A fresh install asks for permissions such as accessibility and screen recording in dialogs, and each dialog would block Devin until a person approved it.
To avoid those dialogs, Cognition mounts the guest image disk on the host and prepares its state directly, creating the user and updating the macOS internal configuration databases so the permissions are in place before the guest boots. Cognition then boots the prepared image to install the remaining developer tools, verify Xcode, warm up the iOS Simulator, and let Spotlight indexing and other background setup finish. Cognition also turns off background services development sessions don’t need. With all this preparation done ahead of time, a new session can start building and testing as soon as its VM starts.
Give users a responsive live view of the app
Users can watch the macOS desktop in a Virtual Network Computing (VNC) view and their app in a new iOS Simulator pane in the Devin session. From either view, users can also try the app themselves and take control when they want.
Figure 2 shows a recorded Devin session from Cognition, in which Devin builds a 3D iPhone game and tests it in the iOS Simulator while the session’s Computer pane shows the macOS desktop.”
Figure 2: Devin builds and tests a 3D iPhone game on macOS. Video courtesy of Cognition
Two steps decide whether the live view responds fast enough for users to operate the app: capturing the screen and delivering the video. For the macOS desktop, ScreenCaptureKit, the Apple desktop capture API, supplies screen images from a limited pool of reusable buffers. When Cognition needs to keep the last captured image, it keeps its own copy instead of holding a pooled buffer, because holding a buffer while the screen is idle can delay the next screen change.
After capture, the desktop and Simulator video is encoded, sent to the user’s browser, and displayed. When one stage can’t keep up, frames wait between stages, and the stream can look smooth while it shows an old state of the app. In the iPhone game example, a user might press Pause and still see the game move, because the viewer is still showing frames from before the press. To keep the view current, Cognition limits how many frames can wait between stages and doesn’t replay a stale backlog.
Because compressed video frames often build on earlier frames, dropping a frame can leave the frames after it impossible to decode. A keyframe doesn’t depend on earlier frames, so the decoder can start fresh from it. When the Simulator stream falls behind, it restarts from a recent keyframe or asks for a new one and skips the missed frames. Keyframes are part of the compressed video stream, so they’re separate from the screen images Cognition copies at capture.
Let Devin operate native apps through the accessibility tree
Like users, Devin needs to see and operate the app, and it also needs an efficient way to check the result of each action. Devin does this through computer use, which in its simplest form takes a screenshot, has a model find a control in the image, clicks it, and takes another screenshot. This loop is slow and costly across the many pause, quit, and relaunch paths that Devin tests compared to web apps, where browser automation is more efficient. This is because the browser exposes the page structure, so Devin can find a named button or read a field’s value without working from pixels.
Native macOS apps and apps in the iOS Simulator run outside the browser, but they expose a structure of their own: the accessibility tree. Built for assistive technologies, the tree describes each control by its role, name, value, state, and relationships to other controls. Cognition exposes this tree to the Devin computer-use tool, so Devin can confirm that a control is a Resume button instead of guessing from pixels. Devin queries for a control, acts on the reference the query returns, and then reads the tree again to report what changed. The following exchange, adapted from Bringing macOS to Devin, shows a query for a Resume button and the press that follows.
Cognition built these capabilities on the open source accessibility-cli project from Dioxus, which is now part of Cognition. The project provides accessibility, input, and screen capture building blocks, and Devin turns them into the observe, reference, and act loop shown here. Even with the accessibility tree, Devin still relies on screenshots to check how the app looks. In the game example, a closed pause menu doesn’t prove the game restored the player’s position, because the app might draw gameplay directly instead of describing it in the tree.
Results
Cognition launched macOS support for Devin on September 15, 2026, and nearly 1,000 organizations were running Devin on macOS within six weeks. Devin no longer needs a customer’s CI system or Mac computers to build and test Apple apps, because it now builds, runs, and verifies iPhone, iPad, and Mac apps in its own cloud workspace. From that workspace, Devin also uploads builds to TestFlight, the Apple beta testing service.
“With Amazon EC2 Mac, we gave Devin macOS environments in the cloud, unlocking iOS and macOS development. Now customers can hand Devin platform-specific tasks such as building and testing iOS applications, without anyone managing Mac hardware. Our mac-m4pro.metal and mac-m4.metal fleet spans six regions, and we can mint fresh macOS VMs for Devin in under a minute.”
— Evan Almloff, Member of Technical Staff, Cognition
Wispr, which makes the Wispr Flow voice dictation app, uses Devin for macOS to test its iOS app end to end.
“At Wispr, a big part of testing our iOS app is making sure recording and transcription work end to end. The biggest blocker for us was end to end testing with Audio and Keyboard extension. With Devin’s macOS support, the pace of development has accelerated and it has given us more confidence in shipping features and triaging bugs. The velocity unlock is huge and cut down code review time by 70% and improved our velocity by nearly 2x.”
— Sumit Oberoi, Lead iOS Engineer, Wispr
Plan your own macOS fleet on EC2 Mac
The following points from the Amazon EC2 User Guide affect how you design a macOS fleet:
Each Dedicated Host runs one Mac instance, and you can release a host only after its 24-hour minimum allocation period.
Cognition gave Devin its own cloud Mac by running a fresh macOS guest VM for each session on Amazon EC2 Mac bare metal hosts. Disk snapshots, a user-space Ethernet gateway, prepared guest images, and accessibility-based control turn each VM into a workspace where Devin can build, run, and verify Apple apps.
“Our billing transformation with Amazon Redshift empowered the business to deliver new ways of selling which were impossible to consider before. The fact that it did this while simultaneously reducing costs by 70% and reducing operational overhead told us how powerful the approach was.”
— Sean McKibben, Principal Software Engineer, Twilio
Twilio is a cloud communications platform with APIs for messaging, voice, email, and video. It serves over 400,000 active customer accounts and more than 12 million developers worldwide to build unique, personalized experiences for their customers. Twilio’s Commerce Platform business unit owns shopping, metering, and rating domains, processing tens of billions of usage events per month across 200 million price points. The platform supports Twilio’s Opportunity-to-Revenue (OTR) initiative, a company-wide program to modernize the full billing lifecycle from customer intake through invoicing.
Challenges with the legacy billing system
Twilio built its billing system on Amazon Aurora MySQL, which reliably powered 70 partitioned database instances and converted billions of events into invoices across messaging, voice, email, and video. As Twilio’s business grew and data volumes expanded significantly, the team recognized an opportunity to evolve the architecture to meet new demands.
Following are the primary challenges with the legacy platform:
Processing slowdowns, with backlogs sometimes taking hours to clear.
Operational fragility because of frequent ETL failures requiring engineers to spend more time troubleshooting pipelines than delivering new features.
Higher infrastructure costs that were disproportionate to the business value delivered. It also lacked the flexibility to smoothly deliver features like backdated changes to pricing models or complex organizational lifecycles without manual intervention.
The billing system needs to generate invoice line items with financial-grade consistency. There can be no duplicate charges or missing events. The existing system could not support new pricing models without re-architecting, and the finance team could not run analytical queries without impacting production.
Twilio needed a distributed data warehouse architecture that could handle both transactional billing integrity and analytical flexibility. The architecture had to process billing calculations in minutes rather than hours and let finance and product teams query data without impacting production.
Overview of the solution
Twilio’s Commerce Platform team evaluated several approaches, including traditional data warehouses, data lakes with query engines, and split architectures with separate operational and analytical systems. Traditional data warehouses are optimized for analytics at the expense of real-time data consistency while operational databases handle transactional workloads but struggle with complex analytical queries at scale.
With Amazon Redshift, Twilio bridged that gap, helping queries return consistent results even for concurrent write workloads, while still maintaining high analytical performance. The key capabilities that drove Twilio to adopt Amazon Redshift Serverless are as follows:
Serverless operations — Amazon Redshift Serverless eliminates provisioning, capacity planning, and failover management. Compute scales automatically in response to workload demand, optimizing cost without manual intervention.
Real-time streaming ingestion — Billing events stream continuously through Amazon MSK. Amazon Redshift streaming ingestion delivers near real-time event data directly into the data warehouse with no requirement of intermediate landing zones.
Transactional integrity — Using serializable isolation with Amazon Redshift helped deliver consistent query results across concurrent workloads, thereby preventing data anomalies that would require custom reconciliation logic.
Materialized views AUTO refresh — Materialized views (MV) with AUTO refresh incrementally aggregate billing events by customer, product, and day, delivering near real-time rated data to downstream workgroups without batch processing.
Distributed data warehouse — With Amazon Redshift data sharing, multiple workgroups securely share data across workloads. This provides workload isolation by running analytical queries on an independent consumer workgroup without slowing down invoice processing, along with cost visibility per workload.
Transformation orchestration with dbt — dbt (data build tool) is used for orchestrating Amazon Redshift MV refreshes and stored procedure execution, managing the dependency graph across more than 200 million price points with auto-generated documentation and full calculation lineage. Amazon Redshift full SQL compatibility with dbt Core allows them to define metering, rating, and bookkeeping logic as reproducible SQL directed acyclic graphs (DAGs).
The following diagram illustrates the architecture of the solution implemented by Twilio:
Figure 1: End-to-end solution architecture
The key implementation steps for the architecture are as follows:
1. Ingestion layer
Twilio’s billing events originate from product teams across messaging, voice, email, and video. The data from these source systems are ingested into the billing system using the following ingestion pipelines:
Streaming ingestion
Each product emits usage events to Amazon MSK topics within their Amazon MSK Serverless clusters. Billing events from these topics flow into Amazon Redshift using streaming ingestion. AUTO refresh option for Amazon Redshift MVs provides real-time aggregation as events land, incrementally aggregated by customer, product, and date, thereby processing billions of events daily.
Serializable transaction isolation, combined with deduplication logic in the materialized views, allows each event to be counted exactly once.
Zero-ETL integration
Twilio’s product catalog and pricing configuration data live across multiple Amazon Aurora MySQL clusters. This legacy system contains customer account data, pricing configurations, and historical billing records that must be accessible to the new engine for reconciliation. The legacy system priced everything with whatever configuration was current at the time of processing, which worked well for forward-looking billing. However, the team needed the flexibility to reprice historical usage for corrections, promotional adjustments, and contract changes.
Using Zero-ETL with history mode for integrating Amazon Aurora databases with Amazon Redshift, every price update and configuration change is automatically captured with timestamps. As a result, the team can reconstruct any bill from any point in time after history mode was enabled. They can also reprice historical usage with the exact configuration that should have applied, or model what invoices would look like under different scenarios.
Additionally, Zero-ETL replicates data from the legacy MySQL billing shards into Amazon Redshift Serverless with CDC, eliminating custom extraction pipelines. This allowed:
Billing accuracy validation during the parallel-run period.
A unified query layer across all shards without managing shard-aware queries.
COPY command to load from Amazon S3
Finalized invoice data is exported from the invoicing platform, Zuora, in Apache Parquet format to Amazon S3, providing completed invoice line items, customer charges, and billing summaries that need to be available for customer self-service and console experiences. This invoice data in Amazon S3 is loaded into Amazon Redshift tables using COPY from Parquet on Amazon S3.
2. Transformation layer
The billing transformation logic runs on open source dbt Core with SQL DAGs defining the following transformation pipelines:
Metering
Metering deduplicates raw billing events using transaction identifiers and then aggregates events by customer, product, and time period. It also handles edge cases like late-arriving events and event corrections. dbt Core orchestrates the ingestion while auto-maintained incrementally refreshed Materialized Views aggregate billing events.
Rating
Rating applies pricing rules to metered aggregates. It manages over 200 million price points across multi-tiered volume discounts, promotional discounts that stack in specific orders, multi-product bundles, and bifurcated taxes. Each pricing rule is a discrete SQL model, and dbt orchestrates the dependency graph between them.
Bookkeeping
dbt Core orchestrates SQL transformation DAGs that generate priced aggregate artifacts formatted as invoice line items for the invoicing platform. The Bookkeeper system also creates read-only Iceberg tables from rating system data shares for data lake delivery. dbt cleans and transforms invoice data returned from the invoicing platform through Amazon S3 in Parquet format before it is written to Amazon DynamoDB for customer console experiences.
3. Storage layer
The billing engine uses multiple Amazon Redshift Serverless workgroups with AI-driven scaling, primarily 128 Redshift Processing Units (RPUs) base, up to 1,024 for heavy workloads. Amazon Redshift data sharing distributes rated data across workgroups without ETL or data copies, across all consumers in real time.
As part of the billing pipeline, three Amazon Redshift Serverless workgroups serve distinct workloads:
Metering workgroup
The Amazon Redshift Serverless workgroup hosts the auto-refreshing MVs that deduplicate and aggregate billing events and stores over half a trillion events available for immediate querying. It writes curated financial datasets directly to Amazon S3 as Iceberg tables, indexed with AWS Glue Data Catalog.
Rating workgroup
This Amazon Redshift Serverless workgroup processes pricing configuration information, from aggregated Zero-ETL sources. It then applies pricing to usage aggregates to create the central system of record for rated usage. These core datasets are then shared with Bookkeeper for use-case-specific delivery.
Bookkeeper workgroup (invoice generation)
The Amazon Redshift Serverless workgroup for invoice generation receives rated data through data shares from the rating workgroup. Data shares from this workgroup are also used to feed the Customer Usage API workgroup. This also stores priced aggregate artifacts formatted as invoice line items for the invoicing platform. It processes the invoicing platform’s return data to Amazon S3 and writes to Amazon DynamoDB for customer console experiences.
In addition, the following Amazon Redshift Serverless workgroup serves Twilio’s end customers through their public APIs:
Customer Usage API workgroup
This dedicated Amazon Redshift Serverless workgroup receives rated usage data and product catalog configurations through stored procedures from the source systems and metered aggregates through data shares from the bookkeeper workgroup. It serves near real-time billing queries for the customer-facing usage API without impacting the billing pipeline’s compute resources.
4. Consumption layer
Processed billing data serves five downstream consumers:
Invoicing platform — The Bookkeeper workgroup delivers priced aggregates as invoice line items for customer billing.
Twilio Public APIs — The Customer Usage API workgroup powers near real-time billing queries for customers, backed by live data shares from the Metering workgroup.
One Admin — Internal billing operations dashboards served directly from Amazon Redshift with sub-minute response times.
One Console — Customer self-service experiences, for example balance inquiries, CSV invoice downloads, and so on, are served from Amazon DynamoDB. The Bookkeeper workgroup loads finalized invoice data returned from the invoicing platform to DynamoDB for low-latency API serving end-users.
Product Teams — Amazon Athena queries curated financial datasets on Iceberg tables through the AWS Glue Data Catalog, providing broader organizational access without direct Amazon Redshift access.
Results
Twilio’s modernized billing engine cut infrastructure costs by 70% while accelerating billing recalculations by 12x, all while processing billions of events a month. Twilio launched the new billing system in production in mid-2026, providing rated usage for real customer invoices through Zuora. This new engine modernized on Amazon Redshift Serverless delivered measurable improvements across every dimension, which include:
70% lower infrastructure cost — Ongoing costs for the billing system dropped by 70%, while the system scaled to store almost two trillion events that the legacy architecture could not accommodate.
12x faster billing recalculation — Full month recalculations lowered from over 6 hours down to 30 minutes, along with retroactive pricing changes and scenario modeling that were previously impractical.
Over 80% reduction in processing time — 80-85% operational gain across the pipeline, with the team meeting business service level agreements (SLAs).
Sub-minute financial reporting — Finance dashboards moved from daily batch refreshes to sub-minute response times, providing near real-time visibility into billing data.
Complete pricing flexibility — The rating engine now manages Twilio’s complete catalog of 200 million price points, up from a constrained subset, with no duplicate charges or missed events.
Leaner operation — A small team manages what previously required a much larger operations team.
Most significantly, engineers shifted from firefighting pipeline failures to building new product capabilities, a cultural transformation driven by reliability and simplicity of the serverless architecture.
Conclusion
In this post, we showed how Twilio modernized their legacy billing system by adopting Amazon Redshift Serverless as the foundation for a financial-grade, real-time billing system at scale.
The modernized architecture is driven by streaming ingestion using Amazon MSK along with Amazon Redshift Zero-ETL from Amazon Aurora MySQL. With direct writes to Amazon S3 Iceberg tables cataloged with AWS Glue Data Catalog and dbt-driven transformations, Twilio built a billing engine that scales with their business. The new solution helped engineering teams to focus on billing product innovation rather than infrastructure operations. Learn more about how Amazon Redshift helped Twilio redesign their billing engine from their talk at AWS re:Invent 2025, where they co-presented with the Amazon Redshift and Amazon Athena service teams.
To learn more about the AWS services used to build modern data solutions on AWS, refer to the AWS public documentation and stay up to date through the AWS Big Data Blog.
Analytical queries often repeat the same expensive joins and aggregations, and materialized views (MVs) in Amazon Redshift optimize that pattern. An MV pre-computes and stores a query’s result, so the expensive work happens at refresh time instead of on every read. A query that would otherwise scan and aggregate large tables becomes a fast lookup of the stored result.
That speed has a running cost. Every MV consumes storage, and every refresh consumes compute, whether or not a query ever reads the result. A well-used MV repays that cost many times over. An MV that refreshes constantly but is not read costs more than it saves. So does one that fully recomputes a hundred million rows to serve a handful of queries.
As MVs become more popular in your organization, it can be challenging to keep track of which MVs are worth the maintenance costs. This post introduces a diagnostic view, v_mv_health, that reports each MV’s refresh eligibility, staleness, refresh cost, dependencies, and query activity. A companion stored procedure, sp_populate_mv_definitions(), creates and fills a table, mv_definitions, holding the one signal a view cannot compute. It reads each MV’s definition and flags the SQL constructs that block incremental refresh. Join the two for a single result set that covers these signals. Once deployed, the view and procedure give you the data to make MV health part of your regular operational review.
Solution overview
The following diagram shows how the two components fit together.
Figure 1: How the v_mv_health view and sp_populate_mv_definitions procedure combine into the MV health dataset
Both components read from Amazon Redshift system views. The v_mv_health view reads them directly each time you query it. The sp_populate_mv_definitions() procedure reads each MV’s definition, flags constructs that block incremental refresh, and writes the results to the mv_definitions table each time it runs. Joining v_mv_health with mv_definitions produces the MV health dataset, a single result set with one row per MV.
Prerequisites
The diagnostic view and procedure require:
An Amazon Redshift provisioned cluster or an Amazon Redshift Serverless workgroup with one or more MVs.
sys:superuser role, or the sys:monitor role, so the view can read activity in the cluster or workgroup. Without it, the refresh and query activity the view reports covers only your own sessions. Grant it with GRANT ROLE sys:monitor TO <username>; (for an IAM identity, use the IAMR:role-name form). For the full list of system-defined roles, refer to Amazon Redshift system-defined roles.
For a non-superuser (such as a sys:monitor user), USAGE on each schema that contains MVs, because SVV_MV_INFO only returns MVs in schemas the user can access. Grant it with GRANT USAGE ON SCHEMA <schema> TO <username>;.
The diagnostic view
Amazon Redshift already exposes the signals, but each lives in a different system view:
State and staleness: SVV_MV_INFO (current state, staleness, autorefresh setting, and interval).
Query activity: SYS_QUERY_DETAIL and SYS_QUERY_HISTORY (which MVs are actually being read, including through automatic query rewriting).
The v_mv_health view joins them into a single row per MV: state, staleness, autorefresh interval, refresh cost, query activity, dependency depth, and whether parent MVs in a chain are stale. The definition for the v_mv_health view is available in the amazon-redshift-utils GitHub repository.
The stored procedure
One signal the view can’t provide is the MV’s definition text. The sp_populate_mv_definitions() procedure iterates through each MV and extracts its definition into the mv_definitions table, created automatically if it doesn’t exist. It then scans each definition for SQL constructs covered in Refresh eligibility. The definition for the sp_populate_mv_definitions() procedure is available in the amazon-redshift-udfs GitHub repository.
The procedure uses a two-phase approach: it stages the MV object IDs into a temporary table first, then walks that local table one row at a time. It executes the pg_get_viewdef() function, which operates on one view at a time. Results are collected in a second temporary table and then replace the contents of mv_definitions in a single transaction, so each run reflects the current state of your MVs. Amazon Redshift drops the temporary tables automatically at the end of the session, so no manual cleanup is needed.
Run the procedure, then join the v_mv_health view to the mv_definitions table it populated:
CALL sp_populate_mv_definitions();
SELECT
v.*,
d.incremental_blocker_hint
FROM v_mv_health v
LEFT JOIN mv_definitions d
ON v.mv_schema = d.mv_schema
AND v.mv_name = d.mv_name;
Both objects use the same SQL on provisioned clusters and serverless workgroups. They report the MVs in their own database, so create them in each database that contains MVs.
Note: The view uses a 7-day lookback window because SYS_MV_REFRESH_HISTORY, SYS_QUERY_DETAIL, and SYS_QUERY_HISTORY retain 7 days of data by default. Amazon Redshift can retain system table data beyond 7 days by automatically replicating it to Amazon S3 Tables, a capability of Amazon Simple Storage Service (Amazon S3). Long-term retention supports SYS_QUERY_HISTORY and SYS_QUERY_DETAIL, so you can extend the query-activity signals by pointing the view’s queries on them at the retained tables. At the time of writing, SYS_MV_REFRESH_HISTORY is not among the retained system tables, so the refresh-cost columns remain limited to the 7-day in-cluster window unless you capture that history yourself.
What the output tells you
The joined output returns one row per MV:
Column
What it means
mv_database
Database containing the MV
mv_schema
Schema containing the MV
mv_name
MV name
state
1 (incremental), 0 (full_recompute), 101-105 (broken). Refer to SVV_MV_INFO
state_label
incremental, full_recompute, or broken with its cause (for example, broken:column_renamed)
is_stale
Whether MV data is out of date relative to base tables; NULL for MVs on external tables other than Iceberg.
is_autorefresh
Whether automatic refresh is turned on
autorefresh_interval_sec
Autorefresh interval in seconds; NULL when autorefresh is off
is_default_autorefresh_interval
Whether the MV uses the cluster or workgroup default interval rather than its own. false when autorefresh is off
is_autorewrite_eligible
Whether the optimizer can transparently rewrite queries to use this MV
refresh_count
Refresh attempts in the last 7 days, including failed refreshes and refreshes that found the MV already up to date
query_count
Queries that read the MV in the last 7 days, including queries served through automatic query rewriting. Refreshes are excluded; NULL if the MV’s storage table can’t be found in the catalog
recompute_to_query_ratio
Full-recompute refreshes (not incremental) ÷ queries. High values indicate refresh cost may exceed benefit; NULL when query_count is 0 or NULL
avg_refresh_sec
Average refresh duration in seconds
last_refresh_status
Status message from the most recent refresh, such as incremental, full recompute, or already up to date
mv_rows
Row count of the MV, for gauging refresh cost against usage
chain_depth
Depth in a dependency chain (0 = no MV dependencies)
mv_dependencies
Parent MVs the MV depends on; NULL if it has no parent MVs
stale_ancestors
Parent MVs in the chain that are currently stale; NULL if no parent MV is stale
pct_of_total_query_time
Refresh time as a percentage of total query time on the cluster or workgroup
incremental_blocker_hint
SQL constructs preventing incremental refresh, evaluated only for state 0 MVs (none otherwise, unidentified when no known construct matches). From mv_definitions
Refresh eligibility
Amazon Redshift refreshes an MV in one of two ways. In an incremental refresh, Amazon Redshift identifies the changes to the data in the base tables since the last refresh and updates the data in the MV. In a full recompute, it reruns the MV definition, replacing the data in the MV. Amazon Redshift automatically chooses the method based on the query that defines the MV.
Each MV in Amazon Redshift falls into one of three states:
Full recompute (state 0): The entire MV is rebuilt from scratch on every refresh.
Incremental (state 1): Only changed rows are processed on refresh.
Broken (state 101-105): The MV cannot refresh at all and must be dropped and recreated.
The state column tells you which category each MV falls into. An MV’s state depends on its definition, not its size. Its size (mv_rows) determines how much that state costs. An incremental refresh on a 100-million-row table might process 50 changed rows, while a full recompute scans all 100 million regardless of how few changed.
Note: A state 1 MV can still occasionally fully recompute, for example after a VACUUM with the FORCE option on a base table while the MV is out of date, or when the MV hasn’t been refreshed for an extended period. These show up as full recomputes in recompute_to_query_ratio even though the state is 1. If you need VACUUM FORCE, run it straight after refreshing the dependent MVs.
Certain SQL constructs block incremental refresh. The incremental_blocker_hint column identifies which constructs are preventing incremental eligibility. If any of the following appear in the MV definition, the MV cannot refresh incrementally and falls back to a full recompute on every refresh:
Distinct: SELECT DISTINCT, COUNT(DISTINCT ...).
Outer joins: LEFT, RIGHT, or FULL OUTER JOIN.
Window functions: anything with an OVER() clause (ROW_NUMBER, RANK, SUM, NTILE, and so on).
Subqueries: in the WHERE clause or SELECT list (subqueries in the FROM clause are fine).
An MV may trip more than one of these at once, and incremental_blocker_hint lists each one it finds.
Note:incremental_blocker_hint is a heuristic text scan of the MV definition, not a semantic parse, and is evaluated only for MVs in state 0. The other MVs show none. It matches whole-word SQL keywords, so it won’t trip on names like distinct_count, but a keyword inside a string literal (for example, WHERE status = 'union') can still produce a false positive. Treat it as guidance and verify by inspecting the definition.
OUTER JOIN is a frequent blocker. Outer joins (FULL, LEFT, and RIGHT) are a legitimate and important SQL pattern, but they prevent incremental refresh in MVs. If you need incremental eligibility, you have options: if the join always produces a match (no NULLs in the result), rewriting as INNER JOIN restores incremental refresh with no change to output. If the outer join is genuinely needed, consider handling the unmatched rows upstream. For example, pre-joining in an ETL step, or using a regular view for the outer join while keeping the MV incremental on the inner-joined subset.
For the full list of incremental refresh limitations, refer to Refreshing a materialized view in the Amazon Redshift documentation.
Refresh cost
Every refresh consumes compute resources. The pct_of_total_query_time column shows what share of total query time is spent refreshing each MV, and avg_refresh_sec identifies individual MVs with unusually long refresh times. There is no universal threshold, because what counts as expensive depends on the cluster. Start with the MVs that rank highest on pct_of_total_query_time: those in the highest decile of refresh cost, and those whose cost looks large relative to the queries they serve.
The net-negative MV. An MV that refreshes frequently but is never queried consumes resources without delivering value: refresh_count > 0 with query_count = 0. If is_autorefresh = true and query_count = 0, consider dropping the MV. If it’s still needed occasionally, lengthen its autorefresh interval or switch it to manual refresh on demand.
Refresh-to-query ratio. Even when queried, the refresh cost may exceed the benefit. If an MV fully recomputes many times for every query that reads it, the caching isn’t paying for itself. The recompute_to_query_ratio column flags this. Consider lengthening the autorefresh interval or scheduling refreshes to match how often the MV is read, or dropping the MV entirely.
Note: Amazon Redshift supports creating an MV on a consumer warehouse over data-shared base tables or directly refreshing an MV from a remote warehouse. This isolates the compute and minimizes cluster disruption, whether the refresh is full or incremental.
Dependencies and staleness
Amazon Redshift supports MVs that reference other MVs, known as nested MVs. Nested MVs can be refreshed together, in dependency order, using REFRESH ... CASCADE (refer to Harnessing the power of nested materialized views and exploring cascading refresh). The chain_depth column shows how deep each MV sits in a dependency tree, and mv_dependencies lists its parent MVs.
Staleness propagates one hop at a time. The is_stale column reports whether an MV’s data is behind its base tables. When base table data changes, the immediate dependent MV is marked is_stale = true. Downstream MVs remain is_stale = false until their direct parent is refreshed. At that point they become stale in turn. For deeper chains, is_stale = false on a downstream MV indicates freshness relative to its immediate parent, not the original base table. The stale_ancestors column walks the full chain and reports which parent MVs are currently stale.
CASCADE refresh solves propagation but requires explicit invocation.REFRESH MATERIALIZED VIEW mv_name CASCADE refreshes the entire chain in topological order (parent MVs first). It is not automatic and autorefresh does not cascade, so run it at your required freshness interval, for example on a schedule with Amazon EventBridge and the Amazon Redshift Data API, or as the final step of the ETL job that loads the base tables. Refer to the Autorefresh section for details on when AUTO REFRESH YES is supported.
Note:CASCADE is supported only for chains built on local tables, data-shared tables, local MVs, and streaming MVs. It doesn’t extend to MVs on Amazon Redshift Spectrum sources or to MVs shared from another warehouse, which must be refreshed individually in dependency order. Each additional level in a dependency chain adds refresh latency and widens the window where downstream MVs serve data that hasn’t caught up. Keep chains shallow, and weigh that lag against the benefit the chain provides.
Refreshing materialized views on external tables
MVs can cache results from external tables stored in Amazon S3, so each query reads the stored result instead of re-scanning the same Amazon S3 files. Refresh behavior depends on two factors:
Data storage format: a standard file type (Parquet, CSV, Avro) or an open table format (Apache Iceberg, Hudi, Delta Lake). When new files appear in Amazon S3, MVs on standard file types and Iceberg refresh incrementally, whether or not they aggregate. Hudi and Delta Lake don’t support incremental refresh.
Aggregation: whether the MV aggregates (GROUP BY, SUM, COUNT). When a file is deleted or overwritten, a non-aggregating MV stays incremental, but an aggregating MV must fully recompute, because aggregates can’t be undone without re-reading the remaining data. The last_refresh_status column reports this as “A full recompute was successfully completed as a data file was deleted.”
Apache Iceberg supports incremental refresh in more cases than the other formats. Iceberg’s metadata layer tracks row-level changes (inserts, deletes, updates, compaction), so aggregating MVs stay incremental even when rows are removed. Iceberg is the only data lake format that accepts AUTO REFRESH YES. For MVs over data lake sources where incremental refresh matters, Iceberg is the strongest fit (refer to materialized views on external data lake tables). For a deeper treatment of how incremental refresh works across data lake table formats, refer to Incremental refresh for Amazon Redshift materialized views on data lake tables.
Note: An incrementally refreshable materialized view on Iceberg tables may fall back to a full recompute if that is expected to perform better, or if it joins multiple base tables and more than one of them has been updated since the last refresh.
The following table summarizes the refresh method each source format uses for file additions and deletions, and whether it supports autorefresh:
Source format
On file addition
On file deletion, non-aggregating MV
On file deletion, aggregating MV
Autorefresh
Apache Iceberg
Incremental
Incremental
Incremental
Supported
Parquet / CSV / Avro
Incremental
Incremental
Full recompute
Not supported
Hudi / Delta Lake
Full recompute
Full recompute
Full recompute
Not supported
Note: On Iceberg tables, an aggregating MV falls back to a full recompute if a snapshot it needs has been expired. Expire snapshots only after refreshing the MVs that depend on the table, and if you use AWS Glue Data Catalog snapshot retention, keep the retention period longer than the interval between MV refreshes. Refresh after compaction stays incremental but processes more data, so plan for a longer refresh.
On Amazon Redshift RG instances and Serverless, external table queries run through an integrated query engine rather than Amazon Redshift Spectrum, which can reduce MV refresh times on Iceberg data. No configuration change is required.
Autorefresh
Autorefresh keeps MVs current without manual scheduling. The is_autorefresh column shows which MVs have it turned on, and autorefresh_interval_sec shows how often Amazon Redshift checks each one for staleness. An autorefresh runs only when the MV is stale, with the same priority as other user queries. On provisioned clusters, autorefresh queries run in your workload management (WLM) queues alongside your workload and appear in STL_QUERY. On Amazon Redshift Serverless, they consume Redshift Processing Units (RPUs) like any other query. On both, SYS_MV_REFRESH_HISTORY is where you see autorefresh activity, because it doesn’t appear in SYS_QUERY_HISTORY.
Autorefresh on high-churn tables generates constant refresh activity. Some base tables change frequently through streaming ingestion, AWS Database Migration Service (AWS DMS) replication, or zero-ETL. On those tables the MV is almost always stale, so autorefresh runs at every interval (5 minutes by default). The refresh_count column quantifies this. The worst case is autorefresh on a state 0 MV. Every refresh is a full recompute, so at the default interval that’s a full rebuild of the MV every 5 minutes. If the MV doesn’t need to be that current, keep autorefresh on but lengthen the interval (minimum 60 seconds) to match how often the results are queried: ALTER MATERIALIZED VIEW mv_name AUTO REFRESH YES INTERVAL <seconds>. To change the default for every MV on the cluster or workgroup, use ALTER SYSTEM SET default_mv_auto_refresh_interval = <seconds>. For details, refer to ALTER MATERIALIZED VIEW and ALTER SYSTEM. Custom intervals aren’t supported on streaming MVs.
Autorefresh does not cascade. It refreshes only the configured MV, not its dependents. AUTO REFRESH YES is rejected at creation time on nested MVs and on external tables other than Iceberg, returning an error rather than being silently ignored. On a nested MV the message is “Auto-refresh is not supported for materialized views defined on other materialized views.” It is supported on local single-level MVs over Iceberg or datashare tables, but not on an MV that combines both.
Broken materialized views
An MV becomes permanently broken when the definition of its base table changes in certain ways. The state column shows values 101-105 for broken MVs, with a label indicating the cause (refer to SVV_MV_INFO for the full state code reference).
Renaming an object that an MV depends on is not blocked, and it leaves the MV unable to refresh. A rename of a column, table, or schema completes without an error and moves the MVs that reference it to a broken state (103-105). Once broken, an MV cannot be refreshed, and renaming the object back does not restore it. The fix is to DROP and CREATE the MV.
Dropping a column that an MV uses, or changing its data type, is rejected. Amazon Redshift returns an error and the MV stays healthy.
Identify affected MVs before you alter a base table or column.SVV_MV_DEPENDENCY only shows MV-on-MV relationships, not base-table dependents. Before you make such a change, use the v_view_table_column_dependency view in the amazon-redshift-utils GitHub repository to identify the dependent MVs and the specific columns they rely on.
Automatic query rewriting
Amazon Redshift can rewrite a query on base tables to read from an MV, even when the query doesn’t name it (refer to Automatic query rewriting to use materialized views). The query_count column includes these reads. The is_autorewrite_eligible column shows whether the MV’s definition allows rewriting.
Eligible doesn’t mean used. Amazon Redshift skips a stale MV until its next refresh, even though the flag stays true. The flag also reads true for nested and broken MVs, which aren’t used. To confirm a specific query was rewritten, run EXPLAIN on it. In a rewritten plan, the base tables the MV covers no longer appear. In their place is a scan of an internal table that holds the MV’s results.
Should this be a materialized view?
Not every cached result benefits from being an MV. The following characteristics indicate when an MV is a strong fit and when an alternative is likely better:
Favors a materialized view
Points to an alternative
Analytical queries from dashboards and analysts
Application lookups serving thousands of concurrent requests
Multiple users or queries read the result
The result is read once or rarely
The query scans a large table but returns few rows
The query returns most of the rows it scans
Query latency is unacceptable without pre-computation
A regular view already meets the latency requirement
Readers can tolerate data that is a refresh interval old
Readers need sub-minute freshness
When your workload matches the right-hand column, a different approach usually fits better: a regular view when the query is already fast enough, in-stream transformation when readers need sub-minute freshness, and an in-memory cache such as Amazon ElastiCache for application lookups at high concurrency.
Putting it together
Deploy the diagnostic view and stored procedure. Run them periodically. Weekly is sufficient for most clusters. Focus on:
State 0 MVs with high refresh cost: Check incremental_blocker_hint. If it names an SQL construct, refactor it (for example, OUTER JOIN to INNER JOIN). If it reads unidentified, confirm the full recompute is justified.
MVs with query_count = 0: Consider dropping them.
Deep chains with stale ancestors: Refresh with REFRESH ... CASCADE to bring the chain current, and flatten chains that are deeper than they need to be.
Broken MVs (state 101-105): Drop and recreate.
Autorefresh MVs on high-churn tables: Compare refresh_count against query_count. When refreshes far outnumber reads, lengthen the autorefresh interval to match how often the results are actually queried.
The goal is MVs whose refresh cost is repaid by the queries they accelerate.
Automate the review. Rather than running the diagnostic by hand, schedule it. v_mv_health is consistently current because it reads the system views each time you query it, so only the procedure needs a schedule. For a basic setup, run CALL sp_populate_mv_definitions(); on a cadence with Amazon EventBridge and the Amazon Redshift Data API. For alerting or dashboards, refer to Building an event-driven application with AWS Lambda and the Amazon Redshift Data API, which uses Amazon EventBridge and AWS Lambda to run a stored procedure on a schedule.
Cleaning up
The diagnostic objects are lightweight (a view, a stored procedure, and a small definitions table), but if you no longer need them, remove them with:
DROP VIEW IF EXISTS v_mv_health;
DROP PROCEDURE sp_populate_mv_definitions();
DROP TABLE IF EXISTS mv_definitions;
Summary
In this post, we showed how to check the health of the MVs in an Amazon Redshift database from a single result set. The v_mv_health view and the sp_populate_mv_definitions() procedure surface the signals that matter. Together they cover refresh eligibility, cost, staleness, dependencies, broken states, and autorefresh behavior. Call the procedure, join its output to the view, and you can see which MVs need attention first.
With v_mv_health and sp_populate_mv_definitions() deployed in each database that contains MVs, you can make MV health a routine part of your operational reviews.
Pre-scheduled events like concert ticket on-sales and product launches can drive a load spike 100 times higher than the baseline. The spike persists for a few hours while the inventory clears, then traffic returns to normal. If you miss the first minute of the on-sales, customers experience errors while competitors keep selling, and the event’s reputation takes a hit. Over-provision for the burst, and you pay for peak capacity 24 hours a day, 365 days a year. The actual peak lasts 10 minutes and happens 10 times a year.
In this post, you will see how AWS Lambda Managed Instances, a capability of AWS Lambda, handles predictable traffic bursts. It keeps compute capacity warm before the on-sales event opens and scales it back down afterward. You will see a reference ticketing implementation that sustains 40,000 transactions per second (TPS) for 120 seconds.
Understanding Lambda Managed Instances
Lambda Managed Instances runs your Lambda functions on Amazon Elastic Compute Cloud (EC2) instances in your account, including Graviton4 and memory-optimized instance types. AWS handles the underlying infrastructure lifecycle (provisioning, scaling, patching, and routing), while you benefit from EC2 pricing including Compute Savings Plans and Reserved Instances.
Lambda Managed Instances provides several benefits. With pre-provisioned execution environments (EE), capacity is already warm before traffic arrives, so there are no cold starts when a burst hits. Scaling bounds are configurable with MinExecutionEnvironments and MaxExecutionEnvironments for each function, and each new EE comes online in 1–2 seconds. With multi-concurrent invocations, one EE handles multiple requests at once, which improves utilization for I/O-heavy handlers. You also get EC2 pricing, so Compute Savings Plans and Reserved Instances apply instead of per-request Lambda pricing.
Lambda Managed Instances is well suited for predictable, spike-shaped workloads that need sustained compute capacity during the peak and can scale back down when traffic returns to the baseline.
Predictable burst workloads work best with Lambda Managed Instances
This post focuses on one of the key capabilities of Lambda Managed Instances: absorbing scheduled traffic bursts without provisioning for peak year-round. Some of the use cases where Lambda Managed Instances helps are ticket and event on-sales (concerts, sports, festivals), live streaming and voting events, and scheduled batch and report generation nightly or hourly jobs that consume steady compute during a defined window.
Use case: High-throughput ticket booking with Lambda Managed Instances
To demonstrate Lambda Managed Instances handling predictable traffic bursts, we built a concert ticketing backend. The solution implements the industry-standard queue-plus-hold-and-confirm booking flow, a pattern that ticketing platforms, airlines, and hotels use to prevent overselling during large traffic spikes. It separates user traffic management from the critical database transactions required to lock inventory.
The following diagram presents the detailed architecture of the solution we built.
Figure 1: Architecture of the concert ticketing solution across two AWS CloudFormation stacks
The solution deploys two AWS CloudFormation stacks in a single AWS Region. In the first stack, Amazon API Gateway routes public HTTPS traffic through three ticketing handlers hosted in Lambda Managed Instances on a shared capacity provider. Amazon ElastiCache Serverless for Valkey holds the atomic queue counter. Amazon DynamoDB holds durable per-seat state across a write-sharded inventory table (500 shards) and a bookings table. WarmThroughput is pre-provisioned to absorb the burst without waiting for adaptive capacity. A separate simulation stack drives synthetic load through a three-tier Lambda fan-out, reproducing the on-sales burst shape at any target TPS.
Public traffic and load-generation traffic take completely separate code paths, so the load generator’s own scaling behavior does not affect measurements on the ticketing stack. Each successful booking traverses three Lambda handlers. Handler queue-position assigns an atomic virtual queue number using an INCR on a single ElastiCache key. Handler inventory-lock places a time-bounded hold on a specific seat through a DynamoDB conditional UpdateItem, moving it from AVAILABLE to HELD with a time to live (TTL) of 180 seconds. Handler booking-confirm executes a single TransactWriteItems call that atomically transitions the seat from HELD to CONFIRMED and writes a durable booking record. Either both writes succeed or neither does.
All three handlers are stateless, because each request they receive is treated as an independent, standalone transaction. The mutable state lives in ElastiCache and DynamoDB, stored with safety features like conditional writes and atomic operations to avoid collisions, race conditions, and overwrites. This is why the multi-concurrent EE model of Lambda Managed Instances can serve thousands of simultaneous invocations per instance safely.
What makes this solution better with Lambda Managed Instances
With Lambda Managed Instances, you keep the same Lambda programming model, one function per handler, and the same deployment story, while Lambda Managed Instances handles the fleet. Raise MinExecutionEnvironments a few minutes before an on-sales opens, let it burst inside the Min to Max range while traffic is live, and scale back down when the window closes.
Deploy the application
For the full deployment instructions, refer to the README file in the GitHub repository after you have cloned it.
AWS Service Quotas – the initial deployment works with an AWS account’s default service quota. Peak-load testing requires EC2 vCPU and API Gateway throttle quotas increase.
Run the application
Once deployed, all test traffic goes through the simulation API. The sample includes an optional single-page web user interface (UI) (see the demo-ui/ folder in the repository) that wraps the same endpoints and renders the per-burst results interactively.
Read the “Cost considerations” section before running a simulation to understand the cost you will incur in the process.
1. Smoke test – low TPS to verify the pipeline end-to-end:
By default, deploy.sh provisions a cost-safe baseline of three warm EEs (Min=1, Max=3 per handler). The following smoke test works on this baseline.
To reproduce the headline result, scale the Lambda handlers to the per-handler Min and Max values before firing the peak-load test. Refer to the Peak-load testing section of the GitHub repository before firing the burst. This also requires an EC2 vCPU and an API Gateway account-throttle quotas increase above the default.
The response includes total requests, total bookings written to DynamoDB, delivered peak TPS, and end-to-end latency percentiles.
Interactive demo UI
The sample repository ships an optional single-page web UI (in the demo-ui/ folder) that wraps the same simulation and dashboard endpoints as the preceding curl examples. Point it at your simulation API endpoint, then fire bursts and view results interactively without leaving the browser.
Configure and start the UI:
# In demo-ui/config.js, set SIMULATION_API_URL to your simulation endpoint.
cd demo-ui && python3 serve.py
# Serving on http://localhost:8000/
Fire a burst. Choose a target load (a preset button or a custom TPS value), set the sustain duration and ramp, then choose Start burst. The UI sends a POST request to /simulation/start and stores the returned run_id and event_id, so you can query DynamoDB directly if you want to drill deeper.
View results. After the burst completes, choose View results. The UI queries API Gateway metrics, DynamoDB, CloudWatch Logs Insights, and CloudWatch Lambda metrics in parallel to reconstruct the run: total requests received, durable bookings written, and a per-handler table showing EEs used, Lambda throttles, and p95/p99 latency.
Figure 2: Demo UI results panel from a 40,000 TPS, 120-second run
The panel shows 4,804,200 API Gateway requests and 1,750,886 durable bookings, plus a per-handler table with the baseline EE pool (50/100/150 for queue-position, inventory-lock, and booking-confirm). During the burst, 36 additional EEs are pre-emptively warmed on booking-confirm, with zero Lambda throttles and p99 latencies of 4.7, 15.8, and 39.8 ms.
The identifiers panel at the top exposes the burst’s run_id (the partition key in the simulation metrics table) and event_id (used in both the inventory and bookings tables), so you can locate them directly in DynamoDB or CloudWatch Logs Insights for the specific burst you ran.
What we measured
Across a load range from 5,000 to 40,000 requests per second, the pre-warmed EE pool served every burst without cold-start impact. Key results from the headline 40,000 TPS × 120-second burst:
Metric
Value
Delivered peak throughput
40,035 req/sec
Total HTTP requests
4,804,200
Durable bookings written to Amazon DynamoDB
1,750,886
End-to-end p50 / p99 latency
44 ms / 121 ms
AWS Lambda errors
0
AWS Lambda concurrency throttles
0
Amazon DynamoDB write throttles
0
The tested range spanned 5,000 to 40,000 requests per second, an 8× spread in delivered load. Across it, p99 latency stayed within a 3 ms band. Doubling sustained throughput from 20,000 to 40,000 requests per second held at exactly 121 ms, which confirms that the pre-warmed pool had substantial headroom throughout the tested range.
Observability
Lambda Managed Instances automatically publishes metrics to CloudWatch and structured logs to CloudWatch Logs, giving you visibility into function performance and capacity utilization without additional code. During a burst, the metrics that matter most are:
Duration percentiles per handler to confirm p99 latency stays flat as load rises.
ConcurrencyThrottles to detect if any handler hits its MaxExecutionEnvironments ceiling.
Errors for handler-side failures.
EE count (log-derived) to observe how quickly Lambda Managed Instances adds warm capacity above Min.
The sample repository includes a demo dashboard endpoint that queries CloudWatch metrics, CloudWatch Logs Insights, and DynamoDB in parallel to reconstruct a per-burst report, API Gateway request count, durable bookings landed, distinct EEs used, and per-handler latency percentiles. Reconciling the simulation-side counts against the AWS ground truth catches load-generator artifacts and confirms the system-under-test numbers.
Cost considerations
Lambda Managed Instances uses EC2 instance pricing plus a 15% management fee. Compute Savings Plans and Reserved Instances apply to the underlying instance cost.
The Lambda Managed Instances configuration runs a small always-on baseline and uses a scaling script to pre-warm to 50/100/150 EEs in the minutes leading up to each event, then scales back down to baseline afterward.
To simulate a peak load under controlled conditions, the fleet is pre-warmed for a 7-minute window (5-minute ramp and 2-minute burst) then scaled back down. The cost breakdown can be as follows.
Component
Volume
Rate
Cost
API Gateway requests
4.8 M
$3.50 per 1 M
$16.80
DynamoDB writes
8.8 M WCU
$1.25 per 1 M
$11.00
Lambda Managed Instances compute (peak window)
75 × c7i.4xlarge × 7 min
$0.821 / instance-hr
$7.18
Lambda Managed Instances request charges
4.8 M
$0.20 per 1 M
$0.96
CloudWatch Logs (~2 GB)
ingestion
$0.50 per GB
$1.00
Amazon ElastiCache Serverless for Valkey
4.8 M INCR operations
ECPU-based
$0.30
Total per burst
~$37.00
The estimated cost for simulating each burst is around $37.
Best practices
Based on experience building this solution, here are key recommendations:
Pre-warm before scheduled events. Raise MinExecutionEnvironments using an Amazon EventBridge Scheduler rule or a manual scaling script when you expect major spikes, giving Lambda Managed Instances enough time to scale the underlying instances. Restore the low baseline after the event.
Set MaxExecutionEnvironments aggressively. Lambda Managed Instances adds new EEs to your capacity provider. A high MaxExecutionEnvironments value costs nothing while idle but absorbs unexpected demand during the burst.
Write-shard hot DynamoDB tables. For workloads writing thousands of items per second to one logical entity (a single event, a single product SKU), spread writes across a synthetic sharded partition key. This sample uses 500 shards per event.
Use WarmThroughput on DynamoDB tables. Pre-provision physical partitions before the burst rather than waiting for adaptive capacity to expand during the first minute of the on-sales.
Keep hot atomic counters out of DynamoDB. Single-row atomic increments in DynamoDB cap at approximately 1,000 operations per second.
Make write endpoints idempotent. The sample uses a caller-provided booking_id on the confirmation endpoint so that retries produce the same booking record instead of duplicates.
Clean up
When you are done exploring the solution, remove the provisioned resources to avoid ongoing charges. For the full cleanup commands and exact steps, refer to the GitHub repository README file.
Conclusion
Lambda Managed Instances brings the same Lambda programming model to workloads that need sustained, pre-provisioned compute during predictable bursts: ticket on-sales, product launches, registration windows, and other scheduled surge patterns. The concert ticketing example shows how a queue-plus-hold-and-confirm pattern built on Lambda Managed Instances can sustain 40,000 requests per second while costing less than an always-on EC2 fleet sized for the same peak.
AWS Security Incident Response continuously triages the threat findings from Amazon GuardDuty and AWS Security Hub CSPM, but most of that work never shows up as a case. If cases are all you look at, it’s hard to tell whether the service is working at all, and that’s the question I hear most often when I help customers onboard. The Proactive response dashboard gives you a high-level view of this activity, and this post takes you behind the numbers to show what happens to an individual finding.
In this post, I walk you through what happens to a finding after it’s ingested by the service, what gets triaged, where each finding is sent, and how a triage decision becomes a case. I then show you how to confirm triage is working day-to-day, so your team can focus on the findings that require attention. The process flow is shown in Figure 1.
Figure 1: AWS Security Incident Response triage flow, from ingestion through to one of three outcomes
Ingestion
AWS Security Incident Response ingests threat findings from GuardDuty through Amazon EventBridge rules that are automatically deployed to your accounts during the onboarding process.
If you send third-party detection findings to Security Hub CSPM from tools such as CrowdStrike, Trend Micro, or Lacework, their threat detection findings are also ingested. Each of those findings must carry complete payload information such as resource ID, account ID, timestamp, and threat details. GuardDuty findings are ingested directly, so these findings aren’t re-ingested through Security Hub CSPM and there’s no duplication.
Triage
The service triages findings that indicate an active threat, such as compromised credentials, cryptomining, or data exfiltration. These represent activity that’s underway or has already occurred.
Posture and compliance findings aren’t triaged. A misconfiguration or a failed benchmark check reflects the state of your environment rather than an active threat, so those findings remain for your team to address through your existing remediation process.
Outcomes
For each threat finding, the service runs an automated triage process. It evaluates the finding payload, related AWS activity from AWS CloudTrail and Amazon VPC Flow Logs, AWS threat intelligence, and the context you provide about your environment. The service then maps the finding against a profile of known-good activity. What fits the profile is treated as expected, and what doesn’t is flagged for a closer look.
What happens next depends on that outcome. A finding is sent to one of three places:
Archived, no action needed – Automated triage or an AWS Security Incident Response engineer confirms the activity is benign or expected. The finding is archived in GuardDuty, with no case and no customer contact.
A proactive case is opened – Triage can’t confirm the activity is benign. This is either Unconfirmed Activity (the service needs you to confirm whether it’s expected) or Inappropriate/Unintended Activity (confirmed activity that needs your action). A proactive case is opened, your incident response team is engaged, and the finding stays Current until it’s resolved.
Retained for your review, no case – Posture-related findings, such as overly permissive policies, configuration, or missing encryption, aren’t threats. By design, they stay Current without archiving and no case is created.
When a proactive case is opened, you respond to it in the AWS Management Console for AWS Security Incident Response under Cases, where you can communicate directly with the team, share context, and resolve or reopen the case. Timely responses also help the service learn your environment, which helps reduce false positives over time. For the full workflow, see Responding to an AWS generated case.
The preceding outcomes use GuardDuty terms, because it’s the primary source. Third-party findings ingested through Security Hub CSPM follow the same triage logic, but their disposition shows as a workflow-status change rather than archiving. The finding moves from NEW to NOTIFIED when triage begins, which removes it from the default Security Hub CSPM view. If triage clears it as benign, it moves to SUPPRESSED. Otherwise it stays visible for your review.
Because only benign findings are archived, it’s normal to see many findings in Current, and that isn’t a sign the service missed them. Across customers, less than 1 percent of ingested findings result in a customer-facing escalation. Most are handled automatically, without a case.
Credential exfiltration finding example
Suppose GuardDuty generates an UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWS finding: temporary credentials created on an Amazon Elastic Compute Cloud (Amazon EC2) instance were used from an IP address outside AWS. Triage cross-references the payload against what it knows about your environment.
Cleared – The external IP belongs to a corporate virtual private network (VPN) range that your workloads regularly call through, and the service has seen this pattern before. The finding is archived in GuardDuty.
Escalated – The IP is in a hosting-provider range with no prior association to your accounts, and the AWS Identity and Access Management (IAM) role has never made calls from outside AWS. The service creates a proactive case, notifies your incident response team, and an engineer investigates whether the credentials were compromised.
Same finding type, two outcomes. The difference is context, and context is what triage builds by observing your environment over time.
How triage sharpens over time
The service builds a profile of what’s normal in your environment. It learns the IP ranges and domains you trust, and the IAM principals and behaviors your workloads rely on. When your team routinely connects from a known VPN range, or a specific IAM role runs nightly batch jobs, the service recognizes those patterns and measures new findings against them. Early on, engineers investigate more findings by hand as they learn your environment. Within a few weeks, automated triage handles most of those decisions on its own.
Triage is dynamic. A finding treated as expected today can be re-evaluated tomorrow if the context changes, so the service can still catch a real threat that reuses a pattern it formerly treated as safe. You can shape the profile by submitting known-good activity, such as trusted IP ranges or authorized scanning tools, through an AWS Support case. For details, see Submit known-good activity.
Archiving versus suppression
It’s possible to conflate the two mechanisms, so it’s worth separating them:
Archiving is the primary mechanism. When automated triage or an engineer determines a finding is benign, the service archives it in GuardDuty. The finding then stays there for 90 days.
Suppression rules are less common and work differently. A suppression rule acts on future findings. When the service identifies a recurring pattern of expected activity, it might create a GuardDuty suppression rule that automatically archives matching findings so they don’t generate new alerts. Suppressed findings aren’t sent to your configured export, such as an Amazon Simple Storage Service (Amazon S3) bucket or SIEM. When the service creates a rule, your incident response team is notified, and you can view and manage it in the GuardDuty console under Suppression rules.
A healthy deployment typically shows many archived findings and few or no suppression rules. That’s expected, and it means the service is handling findings dynamically rather than relying on static filters.
How to see what triage is doing
Triage runs on its own, and the service gives you a few ways to confirm it’s working.
Proactive response dashboard
The Dashboard page in the AWS Security Incident Response console has a Proactive response section. It counts how many findings were ingested, triaged, investigated, and escalated over the timeframe you select, the last 7, 30, or 90 days.
The Overview leads with two figures. Noise reduction is the share of ingested findings that automated triage resolved without opening a case, so you can see for yourself how much volume never reached your team. Time saved estimates the analyst hours that automation returned to you, counted as one hour for each ingested finding.
Below that, Finding evaluations breaks those stages down:
Ingest – Threat findings collected from your detection sources
Triage – Findings evaluated automatically to decide whether the activity is expected
Investigation – Findings automated triage couldn’t confirm, passed to an AWS Security Incident Response engineer for a closer look
Escalation – Investigations raised as a case when a genuine risk was detected or the activity couldn’t be confirmed as expected
A flow diagram on the dashboard shows how those findings move from their sources through triage and investigation, with branches for the ones closed as false positives and the ones still in progress. For more, see Viewing proactive response metrics.
Monthly report
The monthly report is the periodic companion to the dashboard. AWS Security Incident Response emails it to your incident response team a week or two after each month closes. It opens with the accounts monitored, findings processed, and investigations, then lists each investigation and its status, the triage flows that show the checks run for each finding type, and the context the service has learned about your environment, such as the trusted networks it now recognizes as normal.
Archived findings in GuardDuty
For a quick confirmation outside either view, open Findings in the GuardDuty console and filter to see Archived. That list also includes findings archived by you or by suppression rules, so look for the threat findings AWS Security Incident Response archived after triage. Each one is a finding that the service cleared as benign so your team didn’t have to.
Conclusion
AWS Security Incident Response continuously evaluates your threat findings so your team can spend its time on confirmed threats rather than alert volume. Findings that are evaluated as benign are archived automatically, the ones that need a response become proactive cases, and posture issues stay in Current for your team to handle.
Cases show only a small part of that work. When I deliver AWS Security Incident Response to customers now, I walk them through the triage flow in Figure 1, the Proactive response dashboard, and their monthly report, so they can see how triage works end to end.
Gaining observability into AWS Lambda Durable Functions, a capability of AWS Lambda, can be challenging. A single workflow can span multiple invocations, queues, and downstream services, with no persistent host or centralized log file to inspect. With OpenTelemetry, you can close that gap by generating and correlating traces, metrics, and logs through an open specification. You can instrument once and export anywhere, which avoids vendor lock-in and establishes a baseline for operating serverless systems at scale.
With AWS Lambda Durable Functions, you can construct resilient workflows with multiple steps, which save their state and automatically recover from errors by replaying. A single durable execution can persist across several Lambda calls. It can continue after pauses, recover from errors, and restart from saved checkpoints. Although this model delivers fault tolerance, it introduces an observability challenge. Each invocation generates its own trace, fragmenting the end-to-end view of a single logical workflow.
This post introduces the OpenTelemetry plugin for the AWS Durable Execution SDK (aws-durable-execution-sdk-python-otel). With this plugin, you can generate deterministic trace IDs that unify all invocations of a single durable execution into one coherent distributed trace. In this post, you learn how to set up the plugin, see the traces it produces for the happy-path workflow, and apply foundational best practices.
The complete application code is available in our GitHub repository, so this post uses code snippets to illustrate the examples.
The problem: fragmented traces across invocations
Consider a document review workflow with a human approval gate:
This workflow runs across at least two Lambda invocations. The first invocation executes extract-text and summarize, then suspends at human-review with zero compute cost while waiting. Hours later, when the reviewer responds, Lambda invokes the function again. It replays the completed steps and executes publish.
The following diagram illustrates the difference between the default behavior and the plugin’s unified tracing. On the left side, two independent traces are generated: Trace A captures the first invocation (totaling 2.69 seconds), while Trace B captures the second invocation after the callback resumes (replaying and publishing in 0.37 seconds). These traces have different trace IDs and no correlation between them. On the right side, with the OTel plugin, all operations appear under a single deterministic trace ID. The human-review wait (6 hours and 8 minutes at zero compute cost) is represented as a continuous span connecting both invocations, giving operators a complete timeline from start to finish. You can compare the total wall-clock duration of 152 seconds against only 0.019 seconds of actual compute time billed.
Figure 1. Trace comparison of fragmented traces without the plugin (left) versus a single unified trace with the OTel plugin (right), showing how the Durable Execution SDK merges multiple Lambda invocations into one end-to-end trace.
The plugin achieves this through:
Capability
What it does
Deterministic trace IDs
Derives a stable trace ID from the AWS X-Ray header, so all invocations share one trace
Span-per-operation
Each step, wait, or wait_for_callback gets its own span with real timing
Continuation spans
Operations completing in a later invocation link back to the original span
Log correlation
Stamps traceId and spanId onto every log record automatically
Configurable sampling
Standard OpenTelemetry sampling to control trace volume
Figure 2. Amazon CloudWatch Application Signals Traces view. The durable execution appears as a single trace with OK status. The Duration column (152s) reflects the total wall-clock time including the human-review wait, while Response Time (0.019s) shows only the compute time.
Choose execution view to see all operations grouped under the Workflow span. Use this view when the full execution, including waits and retries, finishes within your tracing vendor’s span ingestion window. For example, if your vendor rejects spans that started more than 8 hours ago, use execution view only for workflows that reliably finish well under 8 hours. Choose invocation view if an execution might exceed your vendor’s ingestion window, or if you want to see progress as each function execution terminates. Operations appear under the invocation that ran them. A wait’s first segment appears under the invocation that started it, even while the wait is still pending. In both views, the Workflow span covers the full execution, so the vendor’s ingestion window still applies to it. If an execution runs longer than the window, your vendor might reject the Workflow span even in invocation view.
The plugin sends Workflow as one span when the execution succeeds or fail. It doesn’t send that span in pieces. The vendor can, however, accept earlier spans from the same trace.
Why do we recommend someone to use invocation view for long running ones? Suppose a workflow waits 10 hours and the vendor rejects spans that started more than 8 hours ago. In invocation view, the invocation that starts the wait can export the wait’s initial span before the wait finishes. The invocation that resumes the workflow can later export the wait’s completion span. Those short spans can be accepted even if the vendor rejects the final Workflow span.
Getting started
In the following walkthrough, you configure your Lambda durable function to trace requests end-to-end.
Prerequisites
Python 3.11 or later.
An existing Lambda durable function (or a new one you want to instrument).
Note: The examples in this post use AWS Serverless Application Model (AWS SAM) for brevity. You can achieve the same configuration using the AWS Command Line Interface (AWS CLI), AWS Cloud Development Kit (AWS CDK), Terraform, or AWS CloudFormation directly. Refer to the ADOT Lambda Layer ARNs page for the latest layer version and supported architectures. Pin the layer version in production deployments to avoid unexpected behavior from automatic version changes.
Step 3: Turn on X-Ray active tracing
The plugin uses the _X_AMZN_TRACE_ID environment variable to derive deterministic trace IDs. Turn on active tracing on your function:
MyDurableFunction:
Type: AWS::Serverless::Function
Properties:
Tracing: Active
Also verify your function’s execution role includes the AWSXRayDaemonWriteAccess managed policy (or equivalent xray:PutTraceSegments and xray:PutTelemetryRecords permissions).
Step 4: Add the OTel plugin to your handler
Import InvocationOtelPlugin and pass it to the plugins parameter of @durable_execution:
from aws_durable_execution_sdk_python import DurableContext, durable_execution
from aws_durable_execution_sdk_python.config import Duration
from aws_durable_execution_sdk_python_otel import create_otel_plugin_factory
@durable_execution(plugins=[create_otel_plugin_factory()])
def handler(event: dict, context: DurableContext) -> str:
data = context.step(lambda ctx: event["id"], name="fetch-data")
context.wait(Duration.from_seconds(5), name="cooldown")
return context.step(lambda ctx: f"processed {data}", name="process")
The plugin handles Tracer Provider setup, deterministic ID generation, and span lifecycle internally.
Testing and results
After you configure the plugin, deploy the function, invoke it, and confirm the unified trace appears in Amazon CloudWatch.
Testing the setup
Build and deploy your function:
sam build
sam deploy --guided
Then publish a function version (durable functions require a qualified ARN, not $LATEST):
Note: The send-durable-execution-callback-success command does not require --function-name. The callback ID already contains the reference to the execution.
What you see in Amazon CloudWatch Application Signals
After you invoke this function, open the Amazon CloudWatch console and choose Application Signals (APM), then Traces. You see a single unified trace containing:
One root span representing the entire durable execution.
Child spans for each named operation: extract-text, summarize, human-review, and publish.
Accurate timing: each span reflects the actual wall-clock time of the operation, not replay time.
Continuation links: if human-review completes in a different invocation (after the reviewer approves hours later), the span is linked back to the original trace.
Figure 3. Trace details view. The service map shows the flow: Client to Lambda Context (first invocation), then Lambda Function (second invocation after callback resume). Both invocations appear under a single trace ID with total duration of 4.55 sec.
Correlated logs
Because the plugin sets enrich_logger=True by default, your application logs are automatically stamped with traceId and spanId.
Figure 4. Expanded log entry in CloudWatch. Each log record includes traceId, spanId, and otelTraceSampled set to true, which lets you correlate logs across all invocations of the same execution.
You can combine the plugin’s log correlation with structured JSON logging to run powerful queries in Amazon CloudWatch Logs Insights:
This returns logs from all invocations in chronological order, correlated to their respective spans.
Best practices
When you run the OTel plugin in production, keep the following performance, operational, and cost considerations in mind.
Performance considerations
Cold start impact: The ADOT layer adds overhead to cold starts and memory consumption. Measure the impact for your workload using Lambda Power Tuning. For latency-sensitive functions, consider using provisioned concurrency to keep warm environments available.
Memory overhead: The plugin and ADOT layer consume approximately 40–60 MB of additional memory. Verify your function has sufficient memory allocated.
Replay efficiency: During replay, the plugin correctly identifies replayed operations and does not emit duplicate spans. Only new operations generate new spans.
Operational guidelines
Name your operations: Always pass the name parameter to context.step(), context.wait_for_callback(), and other durable operations. These names appear as span names in your traces, making them human-readable.
Use structured logging: Combine the plugin’s log correlation with structured JSON logging to unlock powerful Amazon CloudWatch Logs Insights queries.
Monitor trace gaps: If you see traces with missing spans, check that X-Ray active tracing is enabled and the ADOT layer is correctly configured.
Cost management
Amazon CloudWatch Application Signals pricing: You are charged per trace recorded and per trace scanned. At high volumes, configure sampling to control costs. See Amazon CloudWatch Application Signals pricing.
Log volume: With enrich_logger=True, every log record includes trace context fields, slightly increasing log volume. This overhead is typically negligible but worth noting for high-throughput functions.
Pricing
The plugin is open source (Apache 2.0). Costs come from AWS X-Ray traces recorded and the ADOT Lambda layer overhead. The layer increases both the memory consumption and the cold start duration of your function. Lambda pricing is based on GB-seconds, so the additional memory allocated (rounded up to the nearest MB) multiplied by the additional execution time per invocation determines the cost impact. Each durable execution produces one trace regardless of invocation count, so X-Ray cost scales with executions, not invocations. Measure the overhead for your workload using Lambda Power Tuning and see AWS X-Ray pricing for current rates.
Beyond this post
This post focused on a single, representative workflow (sequential steps plus a human-approval callback) to keep the walkthrough concrete. It is not an exhaustive tour of the SDK. The Durable Execution SDK offers many other primitives that also produce spans and are worth exploring: durable timers (context.wait), condition polling (context.wait_for_condition), durable Lambda-to-Lambda calls (context.invoke), parallel and fan-out execution (context.parallel, context.map), nested child contexts, and automatic retries (with_retry and StepConfig), where each attempt and each parallel branch surfaces as its own span. We also did not cover failure paths, such as step errors and failure callbacks, which is where unified tracing is often most valuable.
Likewise, the OTel plugin exposes configuration we did not exercise here: toggling log enrichment (InvocationOtelPlugin(OtelPluginConfig(enrich_logger=False))), supplying a custom Tracer Provider via OtelPluginConfig(tracer_provider=...), and controlling trace volume through standard OpenTelemetry sampling (OTEL_TRACES_SAMPLER). This walkthrough sampled 100% of traces. Consult the SDK documentation for the full surface area, or access the GitHub repository.
Sending Lambda durable functions traces to Observability partners. The OpenTelemetry plugin exports telemetry data to Amazon CloudWatch and can work with any observability solution that supports OpenTelemetry. Dash0 is an OpenTelemetry-native observability platform that supports Lambda durable functions without custom configuration. Dash0 worked with AWS to validate the OpenTelemetry plugin for the AWS Durable Execution SDK for JavaScript prior to launch, Dash0 coordinates logs and spans. In Dash0, spans for the durable execution, each invocation, and each durable operation appear alongside the function’s inputs and outputs and the payloads of its AWS SDK calls. To learn more, visit About AWS Lambda Monitoring.
Clean up
To avoid ongoing charges, delete the resources created in this walkthrough:
sam delete --stack-name <your-stack-name>
This removes the Lambda function, AWS Identity and Access Management (IAM) roles, and any associated resources created by the SAM template.
If you manually added the ADOT Lambda layer or X-Ray tracing policies outside of your SAM template, remove those separately using the AWS CLI or console.
Trace data retained in X-Ray does not incur storage charges and expires automatically after 30 days.
Conclusion
In this post, we showed how to unify fragmented traces across multiple Lambda invocations using the OpenTelemetry plugin for the Durable Execution SDK. To explore the full SDK surface area, including parallel execution, durable timers, and failure-path tracing, see the AWS Durable Execution SDK Developer Guide. For more observability patterns, visit the AWS Observability Best Practices guide.
Moonfrog Labs uses Amazon Redshift to analyze mobile game telemetry. Each session, purchase, and player drop-off generates events that product and analytics teams use to understand game performance. Faster loading and querying help those teams work with fresher data.
Moonfrog runs a single production analytics cluster with roughly 148 TB in Amazon Redshift Managed Storage (RMS) and about 4,000 warehouse tables. It also queries roughly 1,000 external data lake tables. The warehouse supports telemetry ingestion, revenue reporting, marketing attribution, and self-service dashboards for product, data science, analytics, and support teams.
In this post, we show how Moonfrog migrated its production analytics warehouse from Amazon Redshift RA3 to RG instances using elastic resize. We explain how the team selected capacity for growing analytics demand and more frequent loading, verified warehouse and data lake access, and assessed performance and costs after migration.
The challenge
Moonfrog’s RA3 cluster ran reliably, with no stability issues. Its constraint was compute headroom as analytics demand grew. Ingestion volume was steady before migration. Growth came from analytical queries and data lake scans. The team already planned to expand from five RA3 nodes to six or seven nodes and wanted capacity to load warehouse data more frequently.
The five-node ra3.4xlarge cluster averaged about 54% CPU utilization. In approximately 98% of hours, CPU peaked at or above 90%. Other indicators showed demand increasing:
SELECT queries per day increased 31% from January to July.
Mean workload management (WLM) queue wait for highest-priority queries rose from 505 milliseconds in May to 940.7 milliseconds in July.
Concurrency scaling usage nearly doubled over the same period, from 4,453 to 8,516 seconds per day.
A COPY operation averaged 16.8 seconds on RA3. That duration constrained how often the stats pipeline could load. The team evaluated RG as a way to support growing analytics demand and make more frequent loads practical.
Moonfrog also queried roughly 1,000 external tables in Amazon Simple Storage Service (Amazon S3). Data scanned through Redshift Spectrum increased 33%, from 84.9 TB in March to 112.5 TB in June. The separate Spectrum scanning charge added to the cost of expanding RA3 compute.
Moonfrog used WLM query monitoring rules to stop scans larger than one terabyte. These rules controlled scan spend under the RA3 configuration.
The one-year no-upfront reserved node commitment for ra3.4xlarge expired in July 2026. Renewal gave Moonfrog an opportunity to re-evaluate its compute commitment and determine whether switching to RG would provide additional headroom for its growing workload needs.
Solution overview
Amazon Redshift RG instances use AWS Graviton processors and an integrated data lake query engine. AWS publishes benchmarks of up to 2.2 times faster warehouse workloads and up to 2.4 times faster Apache Iceberg workloads, at 30% lower price per vCPU than RA3. These benchmarks are separate from Moonfrog’s production results. RG runs Apache Iceberg and Apache Parquet scans on cluster nodes, removing the separate per-terabyte Spectrum charge for these scans. Elastic resize supports changing the node family and capacity without a customer-managed export and reload.
Moonfrog retained its ingestion and analytics architecture at cutover. No service was added or removed, and applications continued to use the same warehouse.
The following diagram illustrates the architecture.
Figure 1: The ingestion pipeline writes columnar files to Amazon S3. COPY loads warehouse tables, and the integrated data lake engine on RG queries external tables in place. Conversational analytics is a planned use of the additional headroom
The architecture uses the following AWS services:
Amazon Redshift provides the analytics warehouse and integrated data lake engine.
Amazon S3 stores event files, load staging data, and external data lake tables.
Moonfrog established a baseline, used elastic resize to change the node family, and verified warehouse and data lake access. It then evaluated the early results before selecting its final configuration.
Step 1: Establish a baseline
Before the change, the team captured Amazon CloudWatch metrics for CPU utilization, WLM queue wait by priority, query duration by type, and queries per day. COPY loads and SELECT queries were measured separately. Billing records provided reserved compute, Spectrum scanning, and concurrency scaling costs so the comparison covered each billing line affected by the move.
Step 2: Validate the target configuration and use elastic resize
AWS recommends testing the target RG configuration in a non-production environment with representative workloads before migrating production. That testing is intended to measure benefits, identify issues, and validate the target size before the production migration.
On 26 July, Moonfrog used elastic resize to move from five ra3.4xlarge nodes to eight rg.4xlarge nodes, temporarily providing extra capacity to reduce migration risk. It did not export or reload the 148 TB warehouse. Schemas, ETL jobs, application SQL, drivers, connection strings, and BI tools continued to work.
Amazon CloudWatch recorded one five-minute interval in which the cluster reported unhealthy. Database connections recovered immediately afterward. This sampling interval describes the observed impact. It does not establish an exact five-minute outage duration.
AWS guidance describes elastic resize as a short operation, typically about 10 to 15 minutes. After an RA3-to-RG node-type change, data hydration brings frequently accessed data from managed storage into the new nodes’ local cache. This cache warming should be considered when interpreting early performance measurements.
Step 3: Verify warehouse and data lake access
Moonfrog verified that warehouse loads and external queries continued after the resize. External schemas and tables remained in use, with AWS Glue Data Catalog providing their metadata.
Moonfrog confirmed that per-terabyte S3 scanning charges were eliminated for its RG queries in the subsequent billing records. Those queries used provisioned cluster capacity, which remained billable.
Step 4: Review workload management rules
Moonfrog’s Auto WLM configuration included separate queues for administrators, analysts, ETL, loading, and visualization, along with short query acceleration. These queues carried across the migration. The team reviewed query monitoring rules because data lake scans now consumed RG cluster capacity.
The review accounted for data lake scans sharing compute with warehouse workloads. Rules that previously controlled scan spend could still protect these shared resources.
Results and key benefits
The following four CloudWatch charts cover 1 May to 25 October 2026. Each marks the 26 July resize and shades the 26 July–3 August period when the cluster was reduced from eight to seven to six RG nodes. Query duration and WLM wait charts show seven-day rolling means. Query counts include COPY, SELECT, INSERT, utility, and other operations.
Stage 1: Evaluate RG after cutover
The first evaluation focused on workload continuity and query runtime. Warehouse loads and data lake queries continued, and the applications used the same schemas, SQL, drivers, and connection strings. Queries on the initial RG configuration were completing within expected runtimes. Moonfrog then reduced the node count in stages to assess whether each reduction affected query runtime.
The cleanest comparison of COPY duration is 27–31 July, when load volume remained unchanged. Mean duration fell from 16.8 seconds on RA3 to 3.6 seconds on RG, about 79% shorter. This window falls within the 26 July–3 August right-sizing period, before the final six-node configuration was established.
Select six nodes
Moonfrog reduced the cluster from eight to seven and then six RG nodes within eight days. The team retained the additional node relative to its five-node RA3 baseline to support growing analytical demand and more frequent loading. It had already planned to expand RA3 to six or seven nodes.
The move from five RA3 nodes to six RG nodes increased node count by 20%. Published node specifications list 12 vCPUs per ra3.4xlarge and 16 per rg.4xlarge, so provisioned vCPUs increased from 60 to 96, or 60%. The results reflect the change in both node family and capacity.
Stage 2: Sustain performance as workloads grow
After validating the available headroom on the six-node configuration, Moonfrog increased loading frequency on 24 August. The cluster now executes more than 70,000 COPY operations a day, about 4.3 times the RA3 baseline. These loads use smaller, more frequent batches, so later COPY duration also reflects the changed loading pattern. Figure 2 shows the early duration improvement and subsequent performance as the workload changed.
In late August, after the 24 August increase in loading frequency, Moonfrog purchased a one-year no-upfront reservation for the six-node RG configuration. The purchase followed its evaluation of RG with production traffic and committed capacity for anticipated workload growth.
Figure 2: Mean COPY and SELECT duration. The early COPY comparison uses unchanged volume. Later means also reflect smaller batches after 24 August
More daily queries with compute headroom
Daily queries across all types increased from around 49,122 on RA3 to 83,603 in August, 125,350 in September, and 125,374 during 1–25 October. From September onward, this was more than 2.5 times the RA3 baseline. COPY accounts for much of that increase, so total query growth should be read alongside the query mix in Figure 3.
Figure 3: Successful daily queries by type. COPY frequency increased on 24 August, after the migration and right-sizing period
Concurrency scaling remained enabled to absorb peak bursts alongside the six reserved nodes. Average daily usage was 14–29% below the RA3 baseline in August, September, and October, even as total query volume grew. Usage increased from September to October as demand rose.
Average CPU utilization fell from about 54% on RA3 to 35–39% from September onward, despite the higher query count. Figure 4 distinguishes daily average CPU from the typical peak, defined as the daily mean of each hour’s maximum CPU reading.
Figure 4: CPU utilization before and after the resize. The typical peak is an average of hourly maximum readings, not the single daily maximum
Queue waits as demand grows
Queue waits fell after migration and rose from their August lows as traffic increased in October. During 1–25 October, highest-priority waits averaged 561 milliseconds versus a July RA3 baseline of 940.7 milliseconds, and high-priority waits averaged 193 milliseconds versus 294 milliseconds. Normal-priority waits were about 11 milliseconds, above their July baseline of about 3.6 milliseconds. Figure 5 uses a separate vertical scale for each priority.
Figure 5: Seven-day rolling mean WLM queue wait by priority. Dashed lines mark July RA3 baselines. Each panel has its own scale
Integrated data lake queries and billing
External data lake queries continued after migration. Moonfrog confirmed that the separate Spectrum scanning charge remained exactly $0 from 27 July through the reported months:
The Amazon Redshift system views showed that external queries continued. A recent three-day sample recorded roughly 200,000 external queries against Amazon S3, including Parquet scans. External schemas and tables remained in use.
Billing records showed no separate per-terabyte scanning charge. External scans use provisioned RG capacity, which remains billable. Amazon S3 storage and other charges are outside this comparison.
Cost per query
Moonfrog chose additional capacity for growth, and monthly spend across reserved compute, Spectrum scanning, and concurrency scaling increased approximately 4–6%. On a consistent 30-day basis, cost per 1,000 total queries fell approximately 59% in September and 58% in October. Costs per 1,000 SELECT queries fell 38–50% across August through October.
Metric
RA3 × 5 Before
RG × 6 August
RG × 6 September
RG × 6 Oct 1–25
Queries per day All types
49,122
83,603
125,350
125,374
Cost per 1,000 total queries
$5.60
$3.45 −38%
$2.28 −59%
$2.33 −58%
Reported cost per 1,000 SELECT
$45.60
$22.73 −50%
$25.19 −45%
$28.34 −38%
Cost per 1,000 total queries is calculated by dividing the combined 30-day spend for reserved compute, Spectrum scanning, and concurrency scaling by 30 times the average daily query count, then multiplying by 1,000. These are aggregate cost measures, not the execution cost of an individual query.
How the team plans to use the headroom
The larger configuration created room to test additional analytical use cases. Earlier measurements showed mean short-query duration falling from about 2.8 seconds to 1.8 seconds. That observation applies to the measured short-query workload and does not establish a response-time guarantee for every analytical question.
Moonfrog plans to evaluate conversational analytics using large language model (LLM) agents. Such agents may execute several queries to answer one question, so query latency is one part of the end-to-end response time. The additional compute headroom gives the team room to test these workloads alongside existing analytics.
Lessons learned
Use a reserved node renewal as an opportunity to review capacity and architecture for your growing workload needs. Moonfrog evaluated RG before making another one-year commitment.
Size the cluster for expected workload growth and assess results against the capacity provisioned. Moonfrog added a sixth node for headroom. Interpret total query counts alongside the query mix, because smaller, more frequent COPY batches increase the number of operations.
Include concurrency scaling in capacity planning. In this deployment it continued to absorb peak bursts alongside the reserved nodes, so evaluate its contribution when assessing warehouse throughput.
Separate immediate migration results from subsequent workload changes. The unchanged-volume COPY comparison captures the first days after cutover. Later results include the loading cadence change and rising demand. Measure dashboard latency and query abandonment separately to quantify the effect on users.
Next steps
Moonfrog has already increased warehouse loading frequency. The team plans to measure dashboard load times and query abandonment to assess how greater freshness and shorter query durations affect the experience of product and analytics teams.
Moonfrog is considering Apache Iceberg for data lake tables currently stored as Parquet files. The table format would add capabilities such as schema evolution and time travel. The team will evaluate these changes alongside performance and operating requirements.
The team also plans to evaluate broader natural language access. Governance must define which teams can access each table and how exploratory queries share cluster resources. End-to-end agent response time will need separate measurement.
Conclusion
Moonfrog migrated its 148 TB production Amazon Redshift warehouse from five RA3 nodes to RG using elastic resize, then settled on six nodes after eight days of measured right-sizing. RA3 had run reliably. The change addressed growing analytics demand and the need for more frequent warehouse loads. COPY duration fell from 16.8 seconds to 3.6 seconds at unchanged volume immediately after cutover.
With six RG nodes, Moonfrog handled more than 125,000 daily queries across all types from September onward, over 2.5 times the RA3 baseline. Average CPU utilization was 35–39%. More frequent COPY batches contributed to the change in query mix. External queries continued with no separate Spectrum scanning charge, and concurrency scaling provided burst capacity alongside the reserved nodes.
To evaluate RG for your warehouse, review Amazon Redshift pricing, the elastic resize documentation, and the RA3 to RG migration best practices. Establish a baseline and test representative workloads in a non-production environment first. Validate warehouse and data lake access, then compare total spend and cost per unit of work before committing to reserved capacity.
Amazon Elastic Compute Cloud (Amazon EC2) accelerated computing instances run some of the most demanding workloads customers operate, from large model training and distributed fine-tuning to high-throughput, live inference. These customers seek high availability and performance to make sure their training and inference run efficiently. To meet their performance goals, customers require visibility into the efficiency and performance of each accelerated computing chip in their fleet.
For example, central infrastructure or machine learning teams often operate accelerated computing capacity for many application teams. These infrastructure teams need a clear view of utilization and health across every instance in their fleet even if they don’t develop the applications running on those instances. They are often responsible for how efficiently that capacity is used and for hardware health, while application teams own the workload. Customers asked us to provide foundational telemetry for their accelerated computing efficiency and status that doesn’t require setup within the instance and complements their in-guest tooling.
Amazon EC2 now reports one-minute graphics processing unit (GPU) metrics through Detailed Monitoring and surfaces recoverable conditions with performance status checks. One-minute GPU metrics in Amazon EC2 Detailed Monitoring report per-GPU utilization and thermal data to Amazon CloudWatch, so you can identify underused capacity and tune workloads for cost and throughput. Performance status checks report recoverable hardware conditions, such as a GPU memory error, to help you manage GPU performance.
Feature overviews
Amazon EC2 reports GPU metrics and performance status checks without an in-guest agent and without using instance compute. These capabilities are available on supported NVIDIA GPU-based accelerated computing instance types. For the metrics supported on each instance family, see the Amazon EC2 Detailed Monitoring documentation.
One-minute accelerated computing metrics extend EC2 Detailed Monitoring and are published to CloudWatch as OpenTelemetry Metrics or CloudWatch Metrics. The metric name you add to a category determines which one CloudWatch publishes: include GPUUtilization for a CloudWatch Metric, instance.gpu.utilization for an OpenTelemetry Metric, or both names to publish both. Amazon EC2 publishes each metric to CloudWatch at two levels: one series for the instance, identified by InstanceId, and one series for each GPU, identified by InstanceId and GpuId. GpuId is the GPU UUID, which you can match to a device by running nvidia-smi -L on the instance.
Performance status checks add a fifth status check to the existing Amazon EC2 product check suite of system, instance, attached EBS, and application status checks. The check reports recoverable hardware issues that affect accelerated computing performance while the instance might remain running and reachable. It surfaces through the EC2 console, through DescribeInstanceStatus, and in CloudWatch metrics.
Evaluating accelerated computing utilization and performance with EC2 Detailed Monitoring
Amazon EC2 Detailed Monitoring reports per-GPU measurements, including compute activity, memory use, temperature, and data movement.
GPU utilization metrics report different aspects of GPU use. GPUPowerUtilization is available by default and reports active power use. Power utilization scales with the depth of work the GPU performs. Compare it with more granular utilization metrics to see how efficiently your workload uses the GPUs. GPU utilization shows the percentage of time the GPU was running work. Because a busy GPU might use only a fraction of its streaming multiprocessors (SMs), compare it with SM utilization to see how much of the compute capacity the workload uses. Memory utilization shows how much of the GPU’s memory capacity is in use, helping you assess memory headroom. Context accumulated time is a running total of the time a process has held the GPU open, whether or not it ran work. Use the CloudWatch metric math expression RATE(m1)/1000000, where m1 is GPUContextAccumulatedTime, to compare context activity with GPU utilization. A result close to 1 with low GPU utilization indicates that a GPU context is held open but idle.
GPU temperature is reported as a percentage of the GPU’s thermal throttle limit, and memory temperature as a percentage of the memory’s critical temperature. Both metrics can report values above 100 percent when a GPU or its memory runs above the limit. A GPU reduces its clocks when it reaches its throttle limit, so a value at or above 100 percent can explain a drop in throughput. You can correlate these measurements with GPU and interconnect utilization metrics to understand workload performance.
Interconnect utilization metrics show how much of the available bandwidth a workload uses for data movement. Each value reports the busier direction, either send or receive. NVLink utilization measures GPU-to-GPU traffic, such as collective operations in distributed training. It reports all of the GPU’s links together. PCIe utilization measures traffic between the host and the GPU.
Getting started with EC2 Detailed Monitoring
Amazon EC2 Detailed Monitoring publishes instance metrics to Amazon CloudWatch at one-minute intervals without running an agent in the guest operating system. You can publish these as OpenTelemetry Metrics or CloudWatch Metrics.
To get started, create a metric category, an Amazon EC2 resource containing the metrics you want to collect. Next, associate the category with one or more instances. For an existing instance, provide the category ID when you enable Detailed Monitoring with the MonitorInstances API. For a new instance, provide the category ID in the Monitoring object when you call RunInstances or configure a launch template.
The following example creates a metric category for GPU utilization, SM utilization, and memory utilization.
Categories apply to many instances at once, unlike per-instance metric settings. Define the metric set once and associate it wherever it applies. Every associated instance then reports the same set of metrics. Changing a category updates the metric set for every associated instance. The change is eventually consistent across running instances. Add the category to a launch template to apply the same metrics to new instances. This gives you one metric definition per workload type instead of one configuration per host. Metrics apply under standard Amazon CloudWatch pricing.
Managing accelerated computing availability with performance status checks
Accelerated computing hardware can experience non-terminal issues that affect performance and can be resolved with a GPU reset or an instance reboot. For example, when a GPU encounters an uncorrectable memory error, it schedules a repair that remaps the affected row to a spare. The repair takes effect the next time the GPU is reset or the instance is rebooted.
Amazon EC2 performance status checks surface these recoverable hardware conditions. For example, when Amazon EC2 detects a pending GPU memory row remap, the instance’s performance status check reports an impaired status and identifies reboot as the recommended remediation.
You can view performance status checks on the Amazon EC2 console or through DescribeInstanceStatus. Amazon EC2 also publishes the StatusCheckFailed_Performance metric to CloudWatch. A failed performance status check also increments the combined StatusCheckFailed metric. The following example uses the EC2 DescribeInstanceStatus API:
The following response shows the system, instance, attached EBS, and configured application status checks passing while the performance status check is impaired:
Amazon EC2 sends a scheduled event for the instance if the condition requires further action after a reboot.
To act on these conditions across your accelerated computing instances, create a CloudWatch alarm on StatusCheckFailed_Performance.
The alarm on StatusCheckFailed_Performance fires for an instance in a training cluster.
You confirm the condition and the recommended action with DescribeInstanceStatus, which returns a status of impaired and a remediation of reboot.
You checkpoint the job if applicable, then drain the node and reboot the instance at a planned point. On Amazon Elastic Kubernetes Service (Amazon EKS), cordon and drain the node. In Slurm, set the node to DRAIN.
After the reboot completes, the performance status check returns to ok.
The following command creates that alarm for a single instance.
A CloudWatch Metrics Insights alarm evaluates a single query across all matching instances, so one alarm can cover a large fleet. To drive automation without an alarm, poll the DescribeInstanceStatus API.
Rebooting the instance is the recommended remediation. Alternatively, you can reset the affected GPU while keeping the other GPUs running. On the affected instance, run nvidia-smi -q -d ROW_REMAPPER and find the GPU that reports Pending: Yes. Stop all processes using that GPU, then use root permissions to run nvidia-smi -r -i <GPU_UUID>. The performance status check returns to ok shortly after the reset completes.
Bringing it all together
Accelerated computing metrics and performance status checks address complementary questions. Detailed Monitoring metrics help you find idle or underused capacity and tune workloads for cost and throughput. Performance status checks surface recoverable conditions and recommend remediation. Together, these EC2 signals report utilization and status across the capacity infrastructure teams manage, while in-guest tooling provides workload-specific analysis.
For example, a central infrastructure team monitors how efficiently workloads use the accelerated computing instances it manages for several application teams. It finds that one team’s GPUs report lower GPU utilization and power utilization than comparable workloads run by other teams. The infrastructure team shares the finding and relevant workload-tuning practices with the application team. After the application team updates that workload, the infrastructure team uses the same CloudWatch metrics to evaluate the change. The infrastructure team also monitors StatusCheckFailed_Performance across the fleet. When a check reports an impaired status and recommends a reboot, the orchestrator saves the active job, stops placing new work on the instance, and reboots it. After the check returns to ok, the orchestrator makes the instance available for new jobs. Together, these workflows help the team improve GPU utilization, protect job progress, and return affected capacity to service.
Amazon EC2 Detailed Monitoring reports accelerated computing metrics once per minute at the instance and GPU levels. Performance status checks report recoverable conditions at the instance level. Infrastructure teams can use these EC2 signals to monitor utilization and status across the capacity they manage. In-guest tools add process, container, Kubernetes pod, and sub-minute detail.
Amazon EC2 Detailed Monitoring reports metrics for your instances, including GPU utilization metrics reported per GPU. Performance status checks tell you when accelerated computing hardware needs attention. These capabilities help you evaluate utilization and manage the efficiency of your accelerated computing fleets. To learn more, see the Amazon EC2 Detailed Monitoring documentation and the EC2 status checks documentation.
Note (November 2026): This post covers both MCP servers because the Redshift MCP Server has Redshift-specific settings, such as read-only by default and a cap on result rows, that the AWS MCP Server doesn’t have yet. We’ll update this post when the AWS MCP Server reaches parity.
Guardrails and cost control matter more as AI agents handle an increasing share of the queries in your analytics environments. Asked “Why did revenue drop in the West region last weekend?”, an agent finds the tables, writes and runs the SQL on Amazon Redshift, and follows up. This is agentic analytics, on your data warehouse and lakehouse.
Excessive agency: The agent can do too much. An agent acts on what a model decides. With more tools or permissions than its task needs, a misread request or an instruction hidden in a support ticket can become a real action, such as exporting customer records.
Unbounded consumption: The agent can spend too much. A retry loop can rerun a heavy query all night. A query can return millions of rows that the agent then sends to the model as input tokens. Finally, one SQL query that runs Amazon Bedrock model inference through Redshift ML invokes the model once for every row it processes.
Redshift includes the controls for both at no additional charge: per-agent roles, row-level and column-level security, dynamic data masking, read-only tools, workload management, and usage limits. You pay for queries from agents as you do for queries from any other client: for the compute and storage they use (Amazon Redshift pricing). Your agent’s model provider bills its model tokens, for example at Amazon Bedrock pricing when the agent uses a model in Amazon Bedrock. You pay for the Amazon Bedrock, Amazon Bedrock AgentCore, and monitoring controls in this post at their own rates.
In this post, we show you how to add guardrails and cost controls to agentic analytics on Redshift, using one model: six guardrails, three enforcement layers, and one cost envelope.
The layered guardrail model
Each request passes through the agent layer, the access layer, and the data layer before it reaches your data warehouse or lakehouse, and the cost envelope limits spend across them.
Figure 1: The layered guardrail model. The lower the layer, the less a prompt can change it
Each guardrail type controls one thing and maps to an OWASP risk. Each layer is who enforces it:
Agent layer: Your agent or application, its framework, and Amazon Bedrock.
Access layer: The tools between the agent and your data, such as MCP servers and AgentCore Gateway (a capability of Amazon Bedrock AgentCore), and the IAM policies on the identities those tools use.
Data layer: Amazon Redshift and, for lakehouse tables, AWS Lake Formation.
The following table lists the six guardrail types. Each row names the guardrail type, the main OWASP risk it reduces, and the layer and controls that enforce it.
The agent layer is the first filter, but it cannot be the only one. Most Amazon Bedrock Guardrails checks are model-based classifiers, some with a strength that you tune, so they catch most problems but not all. The guardrails that protect your data in Redshift therefore sit in the access and data layers, which apply fixed rules to the caller’s identity. You need both. AWS Identity and Access Management (IAM) policies decide which Redshift workgroups and APIs it can call, and Redshift and Lake Formation permissions decide what its SQL can touch. Fixed rules give the same answer whichever agent wrote the request, so a prompt injection that gets past the agent layer still cannot reach data that the agent’s identity is not granted.
Agentic analytics patterns on Amazon Redshift
Conversational analytics, the most common pattern, answers business questions from your data in self-service and managed delivery models. The others enrich data, take actions, or help administrators run the warehouse itself.
Scoped writes. Human approval for consequential ones
Operate
Administrators review and tune the warehouse with Kiro, Redshift skills, and the MCP Server review_cluster tool
Read-only. Changes ship as reviewed code
Every pattern needs the same two scopes for least privilege: IAM permissions that limit which workgroups and APIs an identity can call, and database permissions that limit what its SQL can read or change. What differs is which identity reaches Redshift:
Self-service (AI assistants with the Redshift MCP Server or AWS MCP Server). The AI assistant acts on behalf of the user, with the AWS profile in its MCP configuration. If your roles have different scopes, set up a profile for each and point the server at the narrowest one for the task, such as a read-only analyst role for sales questions. The setup steps are in access-layer/redshift-mcp-server and access-layer/aws-mcp-server in the aws-samples repository.
Redshift MCP Server: A user whose profile assumes a DataPlatformAdmin role runs every agent query as IAMR:DataPlatformAdmin, with that role’s grants. The server is read-only by default, and the agent can’t switch profiles. To use a broader profile, change it yourself in the MCP configuration.
AWS MCP Server: The agent can switch on each call among the profiles listed in the MCP Proxy for AWS configuration. List only the profiles you want it to use, and put the read-only one first so it’s the default. On provisioned clusters, a script can also choose a database user if the role allows redshift:GetClusterCredentials, so leave that permission out.
Both: The MCP configuration only controls the MCP tools. An agent that can run shell commands can use any profile on the machine, so the IAM roles and database grants are the real boundary.
SageMaker Data Agent: The agent runs SQL itself, including cells it fixes, as the signed-in person. Without trusted identity propagation, Redshift sees one IAMR:user-<id>@<project> database user per project member. With it, Redshift sees the person’s AWS IAM Identity Center user, so row-level security, masking, and grants apply to each person.
Custom agents, for example on Amazon Bedrock AgentCore. The database user comes from the role that calls the Data API: the AgentCore Runtime execution role, or the AWS Lambda function’s role behind AgentCore Gateway, such as IAMR:agent-support. If the agent acts for a specific person, use trusted identity propagation. The agent’s tool exchanges the person’s sign-in token through AWS IAM Identity Center, optionally federated with your external identity provider, and calls the Data API as that person. Redshift then applies their grants (writes included), row-level security, and masking, plus Lake Formation permissions if you enable that integration.
Managed (Amazon Bedrock Knowledge Bases). The knowledge base runs the SQL it generates as one identity. On Serverless workgroups and provisioned clusters, that is its service role with IAM or the user in an AWS Secrets Manager secret. Provisioned clusters also accept a named database user (authentication methods). Knowledge Bases can’t carry the actual user with trusted identity propagation, so when one identity serves many end users, row-level security can’t tell them apart. With one shared knowledge base, a West region manager and an East region manager query as the same database user, so both get every row that user can read. Instead, create one knowledge base or agent for each audience, such as one per sales region, and scope its role, grants, and row-level security policy to that audience.
Figure 2: Who Redshift sees on each access path
Decide how much agency to grant
Grant agency, what an agent can do, on two planes. The data plane is SQL on Redshift managed storage or Apache Iceberg tables, governed by Redshift and AWS Lake Formation permissions. The control plane is API calls that create, resize, manage, or delete infrastructure, governed only by IAM. The AWS Agentic AI Security Scoping Matrix bounds agency with permissions and autonomy with oversight. Following it, start read-only (Scope 1), then add scoped writes with a human in the loop for consequential ones (Scope 2). Keep agents off the control plane, and widen autonomy (Scopes 3 and 4) only within those boundaries.
Agent layer: Guide the request
The agent layer, mostly outside Redshift, is the first filter. Its controls run in your agent, Amazon Bedrock, and Amazon Bedrock AgentCore, so you set them up and pay for them there. These include the step, retry, and token limits that cap the agent’s own model spend.
Input. Bedrock Guardrails filters prompt injection attempts and denied topics, and ApplyGuardrail works with your choice of model.
Business context.Business context and skill assets in the AWS Glue Data Catalog tell agents which tables and joins to use. They are in preview in the US East (N. Virginia), US East (Ohio), US West (Oregon), and Europe (Ireland) Regions.
Agent configuration and oversight. Limit an agent’s tools before it runs. In Kiro, for example, the MCP configuration lists the tools to approve automatically (autoApprove) and the tools to hide from the agent (disabledTools). Add project instructions, and set step and retry limits in agent frameworks.
Access layer: Limit what the agent can call
The access layer decides which tools an agent can call and what each call can do. Redshift enforces its guardrails the same way for every prompt.
Data plane: A narrow tool surface on every path
Figure 3 shows the tool guardrail each connection path needs, plus least-privilege IAM and database permissions. Each path has a worked example in the access-layer folder of the aws-samples repository, with setup, verification, and clean-up steps.
Figure 3: Access paths and their guardrails
Agents with shell access can bypass an MCP server with the AWS CLI, so scope IAM on every path. To allow only the AWS MCP Server path, see AWS MCP Server only, later in this section.
Discover lets the agent list workgroups. It uses "Resource": "*" because ListWorkgroups doesn’t support resource-level permissions, so it can’t limit where SQL runs.
RunSqlOnOneWorkgroup lets the agent sign in and run SQL on one workgroup only. This is the statement that limits where SQL runs. It includes redshift-data:BatchExecuteStatement, which the Redshift MCP Server needs before it can run writes or named transactions. Without that action, the server stays read-only by refusing writes itself. With it, writes still need ACCESS_MODE=read-write in the MCP configuration, which is off by default, and the agent’s database grants still limit what a write can change.
ReadOwnStatements lets the agent check status and read results only for statements it ran itself.
Custom MCP server: Tools that run fixed SQL. Expose only tools that each run one fixed, parameterized statement against a curated view, under the server’s own IAM role with SELECT on that view only. Have each tool set a fixed StatementName and SQL comment, so AWS CloudTrail and query history name the tool. In the sample server (access-layer/custom-mcp-server/sales_metrics_mcp.py), the agent supplies only a sales region, which the server checks against an allowed list, so prompt injection can at most make the tool query a different allowed region.
AWS MCP Server: Scope the credentials, not the script. Its aws___run_script sends SQL through the Data API as the caller’s mapped database user, so an administrator profile means administrator access. Four guardrails close that gap:
A dedicated agent profile in the MCP Proxy for AWS, for an agent role with read-only grants.
No way to switch database users. Allow redshift-serverless:GetCredentials or redshift:GetClusterCredentialsWithIAM, not redshift:GetClusterCredentials or Secrets Manager secrets, which let a caller choose another user.
Agent workgroups only. A service control policy in AWS Organizations denies Data API SQL through AWS managed MCP servers unless the workgroup is tagged agent-access=true. The same statement also works in an IAM policy or permissions boundary. SCPs skip the management account, so test on a sandbox OU first:
AWS MCP Server only. To stop the agent’s shell from going around the server, deny redshift-data:* on the agent role unless the call comes through it. Also deny direct driver sign-in when aws:ViaAWSService is false: redshift-serverless:GetCredentials, redshift:GetClusterCredentialsWithIAM and redshift:GetClusterCredentials, plus GetIdentityCenterAuthToken when you use trusted identity propagation (access-layer/aws-mcp-server/deny-data-api-outside-aws-mcp.json). Attach it to agent roles or permission sets, not as an SCP. IAM can’t tell the local Redshift MCP Server from the AWS CLI, so on that path read-only database grants are the boundary:
Scope every write, and keep a human in the loop where it matters
Give an agent one scoped tool per action, never a generic write tool. A write can run on its own when its tool limits it to one validated, low-impact action, so approvals don’t slow routine work. Consequential, irreversible, or above-threshold writes need a human in the loop:
Mechanism
How it works
Can the agent bypass it?
Approve as data (recommended for data writes)
The tool records a request. A people-only identity approves it
No: Redshift enforces it
Approve in the agent
The framework asks a person first
Depends on the framework
Approve as code review
Schema and infrastructure changes ship as reviewed code
No: your pipeline enforces it
In the Act pattern, an agent writes to Redshift as part of a workflow, such as issuing a refund. Figure 4 shows how it combines both kinds of write:
The agent’s only write tool, refund_order, runs as an identity that can only EXECUTE one procedure.
The SECURITY DEFINER procedure checks the order and caps the amount at the remaining refundable amount and $500, locking support.refunds against concurrent over-refunds. A failed check writes nothing and returns an error the agent can report.
Refunds up to $100 are approved. Larger ones wait for the refund_approvers role, through a second procedure that rejects self-approval.
A payment process pays approved refunds only.
Figure 4: A scoped action tool, with human approval above a threshold
The procedures and grants are in act-refund/refund_procedures.sql. Expose refund_order as its own tool, under an identity separate from the agent’s read path, so the read identity has no write privileges. Scheduled writes that no agent starts, such as a nightly Enrich job that labels tickets with Redshift ML, need a different control. Review the job’s SQL once before you deploy it, then run it under its own identity that no agent can use.
Control plane: Keep infrastructure changes out of agents’ reach
Control plane calls skip database grants, so IAM is the only gate, and an AI assistant’s credentials often reach its shell and the AWS CLI too.
Give every AI assistant a scoped identity. Run Kiro and other AI assistants, and their MCP servers, under an agent-role AWS profile with read-only control plane actions and a permissions boundary. Don’t allow redshift:Get*, which includes GetClusterCredentials. Share the profile through one AWS IAM Identity Center permission set (access-layer/shared/aws-config-example.ini). Role chaining caps sessions at 1 hour.
Deny infrastructure changes through managed MCP servers. With the aws:ViaAWSMCPServicecondition key, a service control policy can deny create, delete, modify, resize, pause, resume, reboot, restore, and tagging actions made through an agent but not directly (access-layer/shared/deny-infra-changes-through-agents.json). Tagging matters because the data plane deny trusts the agent-access tag.
Data layer: Decide what the agent can reach
The data layer decides what an agent can actually reach, on every query. As the Redshift MCP Server documentation puts it, “The database user’s privileges are the security boundary, not this server.”
Give every agent its own identity: One IAM role, database user, and database role. The IAM role agent-support signs in through the Data API as IAMR:agent-support. On Redshift Serverless, a RedshiftDbRoles tag can grant its database role at sign-in (the aws-samples repository shows the tag). Agents acting for a person can use trusted identity propagation. Grant the role after the user’s first sign-in:
-- One database role per agent: privileges go to the role, never to the user
CREATE ROLE agent_support;
GRANT USAGE ON SCHEMA sales TO ROLE agent_support;
GRANT SELECT ON sales.orders, sales.payments TO ROLE agent_support;
GRANT ROLE agent_support TO "IAMR:agent-support";
Row-level security (RLS) filters rows only on tables you attach it to and makes a table default-deny, so attach policies for other roles first.
Column privileges remove columns, such as email.
Dynamic data masking transforms values, such as a card’s last four digits.
Limit what agents can discover. Turn on metadata security so catalog views and SHOW list only objects the role can access, so agents cannot plan around hidden tables (superusers and ACCESS CATALOG roles see all). Test on non-production first:
ALTER SYSTEM SET metadata_security = true; -- superuser only; applies to the whole cluster or workgroup
GRANT ACCESS CATALOG TO ROLE agent_monitoring; -- a monitoring role that must still see every object
Extend the rules to the lakehouse and other warehouses, so no path skips your filters. Redshift enforces Lake Formation permissions on Iceberg tables, including Amazon S3 Tables (a capability of Amazon S3), and federated permissions carry RLS and masking to an agent warehouse. Plain datashares do not carry RLS filters.
Treat free text as untrusted: Keep Redshift ML instructions in the static PROMPT prefix, and pass row text only as input.
Allow only approved models. The model’s IAM role decides at inference time, so allow bedrock:InvokeModel only on approved model ARNs. By default only superusers can create models. Grant CREATE MODEL to an ML platform role, with ASSUMEROLE ... FOR CREATE MODEL only on approved IAM roles.
Test as the agent: Superusers and sys:secadmin bypass RLS.
Output guardrails: What the agent sees, keeps, and says
An agent has three outputs: results it reads, copies it keeps, and its answer. Redshift controls what enters the agent and its database-side copies. The application and agent layer govern the rest.
What the agent sees and says
The data layer’s policies double as output guardrails: results hold only permitted rows and readable columns, masked values stay masked, and Lake Formation filters do the same for Iceberg tables.
Cap result size too: provisioned clusters can abort on return_row_count, and the Redshift MCP Server’s MAX_RESULT_ROWS (1,000 by default) refuses larger results, protecting the context window, not compute.
Data-layer controls end when results leave Redshift, so check the answer too: Bedrock Guardrails can mask PII and flag ungrounded answers, and the generated SQL makes the answer traceable.
What the agent keeps: Database-side exports and copies
A copy starts with none of the source table’s policies, so treat every database-side write path as an output path:
Export path
Guardrail
UNLOAD to Amazon S3
REVOKE ASSUMEROLE ON ALL FROM PUBLIC FOR ALL (which also blocks COPY and CREATE MODEL). Grant ASSUMEROLE ... FOR UNLOAD to pipeline roles only
CETAS and INSERT into external tables
Agent roles own no external schemas
Writes to Apache Iceberg tables
No Lake Formation write permissions for agent-facing roles
CTAS, SELECT INTO, and INSERT ... SELECT
REVOKE CREATE ON SCHEMA public FROM PUBLIC. No CREATE or INSERT for agents
Datashares
No datashare privileges for agent roles
The MCP Server’s read-only mode denies UNLOAD and CALL, but other paths bypass it, so privileges are the durable line (data-layer/exports-and-copies.sql). Audit exports in SYS_UNLOAD_HISTORY, SYS_QUERY_HISTORY, and CloudTrail S3 data events.
Figure 5 summarizes which layer controls each output.
Figure 5: What the agent sees, keeps, and says, and which layer controls each
The cost envelope: Predictable by design
Each agent question has three cost parts (Figure 1): model tokens at Bedrock rates, query compute on Redshift provisioned clusters or Amazon Redshift Serverless RPUs that you already pay for (older RA3 and DC2 clusters also bill lakehouse scans per terabyte), and data at rest. These compute guardrails are part of Redshift, and you pay only for the Redshift compute your queries use:
Set three ceilings on day one (Figure 6): a per-statement timeout for each agent user, max capacity on the agent workgroup, and a daily usage limit. Queue rules are checked every 10 seconds, so the timeout is the tighter cap.
Figure 6: The cost envelope. Each ceiling catches what the one inside it misses
Max capacity and the usage limit do different jobs (see Billing for on-demand compute capacity). Max capacity caps RPUs. The usage limit logs, alerts, or stops user queries once the period’s RPU-hours are used (cost-envelope/serverless-ceilings.sh). emit-metric only publishes a metric. Alarm on it, or choose Alert on the AWS Management Console.
Each Serverless workgroup or RG cluster accepts at most 2,000 connections. In our tests, Data API tools opened one connection per call, but an idle open driver transaction kept Serverless compute running until the 1-hour timeout. On Serverless, deny redshift-serverless:GetCredentials when aws:ViaAWSService is false. In our tests, this blocked driver sign-in, not direct Data API calls. On each non-superuser agent user (superusers ignore connection limits), set:
ALTER USER "IAMR:agent-support" SET statement_timeout TO 120000;
ALTER USER "IAMR:agent-support" CONNECTION LIMIT 10 SESSION TIMEOUT 300; -- size the limit to the agent's concurrency
Spend less per answer
Reuse work: The result cache, composition for new queries, and materialized views for repeated joins.
Right-size the engine. For lake-heavy agents, RG instances cost 30% less per vCPU than RA3, with no per-terabyte scanning charges.
Spend and store less. Every byte saved is a byte agents don’t read. For local tables, keep ENCODE AUTO so Redshift selects optimal column compression by data type. Iceberg tables use zstd compression by default, helping reduce storage and scan costs (cost-envelope/storage-compression.sql).
Control model spend per agent
Bedrock attributes inference cost to the calling IAM principal (Introducing granular cost attribution for Amazon Bedrock). Since Redshift ML calls Bedrock with the role in CREATE EXTERNAL MODEL, give each agent its own role. A trusted tool, the only identity allowed to run the model, fixes maxTokens and bounds input (cost-envelope/model-spend-summarizer.sql), and a budget action can deny bedrock:InvokeModel and bedrock:InvokeModelWithResponseStream to the role as a period-level brake, not a real-time stop.
Per-agent users make SYS_QUERY_HISTORY a compute ledger. Tag both ledgers per AGENTCOST05-BP01. Because the Redshift MCP Server in read-only mode refuses SETquery_group, attribute by IAM role.
Observe and prove
Security reviewers ask what the agent did, and FinOps reviewers ask what it cost. Per-agent identity answers both.
Figure 7 shows how the following records feed back into tighter guardrails.
Figure 7: The observe and prove loop
What ran, and who called it. SYS_QUERY_HISTORY lists each agent user’s queries, and an agent- prefix on every agent identity lets one filter cover them. CloudTrail adds who and when. With trusted identity propagation, both identify the person.
Find shadow agents, which are MCP calls from an identity without the agent- prefix. The application_name setting and the CloudTrail userAgent or userIdentity.invokedBy fields mark MCP traffic (observe/detection/shadow-agents.sql).
In this post, we showed how the layered guardrail model runs agentic analytics on Amazon Redshift, with most controls built into Redshift. The access layer keeps a human in the loop for consequential writes, and the data layer decides what each query can reach.
Bound the data. Grant only needed tables and columns, attach RLS and masking, revoke ASSUMEROLE and CREATE from PUBLIC, and test metadata security on non-production first.
Bound the spend. Set a statement timeout, max capacity, and a daily usage limit, and test that the usage-limit alarm fires.
Amazon S3 Tables, a capability of Amazon Simple Storage Service (Amazon S3), deliver a cloud object store with built-in Apache Iceberg support and streamline storing tabular data at scale. When you integrate them with dbt and AWS Glue, you can run SQL-based data transformations with the reliability and performance of a modern lakehouse, bringing software engineering best practices to the data space.
This post demonstrates how to configure and implement dbt transformations using Amazon S3 Tables with the dbt-glue adapter. Starting with version 1.12.4, the dbt-glue adapter adds incremental merge support for S3 Tables, which the patterns in this post build on. We cover the specific configuration requirements for the dbt-glue adapter and practical implementation patterns built on S3 Tables incremental models: the merge strategy to keep the latest state per record and the append strategy to build an audit-friendly change history.
Example scenario
In this walkthrough, we simulate an ecommerce system that tracks customer profiles and their orders. We first run the pipeline against an initial dataset, then simulate an update to the upstream source data and run it again to demonstrate incremental updates.
Our example scenario follows a data pipeline architecture that uses S3 Tables throughout. Raw ecommerce data (customers.csv and orders.csv) lands in a regular S3 bucket as comma-separated values (CSV). dbt then transforms it through two layers of S3 Tables. A staging layer cleanses and standardizes each source, and a mart layer produces analytics-ready dimension and fact tables. You can query the resulting mart data from a variety of analytics and business intelligence (BI) tools such as Amazon Athena and Amazon Quick Sight. In this post, we query it from Athena.
The mart layer demonstrates two incremental strategies side by side: the fact_orders model uses merge to keep the latest state per order, while fact_order_history uses append to accumulate a full change history.
The data pipeline flow looks like the following chart:
Source Data (Regular S3 - CSV)
└─ customers.csv, orders.csv
↓
Staging Models (S3 Tables)
├─ stg_customers
└─ stg_orders
↓
Mart Models (S3 Tables)
├─ dim_customers
├─ fact_orders (incremental with merge --- latest state per order)
└─ fact_order_history (incremental with append --- change history)
↓
Consumption Layer (Athena, Quick Sight, BI tools)
The following diagram shows the architecture behind this pipeline: dbt-glue submits each model as a Spark SQL statement to an AWS Glue interactive session, which reads from the raw S3 bucket and writes the staging and mart tables as S3 Tables within the same data lake.
Figure 1: Architecture of the dbt transformation pipeline on Amazon S3 Tables with AWS Glue
Prerequisites
Before you begin, make sure that you have the following prerequisites:
In this section, you set up the AWS infrastructure that dbt-glue needs: an S3 table bucket and namespace to hold your dbt models, and an AWS Glue database for your source data.
First, set your environment variables. Replace YOUR_ACCOUNT_ID, YOUR-REGULAR-BUCKET, and YOUR_Glue_Role_ARN with your data:
Note that the S3 Tables namespace is where the S3 Tables corresponding to your dbt models will be created. This is different from regular S3 buckets. Because the “Integration with AWS analytics services” option for S3 Tables is enabled, creating the namespace automatically creates a corresponding AWS Glue database. Verify that it exists in the next step:
In this section, you create sample ecommerce data to transform with dbt: two CSV files (customers and orders), upload them to a general purpose S3 bucket, and register them as AWS Glue tables that your dbt models can read from.
Note: All sample data in this post is synthetic. It was generated to mimic realistic patterns for demonstration purposes only and doesn’t represent any real individuals or transactions.
Complete following steps to create a sample dataset:
Create a directory for sample data and save the following two CSV files: customers.csv:
Create the bucket for source data if it doesn’t exist, and upload the CSV files to the S3 bucket. Replace YOUR-SOURCE-DATA-BUCKET with your bucket name.
The dbt CLI is a command-line interface for running dbt projects. It’s free to use and available as an open source project. Before installing dbt-core, make sure your Python version is 3.10, 3.11, or 3.12.
Install dbt and the dbt CLI with the following code:
Install the dbt-glue adapter with the following code:
$ pip3 install --no-cache-dir dbt-glue
Note that you need to install dbt-glue 1.12.4 or higher, which adds support for incremental append and merge models on S3 Tables.
Create a dbt project
In this section, you create a new dbt project using dbt init, which generates the standard directory structure (such as models, macros, and tests) that you will populate with the S3 Tables models in the next sections.
Run the dbt init command to create and initialize a new empty dbt project.
$ dbt init
For a project name, enter dbt_glue_s3_tables.
For a database, choose [1] glue.
Please ignore dbt_project.yml file [ERROR not found] message as we are going to create it in the next step.
Configure dbt profile
The dbt profile configuration is critical for S3 Tables integration. In this section, you create a dbt profile that connects to AWS Glue Interactive Sessions and configures Spark to read and write S3 Tables through the Iceberg catalog, then validate the connection with dbt debug.
Create ~/.dbt/profiles.yml with the following structure:
Run the following command to validate the configurations:
cd dbt_glue_s3_tables
dbt debug --profiles-dir ~/.dbt/
Expected output is Connection test: [OK connection ok].
Configure dbt project
The dbt_project.yml configuration determines which models use S3 Tables. Create or update dbt_glue_s3_tables/dbt_project.yml with the following structure:
name: 'dbt_glue_s3_tables'
version: '1.0.0'
config-version: 2
profile: 'dbt_glue_s3_tables'
model-paths: ["models"]
test-paths: ["tests"]
macro-paths: ["macros"]
models:
dbt_glue_s3_tables:
# S3 Tables for staging
staging:
+materialized: table
+file_format: 's3tables' # S3 Tables for staging
+table_properties:
'format': 'iceberg'
'write.format.default': 'parquet'
'write.parquet.compression-codec': 'snappy'
# S3 Tables for marts
marts:
+materialized: table
+file_format: 's3tables' # S3 Tables for marts
+table_properties:
'format': 'iceberg'
'write.format.default': 'parquet'
'write.parquet.compression-codec': 'snappy'
Create dbt models
In this section, you build out the full model layer: a sources.yml that registers your raw AWS Glue tables, two staging models that clean and prepare the customer and order data, and three mart models that turn those staged data into a dimension table and two fact tables, one using incremental merge and one using incremental append.
First, create sources.yml defines your raw data tables:
Delete the example folder under dbt_glue_s3_tables/models. This is an example folder created by default and unnecessary now.
Define source tables in models/sources.yml with the following structure:
This sources.yml defines your raw data tables, so you can reference them with the {{ source() }} function in your models. With this file, you can also define data tests like unique, not_null, and referential integrity checks in one central place.
Second, create the staging and mart models. Staging models are where you unpack and transform raw data. Mart models are what downstream consumers actually query.
Create models/staging/stg_customers.sql:
-- Staging model as S3 Tables with incremental merge
{{ config(
materialized='incremental',
incremental_strategy='merge',
unique_key='customer_id',
on_schema_change='sync_all_columns',
file_format='s3tables'
) }}
SELECT
customer_id,
LOWER(TRIM(email)) AS email,
first_name,
last_name,
CAST(registration_date AS DATE) AS registration_date,
customer_segment
FROM spark_catalog.{{ source('raw_ecommerce', 'customers') }}
WHERE customer_id IS NOT NULL
stg_customers.sql reads from the raw customers source, applies light cleansing (email normalization, date casting, null filtering), and writes to S3 Tables using an incremental merge on customer_id to update existing records rather than duplicating them.
Create models/staging/stg_orders.sql:
-- Staging model as S3 Tables with incremental merge
{{ config(
materialized='incremental',
incremental_strategy='merge',
unique_key='order_id',
on_schema_change='sync_all_columns',
file_format='s3tables'
) }}
SELECT
order_id,
customer_id,
CAST(order_date AS DATE) AS order_date,
CASE
WHEN LOWER(TRIM(order_status)) = 'completed' THEN 'completed'
WHEN LOWER(TRIM(order_status)) = 'shipped' THEN 'shipped'
WHEN LOWER(TRIM(order_status)) = 'processing' THEN 'processing'
WHEN LOWER(TRIM(order_status)) = 'cancelled' THEN 'cancelled'
ELSE 'unknown'
END AS status,
CAST(order_amount AS DECIMAL(10,2)) AS total_amount,
EXTRACT(YEAR FROM CAST(order_date AS DATE)) AS order_year,
EXTRACT(MONTH FROM CAST(order_date AS DATE)) AS order_month,
CAST(updated_at AS TIMESTAMP) AS updated_at
FROM spark_catalog.{{ source('raw_ecommerce', 'orders') }}
WHERE order_id IS NOT NULL
stg_orders.sql reads from the raw orders source, normalizes status to a fixed set of values (defaulting to unknown for anything unexpected), casts order_date, total_amount, and updated_at to their proper types, and derives order_year and order_month for downstream partitioning.
Create models/marts/dimensions/dim_customers.sql:
-- Dimension table using S3 Tables
{{ config(
materialized='table',
file_format='s3tables',
partition_by=['registration_year'],
table_properties={
'format': 'iceberg',
'write.format.default': 'parquet'
}
) }}
SELECT
customer_id,
email,
first_name,
last_name,
registration_date,
YEAR(registration_date) as registration_year,
customer_segment,
CASE
WHEN customer_segment = 'Premium' THEN 1
WHEN customer_segment = 'Regular' THEN 2
ELSE 3
END as segment_priority,
CURRENT_TIMESTAMP() as dbt_updated_at
FROM {{ ref('stg_customers') }}
Create models/marts/facts/fact_orders.sql:
-- Fact table using S3 Tables with incremental merge
{{ config(
materialized='incremental',
file_format='s3tables',
incremental_strategy='merge',
unique_key='order_id',
partition_by=['order_year', 'order_month'],
table_properties={
'format': 'iceberg',
'write.format.default': 'parquet'
}
) }}
SELECT
o.order_id,
o.customer_id,
o.order_date,
YEAR(o.order_date) AS order_year,
MONTH(o.order_date) AS order_month,
o.status,
o.total_amount,
c.customer_segment,
c.segment_priority,
CURRENT_TIMESTAMP() AS dbt_updated_at
FROM {{ ref('stg_orders') }} o
LEFT JOIN {{ ref('dim_customers') }} c
ON o.customer_id = c.customer_id
Create models/marts/facts/fact_order_history.sql:
-- Fact table using S3 Tables with incremental append
{{ config(
materialized='incremental',
file_format='s3tables',
incremental_strategy='append',
partition_by=['event_year', 'event_month'],
table_properties={
'format': 'iceberg',
'write.format.default': 'parquet'
}
) }}
SELECT
order_id,
customer_id,
status,
order_date,
total_amount,
updated_at,
CURRENT_TIMESTAMP() AS recorded_at,
YEAR(updated_at) AS event_year,
MONTH(updated_at) AS event_month
FROM {{ ref('stg_orders') }}
{% if is_incremental() %}
WHERE updated_at > (SELECT MAX(updated_at) FROM {{ this }})
{% endif %}
Run the dbt project
Now it’s time to run the dbt project. Complete following steps:
To run the project dbt, you should be in the project folder:
cd dbt_glue_s3_tables
Run the dbt command:
dbt run --profiles-dir ~/.dbt/ --full-refresh
This command starts an AWS Glue interactive session, compiles the dbt models, and materializes all five tables (stg_customers, stg_orders, dim_customers, fact_orders, and fact_order_history) in your S3 Tables namespace. The --full-refresh flag rebuilds the incremental models from scratch, so it’s the right choice for the first run.
Query using Amazon Athena
Before testing the incremental merge and append behavior in the next section, confirm what the initial --full-refresh run loaded into the mart tables. Query the target tables.
In the Athena console, choose the data source and database that correspond to your S3 Tables catalog:
Run the following query to view the data loaded into the fact_orders table:
SELECT * FROM dbt_glue_s3_tables.fact_orders ORDER BY order_id;
The result returns the five order records:
# order_id customer_id order_date order_year order_month status total_amount customer_segment segment_priority dbt_updated_at
1 1001 1 2024-06-01 2024 6 completed 150.00 Premium 1 2026-10-16 09:41:46.590373 UTC
2 1002 2 2024-06-02 2024 6 completed 75.50 Standard 3 2026-10-16 09:41:46.590373 UTC
3 1003 1 2024-06-03 2024 6 completed 200.00 Premium 1 2026-10-16 09:41:46.590373 UTC
4 1004 3 2024-06-04 2024 6 unknown 125.75 Premium 1 2026-10-16 09:41:46.590373 UTC
5 1005 4 2024-06-05 2024 6 completed 89.99 Standard 3 2026-10-16 09:41:46.590373 UTC
Run the following query to view the data loaded into the fact_order_history table:
SELECT * FROM dbt_glue_s3_tables.fact_order_history ORDER BY updated_at;
The result returns the five order history records.
# order_id customer_id status order_date total_amount updated_at recorded_at event_year event_month
1 1001 1 completed 2024-06-01 150.00 2024-06-01 10:00:00.000000 UTC 2026-10-16 09:41:22.801835 UTC 2024 6
2 1002 2 completed 2024-06-02 75.50 2024-06-02 10:00:00.000000 UTC 2026-10-16 09:41:22.801835 UTC 2024 6
3 1003 1 completed 2024-06-03 200.00 2024-06-03 10:00:00.000000 UTC 2026-10-16 09:41:22.801835 UTC 2024 6
4 1004 3 unknown 2024-06-04 125.75 2024-06-04 10:00:00.000000 UTC 2026-10-16 09:41:22.801835 UTC 2024 6
5 1005 4 completed 2024-06-05 89.99 2024-06-05 10:00:00.000000 UTC 2026-10-16 09:41:22.801835 UTC 2024 6
Incremental merge and append on Iceberg table
After the initial --full-refresh run succeeds, verify that the merge and append incremental strategies behave as expected when the source data changes. This demonstrates the row-level update capability that Iceberg on S3 Tables provides.
Update the sample source data
To simulate a real-world scenario where upstream source data changes over time (for example, a customer updating their profile, or new customers signing up), modify customers.csv to include both an update to an existing record and a new record.
order_id=1004: status updated from pending to completed with a later updated_at (to test the merge UPDATE).
order_id=1006: new record added with a later updated_at, associated with the new customer customer_id=6 (to test both the merge INSERT in fact_orders and the append in fact_order_history).
By running without --full-refresh, dbt runs its normal incremental logic instead of rebuilding the tables from scratch. In the staging layer, stg_customers and stg_orders apply the changes with a MERGE INTO statement that updates customer_id=1 and order_id=1004 in place and inserts customer_id=6 and order_id=1006. Downstream, fact_orders (merge) reflects the 1004 update and the 1006 insert as the latest state, while fact_order_history (append) records both 1004 and 1006 as new history rows.
Verify the results in Amazon Athena
After the re-run completes, use Athena to confirm that the merge and append strategies behaved as expected.
Run the following query to view the updated data in the fact_orders table:
SELECT * FROM dbt_glue_s3_tables.fact_orders ORDER BY order_id;
fact_orders returns 6 rows (one per order), with 1004 now completed and 1006 added.
# order_id customer_id order_date order_year order_month status total_amount customer_segment segment_priority dbt_updated_at
1 1001 1 2024-06-01 2024 6 completed 150.00 Premium 1 2026-10-16 10:06:55.944983 UTC
2 1002 2 2024-06-02 2024 6 completed 75.50 Standard 3 2026-10-16 10:06:55.944983 UTC
3 1003 1 2024-06-03 2024 6 completed 200.00 Premium 1 2026-10-16 10:06:55.944983 UTC
4 1004 3 2024-06-04 2024 6 completed 125.75 Premium 1 2026-10-16 10:06:55.944983 UTC
5 1005 4 2024-06-05 2024 6 completed 89.99 Standard 3 2026-10-16 10:06:55.944983 UTC
6 1006 6 2024-07-02 2024 7 completed 45.00 Premium 1 2026-10-16 10:06:55.944983 UTC
Run the following query to view the updated data in the fact_order_history table:
SELECT * FROM dbt_glue_s3_tables.fact_order_history ORDER BY updated_at;
fact_order_history grows from 5 rows to 7 rows on the second run (the 2 rows whose updated_at advanced: 1004 and 1006). Order 1004 now has two history rows: the original unknown status and the new completed status.
# order_id customer_id status order_date total_amount updated_at recorded_at event_year event_month
1 1001 1 completed 2024-06-01 150.00 2024-06-01 10:00:00.000000 UTC 2026-10-16 09:41:22.801835 UTC 2024 6
2 1002 2 completed 2024-06-02 75.50 2024-06-02 10:00:00.000000 UTC 2026-10-16 09:41:22.801835 UTC 2024 6
3 1003 1 completed 2024-06-03 200.00 2024-06-03 10:00:00.000000 UTC 2026-10-16 09:41:22.801835 UTC 2024 6
4 1004 3 unknown 2024-06-04 125.75 2024-06-04 10:00:00.000000 UTC 2026-10-16 09:41:22.801835 UTC 2024 6
5 1005 4 completed 2024-06-05 89.99 2024-06-05 10:00:00.000000 UTC 2026-10-16 09:41:22.801835 UTC 2024 6
6 1004 3 completed 2024-06-04 125.75 2024-06-11 09:30:00.000000 UTC 2026-10-16 10:06:35.291993 UTC 2024 6
7 1006 6 completed 2024-07-02 45.00 2024-07-02 10:00:00.000000 UTC 2026-10-16 10:06:35.291993 UTC 2024 7
Clean up
To avoid ongoing charges, clean up the resources you created during this walkthrough. Complete these steps in the specified order to facilitate proper resource deletion.
Drop the tables dbt created in the S3 Tables namespace.
Delete the data this walkthrough wrote to your S3 bucket: the dbt warehouse data under s3://<YOUR-REGULAR-BUCKET>/glue/data/ and the sample CSV files under s3://<YOUR-REGULAR-BUCKET>/raw/. Leave the bucket itself in place if you use it for other workloads.
(Optional) Remove the local dbt project directory (dbt_glue_s3_tables) and the sample customers.csv / orders.csv files.
Conclusion
In this post, we showed how to build an end-to-end dbt transformation pipeline on Amazon S3 Tables with AWS Glue 6.0, using a staging and mart architecture. At the core of this pipeline are incremental models on S3 Tables, which let us transform and maintain data incrementally with SQL. We demonstrated two incremental strategies working together: the merge strategy to keep the latest state per order in fact_orders, and the append strategy to build an audit-friendly change history in fact_order_history.
S3 Tables support in the dbt-glue adapter is currently experimental (as of version 1.12.4) and will continue to evolve in upcoming releases. As with any experimental feature, we recommend thoroughly testing it in your own environment before use.
Many organizations run their Apache Spark pipelines on AWS Glue and each new AWS Glue release means another round of version upgrades. New versions bring better performance and new features, but upgrading takes work. For every job, an engineer reviews breaking changes across Spark, Python, and libraries, then runs the job on the new version and confirms that it produces the same results. Many jobs turn out to need no changes, but the team learns that only after doing the work. Across hundreds of jobs, upgrading becomes a project that keeps coming back, so many jobs stay on older versions.
Today, we’re announcing automatic version upgrades for AWS Glue jobs (auto upgrade). When you set a job’s version to auto, AWS Glue analyzes the job, asks for your approval, and moves the job to the latest stable version. Instead of planning, testing, and tracking each upgrade, your team reviews and approves it.
In this post, you learn how auto upgrade works and how to:
Turn on auto upgrade for a job and approve the upgrade in the AWS Glue console.
Use an AI agent to assess a fleet of jobs, turn on auto upgrade with email notifications, approve the upgrades, and check the results.
How auto upgrade works
Set a job’s GlueVersion to auto to turn on auto-upgrade. The job keeps running as usual on its current version while AWS Glue checks the job for known breaking changes. AWS Glue doesn’t modify your script. When AWS Glue determines that the job needs no code changes, AWS Glue sends you an eligibility summary with the compatibility results for application code, configuration, and dependencies, and requests your approval. The job stays on its current version until you approve. After you approve, AWS Glue runs the job on the new version and checks the upgraded runs against the job’s earlier runs. AWS Glue then sends you an auto upgrade evaluation summary with the results for correctness, performance, and cost. If the upgraded runs pass the checks, AWS Glue completes the upgrade, and all subsequent runs use the new version. If an upgraded run fails, AWS Glue retries the run on the previous version, so your pipeline keeps running, and then reverts the job. For details, see How an auto upgrade evaluation works in the AWS Glue User Guide.
One or more AWS Glue jobs that meet the following requirements:
The job is a Spark ETL job (glueetl) on AWS Glue 2.0 or later.
The job’s MaxRetries parameter is set to 1 or higher, and job run queuing is turned off.
The job is safe to retry.
For the AI agent walkthrough, you also need the following:
An AI agent that supports skills and MCP servers, such as Kiro or Claude Code, with the managing-glue-jobs skill from the AWS Glue samples repository on GitHub.
The latest version of the AWS Command Line Interface (AWS CLI) version 2.
The spark-upgrade MCP server from Amazon SageMaker Unified Studio, which runs the compatibility assessment. To connect the server, see the skill’s README.
For email notifications, the Amazon Simple Notification Service (Amazon SNS) and Amazon EventBridge permissions in the skill’s permissions.md file.
To install the skill, copy the skill folder into your agent’s skills folder.
Choose the job, and then choose the Job details tab.
For AWS Glue version, choose Auto, and for Number of retries, enter 1 or higher.
Choose Save.
Figure 1: The Job details tab for orders-daily, with AWS Glue version set to Auto
Approve or decline the upgrade
When AWS Glue finishes the compatibility checks and finds no blocking issues, the job waits for your approval.
Choose the job, and then choose the Upgrade analysis tab. The analysis status shows Waiting for consent.
In the Upgrade consent required banner, choose eligibility summary, and review the summary.
Choose Approve to upgrade the job, or choose Decline to keep the job on its current version.
Figure 2: The Upgrade analysis tab for orders-daily, waiting for your approval
The eligibility summary shows the job, the AWS Glue versions, and the compatibility results.
Figure 3: The eligibility summary for orders-daily
Check the result
After the evaluation ends, the Upgrade analysis tab shows the auto upgrade evaluation summary. The summary shows the result for performance, correctness, and cost, with the expected range and each upgraded run’s value for every check.
Figure 4: The auto upgrade evaluation summary for orders-daily
Walkthrough: Upgrade a fleet of jobs with an AI agent
When you manage many jobs, an AI agent with the managing-glue-jobs skill assesses, turns on, and approves auto upgrade across your jobs from a few prompts. The agent shows each change and asks for your confirmation before it makes the change.
Figure 5: The auto upgrade journey for existing jobs
In this walkthrough, you assess your jobs, turn on auto upgrade, approve the upgrade, and check the result. Between these steps, AWS Glue observes and checks each job, and then upgrades and validates the job. Amazon SNS emails you the eligibility summary and the evaluation summary. The steps that follow match the numbers in Figure 5.
A data team runs three Spark ETL jobs in the US West (Oregon) Region and they want to use AWS Glue version 6.0. The jobs orders-daily and clickstream-agg run on AWS Glue 4.0 and write to Amazon Simple Storage Service (Amazon S3). The job customer-profiles runs on AWS Glue 3.0.
Step 1: Assess your jobs
Ask the agent which of your jobs can use auto upgrade. The assessment does not change anything in your environment, so it’s safe to try first. The agent checks each job against the requirements and runs a compatibility assessment. The agent then lists the jobs that can move to AWS Glue 6.0 and asks you to confirm that each job is safe to retry.
Figure 6: The agent assesses the jobs
To see which job isn’t ready and why, ask the agent. The agent names the setting that blocks the upgrade and the fix.
Figure 7: The agent explains why a job isn’t ready
Step 2: Turn on auto upgrade and set up email notifications
Ask the agent to turn on auto upgrade and set up email notifications in one prompt. The agent sets up the email notifications and sets GlueVersion to auto for each job. The jobs keep running on AWS Glue 4.0 until you approve an upgrade. To get the email notifications, confirm the subscription as the reply describes.
Figure 8: The agent turns on auto upgrade and sets up email notifications
Step 3: Review and approve the upgrade
AWS Glue observes and checks each job in the background, and then you review and approve the upgrade.
Step 3a: AWS Glue observes and checks
You keep running the jobs on their usual schedule. In the background, AWS Glue observes the runs and analyzes each job without changing it. How long this takes depends on how often each job runs.
When a job is ready, AWS Glue emails you and requests your approval. The email names the job and the AWS Glue versions, and links to the job in the AWS Glue console. You have seven days to approve or decline.
Figure 9: The approval request email
Step 3b: Review and approve the upgrade
Ask the agent which upgrades are waiting. The agent reads the eligibility summary of each job, and then shows the jobs, their write paths, and what to confirm before you approve.
Figure 10: The agent shows the upgrades that wait for your approval
Before you approve, confirm that the reply lists every path that each job writes to. Then approve the jobs in one prompt, and name each job that you approve.
Figure 11: The agent approves the named jobs
The agent approves only the jobs that you name, and only jobs from the review that it showed you.
Step 4: Check the result
AWS Glue upgrades and validates each job, and then you check the result.
Step 4a: AWS Glue upgrades and validates
After you approve, subsequent runs of each job use AWS Glue 6.0, and AWS Glue validates the upgraded runs. If an upgraded run fails, AWS Glue retries the run on AWS Glue 4.0 and reverts the job. You don’t need to act in this step.
Step 4b: Check the result
When the evaluation of a job ends, AWS Glue emails you the result. Ask the agent for the result of orders-daily. The agent shows the result of each validation check.
Figure 12: The agent shows the result for orders-daily
Ask the agent about the other job. The agent shows the check that failed and suggests a fix.
Figure 13: The agent explains why clickstream-agg didn’t upgrade
Your pipeline continues to run on AWS Glue 4.0. The auto upgrade evaluation summary shows what changed, so you can fix the job before you try again.
Conclusion
In this post, we showed how automatic version upgrades for AWS Glue jobs keep your Apache Spark jobs on the latest stable AWS Glue version. You used an AI agent to assess your jobs and turn on auto upgrade with email notifications. You then reviewed the eligibility summary, approved the upgrades, and checked the results in the auto upgrade evaluation summary.
With auto upgrade, your team no longer needs to plan and run an upgrade project for each job. AWS Glue analyzes each job and checks the upgraded runs against the job’s earlier runs. Your team reviews and approves each upgrade. This way you keep your whole fleet of AWS Glue jobs current instead of upgrading one job at a time.
Some jobs need code changes before they can move to a new version. For those jobs, use generative AI upgrades for Apache Spark in AWS Glue, which proposes and validates the code changes for the new version. After you update the code, set the job’s GlueVersion to auto so that AWS Glue keeps the job current from then on.
Auto upgrade is available today in all commercial AWS Regions. For the list of Regions, see Considerations and limitations in the AWS Glue User Guide. To get started, ask an AI agent with the managing-glue-jobs skill to assess the AWS Glue jobs in your account. Try auto upgrade, and share your feedback in the comments.
Special thanks
A special thanks to everyone who contributed from Engineering and Science to the launch of automatic version upgrades: Ezgi Maden, Akshara Ganapathi, Tina Shao, Raghavendhar Thiruvoipadi Vidyasagar, Shoukat Ghouse, David Zhang, Suthan Phillips, Prasad Nadig, Syed Mahmood, Karthik Seshadri, Pradeep Kumar Nalluri, Adam Rohrscheib, Eric Zhang, Tayo Adedokun, Weston Dunn, Kartik Panjabi, Shubham Mehta, Bryan Liles, Steffen Rochel, Kinshuk Pahare, Paul Meighan, and Rick Sears
Most organizations run a multicloud estate, and so do the attackers targeting them. An adversary who compromises an identity in one provider follows that identity wherever it leads, including across a federated trust into a second cloud service provider. The signals enumerating this scenario are rarely missing; the problem is that they live in separate consoles, in different schemas, owned by different teams. No one has visibility into the whole picture, so no one can decide what to fix first.
AWS Security Hub addresses prioritization and triage with exposure findings. Security Hub correlates reachability, blast radius, vulnerabilities, misconfigurations, and effective permissions, providing a strong correlation layer with an attack-path visualization, providing the context needed to generate risks from findings. That analysis now extends to Microsoft Azure. Security Hub records and analyzes your Azure resources with the same correlation engine used for Amazon Web Services (AWS) resources. The resulting details and meta-data land in the same console, ranked in the same queue, providing holistic, multicloud visibility into your security risks.
In this blog post, you learn how to configure the Azure integration for Security Hub and use exposure findings to prioritize attack paths across both clouds from one console. We follow a realistic scenario: a compromised identity that threatens both an Azure and an AWS environment through a shared, federated identity plane. We show you how the critical exposures along that path are presented as ranked findings that you can triage together, and we map each one to the MITRE ATT&CK framework. We also cover the prerequisites that teams commonly overlook.
Why prioritizing multicloud risk is difficult
Consider an organization whose Microsoft Entra ID tenant is federated into an AWS account, so identities in the tenant can assume an AWS role. This is an ordinary and intentional configuration used to avoid having to manage a second set of credentials. It also means the two clouds share an identity plane: a single compromised Entra identity is both an Azure threat and—through the federation—an AWS threat.
An attacker exploits this, but the defensive signals land in different places:
Each team sees one fragment, and in isolation each fragment appears low severity. You see the risk only when you correlate all of it together and discover the same identity plane ties the attack path together. Exposure findings provide that severity within AWS; extending it to Azure closes the multicloud visibility gap.
How the Azure integration works
You create the Azure connector in the AWS Management Console for Security Hub. It authenticates to your Entra ID tenant through an application registration, records and evaluates your Azure resource configurations, and streams Microsoft Defender for Cloud alerts and Entra ID audit logs through an Azure Event Hubs namespace. Your Azure resources then flow into the same correlation engine that analyzes signals from AWS Security Hub Cloud Security Posture Management (CSPM), Amazon Inspector, Amazon Macie, and Amazon GuardDuty. That engine produces two kinds of findings:
Control findings against standards such as the CIS Microsoft Azure Foundations Benchmark.
Exposure findings, which are ranked, attack-path findings that correlate traits such as reachability, effective permissions, and misconfiguration, with a severity based on how discoverable and exploitable the risk is.
Both use the Open Cybersecurity Schema Framework (OCSF) and appear in the same console as your AWS findings. However, one filtering detail matters: because Security Hub produces the finding, its top-level cloud.provider is AWS, while the evaluated resource carries resources[].provider = Azure. Filter on resources.provider to scope to a single cloud.
Prerequisites
To follow along with this post, you need:
An AWS account with Security Hub enabled. If you use a delegated administrator account for Security Hub, create the connector there, in the AWS Region where you aggregate findings.
An Entra ID tenant with a Microsoft Azure subscription. You need privileges in Azure to create an application registration, assign roles at the tenant root management group, and create a subscription-level diagnostic setting.
The Azure CLI, authenticated to the target subscription with az login command.
Activity log export. Azure resource recordings are change-driven and depend on activity logs reaching the event hub that the connector reads. The onboarding process assigns an Azure policy to create the required diagnostic setting, but it only remediates existing subscriptions after you create a remediation task. If the connector reports healthy status but resources never appear, run az monitor diagnostic-settings subscription list to confirm the export exists, and create a remediation task if the list is empty.
Configuration
The following steps detail how to connect your Azure environment to Security Hub v2: Registering the Azure application, establishing federated identity credentials, and assigning the roles required for AWS to evaluate your Azure resources.
Step 1: Create the Azure connector in Security Hub
The first step in this configuration is to create the Azure connector in Security Hub. The connector establishes trust with your Azure tenant and defines which subscriptions and regions Security Hub v2 will evaluate.
Open the Security Hub console and choose Integrations.
Choose Create Azure connector.
Enter your Azure Tenant ID and the Application (client) ID of the application registration you created for the integration.
For Subscriptions and Regions, select all. Attack paths cross subscription and Region boundaries, so partial coverage leaves blind spots where a compromised identity can pivot unseen. Scope to specific IDs or Regions only when data-residency rules require it.
Run the generated setup script in your Azure environment, then choose Create connector.
Include the global region scope. Controls that evaluate Entra ID and Microsoft Graph resources require it, and those identity exposures are central to this scenario. If you also create an Amazon Inspector or Security Hub CSPM connector for the same tenant, keep its subscriptions and regions consistent with this one.
Step 2: Verify the connector and its recording activity
Health status alone doesn’t tell you whether recording is flowing. Confirm both.
Step 4 (optional): Add Amazon Inspector for Azure vulnerability scanning
To add vulnerability findings for Azure virtual machines (VMs), function apps, or container registry images, create an Amazon Inspector connector for the same tenant. VM scanning requires each target VM to have a system-assigned managed identity, which you can enforce with an Azure Policy. Figure 1 shows a correctly configured Azure integration inside Security Hub, with vulnerability management and posture management deployed.
Figure 1: Successful configuration of the Azure integration with Security Hub
Walk-through: Prioritizing a cross-cloud attack path
In this example, the organization has one identity plane across two clouds, comprising a Microsoft Entra ID tenant with a federated trust into an AWS account. An adversary who compromises the right Entra identity gains an initial foothold in Azure and a path into AWS, because both clouds trust the same identity plane. The following sections trace that path. Each step is a real, high-severity exposure finding that Security Hub ranked on its own. The point of the walk-through is to demonstrate a real-life scenario and examine all findings in one unified security console.
The path begins with an Entra identity that is both over-privileged and unprotected. You’ll find this in the Security Hub console under Exposures, where Security Hub raises it as an identity exposure finding and maps the attack path stemming from it:
Potential Unauthorized Access: Azure RBAC user with administrative access has MFA disabled (high). It correlates the user, the role assignment that grants administrative access, and the organization.
The tenant’s authorization policies let an attacker broaden that foothold, and Security Hub CSPM reports each policy as a failed control (high): Microsoft Entra ID authorization policies should prohibit default users from registering applications…should restrict user consent for applications, and Azure authorization policies should restrict guest invitations to admin roles only. Each finding expands what a single compromised, non-privileged identity can do without an administrator.
Phase 2: Foothold and privilege escalation (Azure)
The tenant contains an internet-reachable VM whose network security group allows inbound from any address, and whose attached identity holds administrative rights over the subscription. Security Hub surfaces this under Exposures, correlating reachability and effective permissions into one finding that shows why it matters: anyone reaching the VM inherits admin control of the subscription.:
Potential Initial Access: Potentially internet reachable Azure virtual machine with open network security group has administrative access (high). It correlates the VM, the role assignment, the network security group, and the public IP address.
The finding’s analysis reads like an attack path. The resource “may be reachable from the public internet,” “overly permissive network security group (NSG) rules allow unintended inbound access,” and “the Owner or Contributor role grants extensive permissions… enabling a threat actor to escalate privileges.” Security Hub evaluates this from configuration and network-path modeling, so it surfaces whether or not the VM is running. Figure 2 shows the correlated attack path for that virtual machine.
Figure 2: An Azure attack-path exposure, analyzed by the same correlation engine as AWS exposures
The cross-cloud bridge: Federation into AWS
The tenant from Phases 1 and 2 is federated into the AWS account through an IAM SAML identity provider. As shown in Figure 2, a role trusts that provider and grants read access to every bucket in Amazon Simple Storage Service (Amazon S3). This trust is what expands the risk across clouds from the same adversary: a compromised Entra identity can assume this role and reach AWS data.
This one hop lives in IAM rather than in Security Hub. Security Hub doesn’t not raise a finding for a role that trusts your own federated identity provider. Confirming it is a normal investigative pivot: the role trusts a SAML identity provider that represents your Entra tenant, the same tenant whose exposures you triaged when you added Amazon Inspector in Step 4.
Figure 3: The federated trust that links the two clouds through a shared identity plane
Phase 3: The impact (AWS)
ATT&CK: Data from Cloud Storage (T1530), Transfer Data to Cloud Account (T1537)
On the AWS side, the correlation engine has already categorized the resources this identity can reach. Under Exposures in the Security Hub console, the sensitive-data objective surfaces this finding because that reachable set includes data at risk; a compromised identity could destroy it:
Potential Sensitive Data Destruction: S3 bucket has sensitive data and versioning disabled and Object Lock disabled and MFA delete disabled (high). A Macie finding, The S3 object contains personal information, is a contributing signal, and the control S3 general purpose buckets should be encrypted at rest with AWS KMS keys fails alongside it.
The same account carries related AWS attack-path exposures. Two examples are Potential Resource Hijacking: Internet reachable EC2 instance with open security group has software vulnerabilities with limited effective permissions and Potential Unauthorized Access: IAM user has weak password policies. In the exposure queue, these sit next to the Azure findings, ranked by the same severity model.
Prioritizing across both clouds in the console
Here is the operational benefit. An analyst is notified of generated exposure findings and opens the dashboard and filters to High severity. In one prioritized list, without switching tools or opening a ticket for another team, they see the Azure admin identity without MFA, the internet-reachable Azure VM with subscription-admin rights, and the AWS sensitive data exposure. Together, these show the full scope of what a single vector, sharing an identity plane, might target. The analyst confirms the connecting federation with one pivot into IAM. The multicloud triage that used to require two products and two teams now occurs in one place. Figure 4 shows that single ranked queue.
Figure 4: Cross-cloud exposure prioritization in a single console
Phase-to-exposure summary
The following table traces each phase of the attack path to its MITRE ATT&CK techniques, the cloud where it plays out, and the ranked Security Hub exposure that surfaces it — following the pivot from Azure into AWS across the shared identity plane.
Phase
ATT&CK
Cloud
Ranked exposure in Security Hub
1. Compromised identity
T1566, T1078.004
Azure
Potential Unauthorized Access: Azure RBAC user with administrative access has MFA disabled (High)
2. Foothold and privilege escalation
T1190, T1078.004
Azure
Potential Initial Access: internet reachable Azure VM with open NSG has administrative access (High)
2.1 Bridge
T1550 (Use Alternate Authentication Material)
Azure to AWS
Federated trust, confirmed in AWS IAM (shared identity plane)
3. Data objective
T1530, T1537
AWS
Potential Sensitive Data Destruction: S3 bucket has sensitive data… (High), plus Macie
Conclusion
A cross-cloud attack is difficult to prioritize because signals are generated across separate consoles, schemas, and teams. In this post, you saw how the Azure integration for AWS Security Hub brings Azure resources into the same exposure engine and the same queue as your AWS resources. One analyst can prioritize an attack path that spans a compromised Microsoft Entra ID identity, across a federated trust, to sensitive data in Amazon S3, without leaving Security Hub.
To recap why this workflow is practical and effective:
Security Hub records and analyzes your Azure security findings and displays them in the same unified console as your AWS resources, and produces ranked, attack-path exposure findings for both clouds.
Findings from both clouds share the OCSF schema, so you filter, group, and prioritize them in one place. Filter on resources.provider to scope an individual cloud.
Security Hub correlates signals into attack paths within each cloud. The analysis creates a cross-cloud narrative, such as a shared federated identity plane, while co-locating ranked correlation findings across both Azure and AWS, creating efficient scoping and remediations.
Confirm your prerequisites. Include the global region scope for Entra ID controls, know that sign-in log signals require an Entra ID P1 or P2 license, and confirm that the subscription diagnostic setting that exports Activity Logs to the connector’s event hub is in place. A connector can report a healthy status while it records nothing.
Apache Airflow orchestrates data pipelines ranging from data ingestion and machine learning to SQL-based analytics. Some analytical workloads, such as daily rollups and usage reports, process bounded datasets and can run within the resources of a single worker. For these workloads, deploying a distributed query cluster can add unnecessary infrastructure and operational complexity.
DuckDB is an open source in-process analytical database that runs within an application without requiring a separate database server. Its columnar, vectorized execution engine supports analytical SQL operations, including scans, joins, and aggregations.
Amazon Managed Workflows for Apache Airflow (Amazon MWAA) runs Apache Airflow as a managed service, so you can schedule, run, and monitor workflows without managing the underlying Airflow infrastructure. Combined with DuckDB, you can add SQL transformations to your pipelines that run inside the Airflow task itself.
In this post, you learn how to run DuckDB with an Amazon MWAA Provisioned environment.
How DuckDB and Amazon MWAA work together
In Apache Airflow, a directed acyclic graph (DAG) defines tasks and their dependencies, along with scheduling, retry, and concurrency settings. Amazon MWAA runs the tasks on workers and publishes configured task logs to Amazon CloudWatch Logs.
DuckDB runs in the Airflow task process, using the CPU, memory, and local storage of the Amazon MWAA worker container. Amazon MWAA orchestrates the workflow, while DuckDB performs the SQL processing.
This walkthrough uses DuckDB 2.0.0, which includes asynchronous I/O for reading from object storage and first-class VARIANT support for semi-structured data. DuckDB 2.0.0 also supports a client-server mode through the Quack protocol, which lets other processes connect to a DuckDB database over the network. This walkthrough runs DuckDB in-process because each Airflow task performs a self-contained transformation.
Introducing the Apache Airflow DuckDB provider
The Apache Airflow DuckDB provider provides the DuckDBExecuteQueryOperator. The operator runs DuckDB locally in the worker container and executes SQL without starting a separate query service.
The DuckDB integration in the Amazon provider adds the AWS aware duckdb_aws connection type. On supported Amazon MWAA Provisioned environments, the DuckDB packages are preinstalled, and Amazon MWAA creates the default connection, as described later in this post.
Solution overview
An engineering team operates a shared inference service that product teams use for their applications. As usage grows, the team needs to understand which applications and teams are driving inference activity and the estimated cost of that usage. Showback provides an itemized view of usage and estimated cost without charging teams directly.
To build the showback pipeline without a separate analytics cluster, the team uses Amazon MWAA to orchestrate Airflow tasks that run DuckDB. DuckDB reads source files from Amazon Simple Storage Service (Amazon S3), performs SQL transformations, and publishes the results as Apache Iceberg tables in Amazon S3 Tables. This pattern suits bounded, SQL-oriented workloads that run reliably within the resources of a single worker.
Figure 1: Amazon MWAA orchestrates two DuckDB tasks across five stages, from reading Parquet data in Amazon S3 through publishing and validating Iceberg tables in Amazon S3 Tables
The workflow has five logical stages, implemented by two Airflow tasks, as shown in Figure 1.
Stage 1: Store the source data – An Amazon S3 bucket stores the Parquet files for inference events, model rates, and application ownership records.
Stage 2: Trigger the DAG – A manual action starts this example DAG. Amazon MWAA orchestrates both tasks, tracks their status, and sends task logs to Amazon CloudWatch Logs. You can configure a schedule for recurring runs.
Stage 3: Read, clean, and combine the records – The transform_and_publish_showback task uses DuckDB to read the Parquet files directly from Amazon S3, deduplicate events, and apply the model rate and ownership record effective at each invocation timestamp.
Stage 4: Publish the result – In the same transform_and_publish_showback task, DuckDB merges the processed records into the costed_invocations Iceberg table in Amazon S3 Tables and commits the update. The task also creates the daily_application_showback and team_budget_status summary tables.
Stage 5: Validate published tables – After publication, the second Airflow task, validate_showback, uses DuckDB to check the row count, confirm that event IDs are unique, and verify the expected allocation states.
The sample rates and cost_credits values are synthetic and are provided only to demonstrate allocation logic. They do not represent AWS pricing, Amazon Bedrock charges, or customer billing records.
Prerequisites
Before you begin, make sure you have the following resources and permissions:
An Amazon MWAA Provisioned environment running Apache Airflow 3.3.1 with Python 3.12. See Apache Airflow versions on Amazon MWAA for the currently supported versions.
An Amazon S3 bucket for the source Parquet files and an Amazon S3 Tables table bucket for the outputs.
An Amazon MWAA execution role with read access to the source bucket and permissions to create, read, and update tables and table data in the target table bucket. For the required actions, see Accessing Amazon S3 Tables using open source applications. If the table bucket uses a customer managed AWS Key Management Service (AWS KMS) key, the role also needs permission to use that key.
Network connectivity from the Amazon MWAA private subnets to Amazon S3 and Amazon S3 Tables. This sample installs the DuckDB Iceberg extension at runtime, so it also requires access to the official DuckDB extension repository unless the matching extension is already available.
The sample bundle containing the DAG, SQL, and synthetic-data generator used in this walkthrough.
Python 3, the dependencies listed in generator-requirements.txt, and the AWS Command Line Interface (AWS CLI) configured on the workstation where you generate and upload the sample data.
In the test environment used for this post, Amazon MWAA included apache-airflow-providers-amazon 9.38.0, apache-airflow-providers-duckdb 0.2.0, and DuckDB 2.0.0. These versions might change in future Amazon MWAA releases.
Use the built-in DuckDB providers and connection
Amazon MWAA Provisioned environments running Apache Airflow 3.3.1 include DuckDB, the Apache Airflow DuckDB provider, and the DuckDB integration in the Amazon provider. Amazon MWAA also creates a connection named duckdb_default with the connection type duckdb_aws. You do not need to add packages to requirements.txt or create the connection manually.
To confirm that the connection exists, choose Admin, then Connections in the Airflow UI. Look for duckdb_default.
Note: When a DuckDBExecuteQueryOperator task doesn’t specify conn_id, it uses duckdb_default. The AWS aware hook obtains temporary credentials from the Amazon MWAA execution role and creates a DuckDB S3 secret for the task. Don’t put AWS access keys in the DAG or create a separate S3 secret in the SQL, because doing so can conflict with the secret the hook creates. If duckdb_default doesn’t appear under Admin, Connections, update your Amazon MWAA environment without changing any settings to apply the latest Amazon MWAA image.
Prepare the sample data
Use generate_ai_inference_data.py from the sample bundle to create Parquet files containing inference events, model rates, and application ownership records. A fixed random seed makes the input reproducible. The dataset includes duplicate events and changes to rates and ownership, allowing you to demonstrate deduplication and effective-dated attribution.
Run the generator and upload the resulting files to Amazon S3:
The default settings generate approximately 300,000 unique events across daily partitions. The generated manifest.json records the expected unique-event count for subsequent validation.
Build the DuckDB transformation
See publish_showback.sql in the sample bundle for the complete transformation SQL. The following excerpts highlight three operations used in the pipeline.
Read Parquet files and remove duplicates
The read_parquet function reads daily Parquet partitions directly from Amazon S3. The union_by_name option aligns columns across files with different schemas. A ROW_NUMBER window function retains the record with the most recent ingestion timestamp for each event ID.
CREATE OR REPLACE TEMP TABLE latest_events AS
SELECT *
FROM read_parquet(
's3://<SOURCE-BUCKET>/ai-showback/'
'inference_events/ingest_date=*/*.parquet',
hive_partitioning = true,
union_by_name = true
)
QUALIFY ROW_NUMBER() OVER (
PARTITION BY event_id
ORDER BY ingested_at DESC
) = 1;
Apply rates and ownership at the event time
Model rates and application ownership can change over time. Using only the current reference record would misattribute historical events. The DuckDB ASOF LEFT JOIN selects the latest reference record whose effective timestamp is no later than the event timestamp.
CREATE OR REPLACE TEMP TABLE events_with_rates AS
SELECT
e.*,
r.input_credits_per_million,
r.output_credits_per_million
FROM latest_events AS e
ASOF LEFT JOIN read_parquet(
's3://<SOURCE-BUCKET>/ai-showback/reference/model_rates.parquet'
) AS r
ON e.model_id = r.model_id
AND e.event_ts >= r.effective_from;
CREATE OR REPLACE TEMP TABLE costed_batch AS
SELECT
e.*,
o.team_id,
o.cost_center,
(
e.input_tokens * e.input_credits_per_million
+ e.output_tokens * e.output_credits_per_million
) / 1000000.0 AS cost_credits
FROM events_with_rates AS e
ASOF LEFT JOIN read_parquet(
's3://<SOURCE-BUCKET>/ai-showback/'
'reference/application_ownership.parquet'
) AS o
ON e.application_id = o.application_id
AND e.event_ts >= o.effective_from;
The full sample retains events without matching reference records and assigns an allocation status. This makes missing rate or ownership data visible during validation rather than excluding those events.
Publish retry-safe Iceberg output
Set the DuckDB session timezone to UTC, attach the Amazon S3 Tables table bucket as an Iceberg catalog, then merge the transformed records using a stable event ID:
INSTALL iceberg;
LOAD iceberg;
SET TimeZone = 'UTC';
ATTACH 'arn:aws:s3tables:<REGION>:<ACCOUNT-ID>:bucket/<TABLE-BUCKET>'
AS s3t (TYPE iceberg, ENDPOINT_TYPE s3_tables);
CREATE SCHEMA IF NOT EXISTS s3t.ai_showback;
MERGE INTO s3t.ai_showback.costed_invocations AS target
USING costed_batch AS source
ON target.event_id = source.event_id
WHEN MATCHED THEN UPDATE SET
ingested_at = source.ingested_at,
team_id = source.team_id,
cost_center = source.cost_center,
cost_credits = source.cost_credits
WHEN NOT MATCHED THEN INSERT BY NAME;
For daily_application_showback, use every grouped dimension in the MERGE condition. Use null-safe comparisons for nullable dimensions so that a retry cannot match multiple grouped source rows to one target row:
ON target.usage_date = source.usage_date
AND target.application_id = source.application_id
AND target.team_id IS NOT DISTINCT FROM source.team_id
AND target.cost_center IS NOT DISTINCT FROM source.cost_center
AND target.model_id = source.model_id
AND target.use_case IS NOT DISTINCT FROM source.use_case
The sample uses an unpartitioned tutorial table because support for update and delete operations can vary by DuckDB and Iceberg version. Validate table creation, the write pattern, partition design, partial-failure behavior, and reruns with the versions you deploy. An Iceberg snapshot commit is atomic for one table, but commits to the three output tables are not a single transaction.
Create the Amazon MWAA DAG
The duckdb_ai_inference_showback.py file in the sample bundle contains the complete Apache Airflow 3.3.1 DAG. It uses the public airflow.sdk import and a timezone-aware start date. Because schedule=None, you trigger it manually. You can add a schedule for recurring runs. The publication task runs before validation. Setting max_active_runs=1 prevents overlapping runs of this DAG. The detailed-table merge matches on event_id to avoid duplicate inserts during unchanged-input retries. Test partial failures, summary-table updates, and external concurrent writers separately.
# PUBLISH_SQL, VALIDATE_SQL, and the URI constants are defined in the sample bundle.
import pendulum
from airflow.sdk import DAG
from airflow.providers.duckdb.operators.duckdb import (
DuckDBExecuteQueryOperator,
)
with DAG(
dag_id="duckdb_ai_inference_showback",
start_date=pendulum.datetime(2026, 9, 1, tz="UTC"),
schedule=None,
catchup=False,
max_active_runs=1,
) as dag:
# Transform the source records and publish the Iceberg output.
transform_and_publish = DuckDBExecuteQueryOperator(
task_id="transform_and_publish_showback",
sql=PUBLISH_SQL,
split_statements=True,
params={
"events_uri": EVENTS_URI,
"rates_uri": RATES_URI,
"ownership_uri": OWNERSHIP_URI,
"table_bucket_arn": TABLE_BUCKET_ARN,
},
hook_params={
"memory_limit": "2GB",
"threads": 2,
"temp_directory": "/tmp/duckdb-ai-showback-spill",
},
retries=1,
)
# Verify the detailed and summary outputs after publication.
validate = DuckDBExecuteQueryOperator(
task_id="validate_showback",
sql=VALIDATE_SQL,
split_statements=True,
retries=1,
)
transform_and_publish >> validate
Because the operators omit conn_id, they use the built-in duckdb_default connection. The hook_params settings only limit DuckDB memory and threads and select a local spill directory.
In duckdb_ai_inference_showback.py, replace the source bucket and table bucket ARN placeholders, then upload the file to the Amazon S3 DAG folder configured for your Amazon MWAA environment.
Run and validate the pipeline
See validate_showback.sql in the sample bundle for the complete validation SQL. In the Airflow user interface, unpause duckdb_ai_inference_showback and trigger the DAG manually. The graph should show transform_and_publish_showback running before validate_showback.
The validation checks the row count and logical-key uniqueness of both summary tables in addition to the detailed-table manifest, event-ID uniqueness, and allocation-state checks. These assertions make an unchanged-input rerun fail if it creates duplicate summary rows.
Figure 2: The Airflow DAG runs transformation and publication before validation
We tested the walkthrough on a new mw1.small Amazon MWAA Provisioned environment in the Canada (Central) Region. The environment had no requirements or plugins file. In the representative run, the pipeline processed 303,543 source rows, removed 3,543 later-arriving duplicates, and published 300,000 unique events. The transform-and-publish task completed in about 11 seconds, and validation completed in about 6 seconds. These measurements describe this test run. Performance varies with worker capacity, data layout, and concurrent workloads.
Figure 3: The representative run and two unchanged-input reruns completed successfully
Review the transform-and-publish task log to confirm that DuckDB loaded the required extensions, read the inputs, and committed the Iceberg tables.
Figure 4: The AWS aware hook creates the DuckDB S3 secret from temporary Amazon MWAA execution-role credentials before publication
The validation task confirmed unique event IDs, a detailed row count matching the generator manifest, all expected allocation states, and unique logical keys in both summary tables. The result contained 272,728 allocated events, 3,683 events missing a rate, 5,522 events missing ownership, and 18,067 non-success events. The summary tables contained 8,949 daily application rows and 9 team budget rows.
Figure 5: The validation task reports PASS for uniqueness, row count, and allocation coverage
Trigger the DAG twice more without changing the source files. In our test, all three runs retained 300,000 unique events, 8,949 daily application rows, 9 team budget rows, the same allocation counts, and zero duplicate logical keys. This demonstrates repeatability for unchanged input, but does not establish recovery from partial failures or concurrent external writes.
The pipeline published a detailed costed_invocations table and two summary tables, daily_application_showback and team_budget_status, in the ai_showback namespace.
Figure 6: Amazon S3 Tables contains the detailed output and two summary tables
When you run DuckDB with Amazon MWAA, each task runs in an Amazon MWAA worker container whose CPU and memory depend on the environment class. Because Amazon MWAA uses the Celery executor, a single worker can run multiple Airflow tasks concurrently. Keep the following in mind:
Worker capacity: Set the DuckDB memory limit, thread count, and temporary spill space, then test with representative data. Joins, sorting, and data skew can affect peak resource use more than compressed input size alone.
Concurrency: Concurrent tasks on a worker share its CPU and memory, and each DuckDB task can also use multiple threads. Use Airflow pools and max_active_runs to limit how many DuckDB tasks run together and to prevent overlapping writes to the same tables.
Processing boundary: Use this pattern when SQL processing completes reliably within one worker. If a step needs horizontal scaling, high write concurrency, or more resources than one worker provides, run it with AWS Glue or Amazon EMR. Amazon MWAA can continue to orchestrate it.
To avoid ongoing charges, pause the DAG and remove its file from the Amazon MWAA DAG folder. Delete the synthetic source data and drop the tutorial Iceberg tables. Remove the table bucket, source bucket, and Amazon MWAA environment only if you created them exclusively for this walkthrough. Remove any tutorial-specific permissions that are no longer needed.
Conclusion
In this post, you used Amazon MWAA to orchestrate an embedded DuckDB analytics pipeline. DuckDB ran inside the Airflow tasks to transform Parquet data from Amazon S3, publish the results as Apache Iceberg tables in Amazon S3 Tables, and validate the output. The DAG defined the task dependencies, while Amazon MWAA ran and monitored the tasks.
This pattern suits bounded, SQL-oriented transformations that fit within one worker. Start with representative data, set DuckDB memory and thread limits, and test retries, concurrency, and multi-table write behavior. If a task outgrows one worker, Amazon MWAA can continue orchestrating the workflow while a distributed service performs that step.
We thank Kamen Sharlandjiev (Principal Specialist Solutions Architect) and Aritra Ghosh (Senior Product Manager) for their contributions to this post.
Aderant, a global provider of business management software for the legal industry, modernized the data pipeline powering its Stridyn analytics tool using Apache Iceberg, AWS Lambda, and AWS Glue. The new architecture delivers near real-time data availability for 700 client environments across 266 source tables. It replaces a batch-oriented pipeline that took 15 minutes per processing cycle with an event-driven system that processes change data capture (CDC) events in single-digit seconds.
In this post, we share how Aderant redesigned its multilayer data pipeline using a medallion architecture (bronze, silver, and gold layers) built on Apache Iceberg tables. This approach achieved 10–26x faster query performance and a 77 percent cost reduction compared to alternative approaches. We include architecture details, performance benchmarks, and the decision framework so that analytics teams managing multi-tenant SaaS tools can apply the same pattern.
The challenge: Batch processing limiting analytics freshness
Aderant’s Stridyn analytics application serves 700 client environments running Expert Sierra, its cloud-based legal practice management solution. The tool processes data from 266 source tables in Microsoft SQL Server databases, delivering financial reports, billing analytics, and operational dashboards to law firms globally.
The existing pipeline faced several challenges:
Slow processing times. A full data processing cycle took approximately 15 minutes, with batch job overhead adding latency before data transformation could begin.
Limited real-time data availability. Clients experienced delays between operational changes and analytics visibility, impacting time-sensitive billing and matter management decisions.
Performance issues with complex queries. Reports involving window functions, joins across multiple fact tables, and common table expressions (CTEs) suffered from slow response times when querying external tables through Amazon Redshift Spectrum.
Scalability constraints. The architecture struggled to handle custom data, schema changes, and a growing volume of CDC events that already reached 380 million per month across all tenants.
The catalyst for modernization came from Aderant’s commitment to delivering near real-time data availability, making sure data is accessible within minutes from source to target without changing the end-user experience.
The solution: Event-driven medallion architecture with Apache Iceberg
Aderant built a new data pipeline using a medallion architecture with three distinct layers (bronze, silver, and gold), all built on Apache Iceberg tables stored in Amazon Simple Storage Service (Amazon S3). The architecture uses AWS Lambda for event-driven CDC processing, AWS Glue for transformations, and Amazon Redshift for the final analytics serving layer.
How it works: The lifecycle of a data change
The following steps describe what happens when a record changes in a client’s source database.
CDC capture and delivery.AWS Database Migration Service (AWS DMS) captures changes from Microsoft SQL Server databases and writes Parquet files to an S3 landing zone, organized by table and tenant.
Event-driven ingestion (raw to bronze). An S3 event notification triggers an Amazon Simple Queue Service (Amazon SQS) message, which invokes a Lambda function that processes the CDC payload and writes to bronze-layer Iceberg tables in single-digit seconds per event.
Bronze-to-silver transformation. AWS Glue jobs read incremental data from bronze tables using Amazon DynamoDB-based watermarking, apply normalization and deduplication through Iceberg MERGE operations, and produce current-state silver tables with ACID adherence.
Silver-to-gold aggregation. The gold layer uses two approaches based on table complexity: incremental AWS Glue jobs for 77 standard gold tables, and materialized views with Iceberg snapshot comparison for 34 tables with complex query patterns that cannot be easily incrementalized.
Gold-to-Amazon Redshift delivery. Delta changesets from materialized view snapshots are written to native Amazon Redshift tables, where columnar storage, zone maps, and sort keys deliver sub-100-millisecond query performance for end-user dashboards.
Why Apache Iceberg
Aderant chose Apache Iceberg as the table format across all pipeline layers for three reasons.
ACID transactions for concurrent operations. With 700 tenants generating CDC events simultaneously, Iceberg’s snapshot isolation helps prevent conflicts when multiple Lambda functions write to the same tables concurrently.
Time travel and snapshot comparison. For the 34 complex gold tables, Iceberg’s snapshot metadata identifies deltas without manual watermarking. The system compares consecutive snapshots to determine exactly which rows changed, then writes only those deltas to Amazon Redshift.
Schema evolution without pipeline disruption. As Aderant onboards new data sources and clients customize their schemas, Iceberg handles column additions and type changes without requiring full table rebuilds.
Why AWS Lambda for CDC processing
After evaluating three architectural approaches, the team chose Lambda based on cost, latency, and operational simplicity. The Docker container image deployment model (using Amazon Elastic Container Registry) accommodates the large library dependencies required for Iceberg operations, including PyIceberg and pandas. The pay-per-invocation model also aligns naturally with CDC workloads, where event volume fluctuates throughout the day, scaling to zero during quiet periods and handling 10x seasonal spikes without pre-provisioned capacity.
Architecture
The following diagram illustrates the end-to-end data flow from source databases through the medallion layers to the analytics serving layer.
Figure 1: End-to-end data flow through the medallion architecture, from source databases to the Amazon Redshift serving layer
The pipeline begins at the source layer, where AWS DMS replicates CDC events from Microsoft SQL Server databases into an Amazon S3 landing zone as Parquet files. When new files arrive, Amazon S3 Event Notifications publish messages to an Amazon SQS queue. The queue serves as a buffer to handle burst traffic and provides dead-letter queue capabilities for failed events.
AWS Lambda functions, deployed as Docker containers through Amazon Elastic Container Registry (Amazon ECR), consume messages from the SQS queue and write to bronze-layer Iceberg tables in Amazon S3. These Lambda functions use the PyIceberg library to perform ACID-aligned writes, and Amazon DynamoDB stores watermark state to track processing progress and help prevent duplicate writes. The AWS Glue Data Catalog registers Iceberg table metadata across the bronze, silver, and gold layers.
Amazon EventBridge triggers the next stage on a 5-minute schedule, invoking a decision Lambda function that checks whether bronze-to-silver AWS Glue jobs should run based on data availability. When new data is present, AWS Glue 5.0 jobs (running Apache Spark 3.5 on Python 3.11) read incrementally from bronze tables. These jobs apply MERGE operations for deduplication and normalization, then write clean records to silver-layer Iceberg tables. DynamoDB watermarks make sure each AWS Glue job processes only new data since its last successful run.
The silver-to-gold transition follows two paths. For the 77 standard gold tables, Amazon EventBridge detects the completion of bronze-to-silver jobs and triggers a second decision Lambda. That Lambda launches incremental AWS Glue jobs that write directly to Amazon Redshift native tables through the Amazon Redshift Data API. For the 34 complex gold tables, AWS Glue materialized views perform the transformation in SQL. A separate AWS Glue job compares Iceberg snapshots to extract only the changed rows and writes those delta changesets to Amazon Redshift native tables.
Amazon Redshift Serverless serves as the final analytics layer, where native tables with columnar storage, zone maps, and sort keys deliver sub-100-millisecond query latency. A GraphQL Data API layer sits between Amazon Redshift and the end-user dashboards, serving 42 pre-built reports including financial statements, billing analytics, and firm overview dashboards.
Amazon CloudWatch provides end-to-end observability across pipeline components, with custom metrics tracking processing latency, error rates, and throughput per tenant. AWS Identity and Access Management (IAM) enforces least-privilege access, and S3 data is encrypted using AWS Key Management Service (AWS KMS) with server-side encryption. The entire infrastructure is defined in Terraform and deployed through GitHub Actions continuous integration and continuous delivery (CI/CD) pipelines.
Materialized views: Solving the complex query problem
A notable aspect of the architecture is how Aderant handles the 34 gold tables that involve complex SQL patterns: LAG/window functions, joins across multiple fact tables, UNIONs with aggregations, and CTEs.
For these tables, traditional incremental processing would require redesigning each query’s logic. Instead, the team uses AWS Glue materialized views as an intermediate step:
Create materialized views using standard Spark SQL (CREATE MATERIALIZED VIEW AS SELECT ...) against silver-layer Iceberg tables.
Automatic change tracking through Apache Iceberg, which monitors source table changes without manual watermarking.
Scheduled refresh every 2–5 minutes through AWS Glue jobs (bypassing the 1-hour minimum for automatic refresh).
Delta extraction by comparing Iceberg snapshots between refreshes.
Write to Amazon Redshift only the changed rows as native table updates.
This approach alleviates the need to rewrite complex analytical queries while still achieving incremental processing. The materialized view handles the computational complexity, and Iceberg’s snapshot comparison identifies what changed.
Quantifiable results
The architecture improvements delivered measurable gains across three dimensions: query performance, pipeline latency, and infrastructure cost.
Query performance
The team benchmarked 16 analytical queries, ranging from simple aggregations to complex pivots over 9 million rows, comparing Amazon Redshift native tables against external tables queried through Amazon Redshift Spectrum. Across all query types, native tables delivered 10–26x faster response times, consistently returning results in under 100 milliseconds regardless of dataset size. The largest improvement came on smaller, frequently accessed datasets (25.8x speedup), while complex pivot queries with window functions still achieved a 13.7x improvement. These benchmarks were conducted on Amazon Redshift Serverless at 16 RPU, meaning provisioned clusters with dedicated compute and persistent caching would perform even better.
The team also validated Amazon S3 Express One Zone for workloads that remain on S3-based Iceberg tables without Amazon Redshift. It reduced query latency by 31–78 percent compared to Amazon S3 Standard, with the greatest gains on complex queries involving multiple table scans.
Pipeline latency
The largest operational improvement is end-to-end processing time. The previous pipeline required approximately 15 minutes per full processing cycle. The new event-driven ingestion layer processes CDC events without batch job overhead. CDC events now flow from source database to bronze-layer Iceberg tables in single-digit seconds. Gold layer refreshes complete in under 5 minutes for initial loads and under 1 minute for incremental updates. The system sustains throughput of 186,000+ events per second across all 266 tables and 700 tenants.
Infrastructure cost
By choosing Lambda-based event processing over streaming alternatives, Aderant achieved a 77 percent reduction in pipeline compute costs. The serverless, pay-per-invocation model scales to zero during quiet periods and handles 10x seasonal spikes without pre-provisioned capacity, keeping costs proportional to actual data volume rather than reserved infrastructure.
In production: Multi-tenant operations
The architecture runs in production today, processing data for 700 client environments across 266 source tables. Three aspects of the implementation stand out.
Tenant isolation with shared infrastructure. Each tenant’s CDC events flow through the same Lambda functions and AWS Glue jobs, but Iceberg’s partition-by-tenant structure maintains data isolation. Configuration files drive per-tenant behavior without code changes.
Graceful handling of complex reports. The Expert Bill Report, one of Aderant’s most complex analytical outputs involving multiple dimension tables and fact aggregations, processes 900,000 records in approximately 5 minutes for initial load, with subsequent incremental runs handling only changed records in seconds.
Self-healing watermark management. DynamoDB-based watermarks track the last processed timestamp per table per tenant. If a Lambda function fails, the watermark remains unchanged, and the next invocation reprocesses from the correct point, providing exactly-once semantics without complex distributed transaction logic.
Looking ahead
Aderant plans to continue expanding the tool’s capabilities.
Streaming analytics for high-volume tenants. The Lambda-based architecture supports a hybrid model where tenants with the highest event volumes can migrate to Amazon Kinesis streaming for sub-second latency, while standard tenants remain on the cost-effective Lambda path.
AI-powered analytics. Integration with Amazon Bedrock for natural language querying of the gold layer, so law firm users can ask questions about their billing and matter data conversationally.
Automated data quality. Expanding the validation framework to continuously monitor data consistency between pipeline layers, with automated alerting when discrepancies are detected.
Conclusion
Aderant’s journey from batch-oriented data processing to an event-driven, Iceberg-based pipeline demonstrates what is possible when you combine modern open table formats with serverless compute. The new architecture processes CDC events in single-digit seconds instead of 15-minute batch cycles. It delivers 10–26x faster query performance through native Amazon Redshift tables and reduces infrastructure costs by 77 percent compared to streaming alternatives.
The key insight is that not every table needs the same processing strategy. Aderant uses incremental AWS Glue jobs for straightforward tables and materialized views with Iceberg snapshot comparison for complex analytical patterns. This approach delivers near real-time freshness across all 111 gold tables without rewriting complex SQL logic.
For analytics teams managing multi-tenant SaaS tools, Aderant’s experience shows the value of Apache Iceberg. Its ACID alignment, time-travel capabilities, and schema evolution support make it a strong foundation for production data pipelines at scale.
When an artificial intelligence (AI) agent’s tools start failing (a database query times out, an API returns incorrect data, a search call silently drops fields), what does your agent do? Does it retry, fall back, or acknowledge it can’t complete the task? Or does it present a confident answer built on corrupted data, show the user a raw error, or fail silently with no alert to your operations team?
These aren’t hypothetical scenarios. In production, tool calls fail, networks partition, upstream services degrade, and agent-generated queries return incomplete results. If you’ve never tested how your agent behaves under those conditions, you’re relying on assumptions, not evidence. With AWS Fault Injection Service (AWS FIS), you can test how your Strands agent handles tool-level faults before a real impairment does. The goal isn’t to verify that your tools work, it’s to find out two things: what your agent does when a tool fails or returns incorrect data, and whether you can detect it when it happens.
In this post, you’ll learn how to:
Structure a measurable resilience hypothesis for an AI agent.
Build the observability to tell a safe failure from a silent one.
Solution overview
In this experiment AWS FIS runs a single SSM Automation action that turns fault injection on, holds it for a set duration, then turns it off. The system injects the faults inside the agent, right before or right after the tool call. So you are testing the agent’s own behavior rather than the network or infrastructure around it. The agent keeps serving traffic the whole time. Nothing is redeployed to start or stop a run.
Figure 1: AWS FIS runs a single SSM Automation action, which writes /chaos/{runtime_id}/ in Parameter Store. The agent’s controller reads the SSM parameters on each invocation and injects the configured faults.
The example agent is based on the public pokemon-team-advisor sample from strands-agents/samples, with two tools (get_pokemon and get_move) that return structured JSON.
Two controls separate deploying the fault-injection code from activating it:
Coarse -“is chaos loaded?”. You wire the chaos plugins into the agent constructor with a single line, plugins=chaos_plugins(). This decides whether the runtime can inject faults.
Fine – “is chaos active now?”. Values under /chaos/{runtime_id}/ in SSM Parameter Store, read on every invocation (cached for 10 seconds using a time to live (TTL)), control which faults fire and on what fraction of invocations, driven entirely by AWS FIS.
Each invocation skips fault injection until SSM returns active=true. The Strands Evals SDK already provides the ChaosPlugin for offline chaos testing (documented in the Strands chaos-testing guide). This post adds the ability to run those same faults against a deployed AgentCore runtime (a capability of Amazon Bedrock AgentCore) serving live traffic, controlled by AWS FIS. The experiment artifacts are in the FIS template library.
Two families of fault
Pre-hook faults cancel the tool call before it executes and return an error to the agent (timeout, network_error, execution_error, validation_error). This tests whether the agent detects a failed call and retries, falls back, or acknowledges the failure.
Post-hook faults let the tool run, then corrupt its response (truncate_fields, remove_fields, corrupt_values). This is the more dangerous case. An agent can get a successful tool call carrying bad data, and answer the user confidently without ever telling the user the data was degraded.
Define your hypothesis
Before running the experiment, write down what you expect your agent to do when its tools fail, and name the signals you’ll judge it by:
When tool calls for [agent] are [canceled | corrupted], we expect it to [observable behavior] and to fail safe rather than fabricate. After {x} failed tool calls in {y} minutes | {z} failed tool calls in succession an alarm should be raised and the DevOps team notified within {a} minutes. On recovery, it returns to normal within [time], as measured by [metrics/signals].
After the experiment, you compare actual behavior against this hypothesis, and the gaps are where your agent needs iteration and refinement.
Prerequisites
This walkthrough uses the artifacts from the agentcore-strands-agent-faults experiment in the FIS template library on GitHub. The repo provides the chaos controller module, the SSM Automation document, the FIS experiment template, and least-privilege AWS Identity and Access Management (IAM) policies for each role. You need:
A Strands agent integrated with chaos_plugins() (vendors strands_agentcore_chaos.py and its dependencies: strands, strands-agents-evals, pydantic, and boto3).
The runtime ID of the target AgentCore runtime (resolved automatically from AGENTCORE_RUNTIME_URL).
The SSM Automation document deployed to your account and named ChaosExperiment.
An IAM role for AWS FIS (trusted by fis.amazonaws.com) with the least-privilege policy from the repo.
An IAM role for SSM Automation (trusted by ssm.amazonaws.com) with ssm:PutParameter and ssm:DeleteParameters on /chaos/*.
A chaos-build runtime execution role with ssm:GetParametersByPath on /chaos/*.
The FIS experiment template deployed to your account.
Integrating chaos into your agent
The chaos plugins integrate into your agent constructor with plugins=chaos_plugins(). A complete deployable file:
import logging
from strands import Agent
from strands_agentcore_chaos import chaos_plugins
from bedrock_agentcore.runtime import BedrockAgentCoreApp
from my_tools import get_pokemon, get_move
logging.getLogger("strands_agentcore_chaos").setLevel(logging.INFO)
agent = Agent(
model="us.anthropic.claude-sonnet-4-5-20250929-v1:0",
system_prompt=(
"You are a Pokémon team-building advisor. Use the get_pokemon and get_move tools. "
"If a tool call fails, immediately stop, notify the user which data you could not "
"retrieve, and do not answer from guesses."
),
tools=[get_pokemon, get_move],
plugins=chaos_plugins(),
)
app = BedrockAgentCoreApp()
@app.entrypoint
def invoke(payload):
return {"result": str(agent(payload.get("prompt", "")))}
if __name__ == "__main__":
app.run()
The failure-handling instruction in the system prompt is what produced safe behavior under a fault in our runs. Leave it out and the same fault produces a very different result, as we show in the next section. But a system prompt is a probabilistic mitigation, not a switch. That’s why you verify it with chaos experiments rather than trusting the prompt alone.
Configuring the experiment
Update the default FIS experiment template documentParameters to match your requirements. FaultRate decides whether an individual invocation is faulted, FaultInjections defines what happens to which tools:
The SSM Automation document writes fault_rate, fault_injections, and execution_id first, then sets active=truelast, so no invocation observes a half-written config. On stop, it reverses that order and waits for the TTL cache to drain. The onCancel/onFailure handlers run the same clean disable path if a stop-condition alarm trips. See the FIS template library for the full SSM document and FIS template.
Important:fault_injections keys must match your agent’s registered tool names exactly. Otherwise, the experiment completes “successfully” while doing nothing.
Running the experiment
aws fis start-experiment --experiment-template-id <YOUR_TEMPLATE_ID> --region <YOUR_REGION>
# confirm chaos is active
aws ssm get-parameters-by-path --path /chaos/<YOUR_RUNTIME_ID>/ --region <YOUR_REGION>
# send a burst of traffic
for i in $(seq 1 20); do
agentcore invoke '{"prompt": "Which of these three has the strongest move?"}'
done
What the fault reveals
We ran the same fault (get_move set to timeout, fault_rate=1.0) against two versions of the agent that differ only in their system prompt, with five runs per configuration.
Figure 2: The agent with no failure-handling prompt (Configuration A) made 21 tool calls on the broken tool, then answered from training knowledge. The prompted agent (Configuration B) declined after 12 calls and named the data it was missing.
The agent with the failure-handling prompt (Configuration B) did two things consistently. It cut the retry count. The agent with no failure-handling prompt (Configuration A) used about 1.35x the tool calls on average, rising to 2.5x the unfaulted baseline in its worst run. More importantly, it changed what the agent did when retries ran out. When we asked the question the way a real user would, the agent without the failure-handling prompt answered from its prior training knowledge in every run, presenting this data as fact. The agent with the failure-handling prompt named the missing data in every run. Here is one answer from the agent with no failure-handling prompt, verbatim, from an invocation where everyget_move call had failed:
“I’m experiencing technical difficulties with the move lookup tool. However, based on standard Pokémon move data: Among Mamoswine, Nidoking, and Garchomp, the one that learns the single most powerful move is Nidoking, with Megahorn at 120 power…”
One clause of hedging, then a confident, numerically detailed answer built entirely on aged training data. Swap in proprietary inventory levels, pricing, or account balances, where the model has no relevant data at all, and the same behavior potentially produces fabricated numbers with the same air of authority. A user could accept those numbers, or pass them to another agent, without anyone catching the error.
The same impairment produced three classes of outcome depending on configuration:
Fail safe: detect the failure, decline or add a caveat, show the user no raw error.
Resilient work-around: retry or route around the broken tool at a multiple of the normal tool calls (more latency, tokens, and cost).
Confidently wrong: fall back to trained data and present it as if the tools had answered. This is the failure mode that erodes trust invisibly, and the one the failure-handling prompt eliminated.
Corruption is harder. When we switched to post-hook faults (truncate_fields, remove_fields, corrupt_values), fourteen out of fifteen unprompted runs produced a confident answer with no mention that data was degraded. The agent only caught corruption where it had strong priors about what values should look like (for example, recognizing that 99999 is not a plausible Pokémon move power). On proprietary values, there are no such priors. Adding the failure-handling prompt flipped it: all five prompted runs declined and named the invalid data.
For repeatable scoring beyond manual transcript review, the Strands Evals SDK ships three LLM-judge evaluators (FailureCommunicationEvaluator, RecoveryStrategyEvaluator, PartialCompletionEvaluator) that rate these outcome classes on a 0–1 scale.
Observing the fault
A tool-level fault that your agent handles gracefully is invisible to infrastructure monitoring. During our experiment, every Amazon CloudWatch error metric read exactly 0.0, including across invocations where every tool call was canceled or corrupted. Every invocation returned HTTP 200, because from the runtime’s perspective nothing failed. If your observability watches only availability, you will not see this class of problem.
Mitigations
Approaches to mitigate this failure mode depend on the agent SDK and foundation models you’re using. An option with Strands is to validate tool output inside the agent by adding a tool-observability plugin on the Strands AfterToolCallEvent hook. The plugin validates tool output against a Pydantic contract and emits an Embedded Metric Format (EMF) log line, for example:
from pydantic import BaseModel, Field
class PokemonOutput(BaseModel):
name: str = Field(min_length=4) # catches truncate_fields
pokedex_id: int
types: list[str]
A Pydantic BaseModel turns each annotated attribute into a validation rule, and passing the tool’s output through it raises a ValidationError the moment the data breaks the contract:
Declaring a field makes it required. Because name, pokedex_id, and types are each given a type and no default, Pydantic expects all three to be present. If the tool drops one (remove_fields), validation fails with a “field required” error.
The type annotation checks the shape of the value.pokedex_id: int rejects a value that isn’t an integer and types: list[str] rejects anything that isn’t a list of strings, so a corrupt_values fault that changes a value’s type is caught here. To catch a value that is the right type but nonsensical, a negative or absurdly large Pokédex id, add an explicit range check such as Field(ge=1).
A constraint checks the value itself. Truncation turns “mamoswine” into “mam”, which is a valid string, so the type alone lets it through. It’s the min_length=4 constraint that catches it.
Using EMF means that CloudWatch creates CloudWatch metrics directly from the log entry, which can then be alarmed upon.
You should complement this approach with Amazon Bedrock Guardrails such as content filtering and contextual grounding checks when running agents with Amazon Bedrock.
What about structured outputs? Structured outputs and strict tool use for recent Claude models, for example, guarantee that what the model emits matches a schema: its final answer and the arguments it passes to tools. They say nothing about whether what your tools returned was correct. A schema-valid answer can still be built on a timed-out or corrupted tool call. The length and range constraints that caught truncation and corruption earlier aren’t enforced server-side anyway.
Best practices
Use a dedicated chaos runtime. Don’t inject faults into production. Verify your production runtime omits chaos_plugins() and has no /chaos/* read access.
Engineer the behavior you want, then test it. Write the failure-handling guardrail, then use chaos to prove it holds.
Run each scenario multiple times. Agent responses are nondeterministic. A single clean run is an anecdote, not evidence.
Validate agent output, not just availability. An agent that stays “up” while serving fabricated answers has failed the test.
Point stop conditions at customer impact, not at the fault you’re injecting. Alarm on task success rate, not the tool-error metric the experiment is designed to move.
Cleaning up
The experiment deletes its own parameters when it ends, but surrounding resources persist. To remove everything:
Then detach and delete the three IAM roles and any stop-condition alarm.
Conclusion
The value of this experiment isn’t confirming that your agent keeps running when its tools fail. It’s finding out what it does with bad data, and whether you’d notice. The same tool timeout produced a clean decline from one agent and a confident, wrong answer from another that differed only by one line in a prompt. Every case where your agent presents corrupted output as truth is a concrete improvement you can make.
Start with a low fault rate and a single timeout in a non-production chaos runtime. Fix what breaks. Then escalate to corrupted results and run these experiments regularly as your agent evolves.
With AWS Lambda customer-managed runtimes for Lambda Event Functions (formerly called Lambda functions), you get full control over Lambda runtime contents, updates, access, and lifecycle. You package your runtime once, share it across your organization, and when you update it, Event Functions pick up the change automatically. You can test, schedule, stagger, and monitor the runtime update rollout. If necessary, you can roll back.
In this post, we will explain why you might use a customer-managed runtime, and the core concepts of Lambda runtime management. This includes the runtime publisher and consumer roles, resource model, and update process. We will also cover cross-organization runtime sharing, deletion guardrails, and pricing.
Lambda managed runtimes
Until now, AWS Lambda Event Functions (formerly Lambda functions) ran only on runtimes that Lambda manages. You choose a language, deploy your code, and Lambda takes care of the runtime, including patching and lifecycle management. This model works well, and remains the right choice for many Lambda customers, especially those who are new to serverless.
However, for more advanced customers managing thousands of Event Functions, the Lambda managed runtime can be restrictive. For example, suppose your organization has a standardized security or monitoring extension, enterprise certificates, or even wants to use Lambda with an additional language such as PHP. These components need to be included in each Event Function in an application or organization, in addition to the function code.
With Lambda managed runtimes, you have two options. You can use Lambda layers to distribute shared libraries. These must be deployed with every function, as shown in the diagram:
Figure 1: Using PHP and a monitoring extension with a Lambda managed runtime
Layers follow a pull model, so when you update a layer, you must redeploy every Event Function that uses it to pick up the change. Alternatively, you can use container image packaging to get full control over the runtime contents. But this shifts complexity to every developer on every team. Developers need to understand Dockerfiles, image registries, and container builds, and need to rebuild and redeploy every function to roll out a shared component update. You also lose the simplicity of .zip-based deployment and automatic runtime updates.
How customer-managed runtimes solve this
With customer-managed runtimes you can package your language runtime, certificates, security tools, and monitoring agents into a centrally managed runtime resource, shared by any number of functions.
Figure 2: Using PHP and a monitoring extension with a customer-managed runtime
Application developers reference your runtime in their Event Function configuration, the same way they would reference a Lambda-managed runtime like python3.14. They deploy their code as .zip files, use the same AWS Command Line Interface (AWS CLI) and tools, and receive runtime updates automatically.
When you update the runtime, you update it once. Event Functions pick up the new version at their next cold start, with no per-function redeployments. You can stage the rollout across environments, roll out Region by Region, monitor function invocation success rates, and roll back if something goes wrong.
This model supports a range of scenarios:
Standardize shared components at scale – Give teams in your organization a runtime with your approved security and monitoring tools built in. Update those tools centrally.
Use languages Lambda doesn’t support – Package languages or runtimes such as PHP, Bun, R, or any other language into a customer-managed runtime. Developers use it with the same .zip deployment experience as Python or Node.js.
Control your patching cadence – Apply runtime patches on your schedule, immediately for critical issues or during planned maintenance windows for routine updates. You can also stage the updates, for example across development, test, and production environments.
Extend runtime lifetime – If Lambda deprecates a managed runtime before your organization is ready to migrate, fork it into a customer-managed runtime. Now you can apply your own security patches and deprecate on your own timeline.
Publishers and consumers
Customer-managed runtimes introduce two roles: runtime publisher and runtime consumer.
The runtime publisher owns the runtime. That includes its contents, updates, access control, and lifecycle. The publisher builds runtime images, publishes versions, rolls out updates, and decides who can use the runtime. In an enterprise, this could be a central cloud platform team. Alternatively, an application team could operate an application-specific runtime built on base images from their platform team, or from Lambda.
The runtime consumer is the function developer. Consumers reference the runtime in their Event Function configuration, deploy their code as .zip files, and receive updates automatically. They don’t use or manage the underlying container images. They only write application code.
This separation creates a clean boundary. The runtime publisher focuses on runtime management: patching, security tooling, and compliance. Developers consume the runtime and focus on their business logic.
Resource model
Customer-managed runtimes use three resource types that work together.
Runtime: The top-level resource representing the runtime as a whole, for example, a PHP 8 runtime for your organization. A runtime has a name, an Amazon Resource Name (ARN), and a description. You control access at the runtime level using a resource-based policy. To create a runtime:
aws lambda-core create-runtime \
--name my-runtime \
--description "Describe or link to runtime description" \
--license-info "None"
Runtime version: Represents the contents of the runtime at a point in time. Each version is backed by a container image in Amazon Elastic Container Registry (Amazon ECR) and is immutable, so once created it can’t be changed. To update the runtime, you create a new version. To create a runtime version, reference the ECR image that defines the runtime contents:
Runtime images contain the operating system libraries, language support, a bootstrap script, and the runtime interface client (code that retrieves invoke requests from the Lambda service and calls your function handler). You must grant the Lambda service principal read access to your ECR repository. For details, refer to the runtime image building documentation.
Runtime alias: A named pointer to a runtime version. Event Functions consume the runtime through an alias. When you update an alias to point to a new version, functions using that alias pick up the change at their next cold start. To create a runtime alias:
How you structure your aliases depends on your release process, for example, separate aliases per environment (dev, test, prod), per release track (latest, stable), or semantic version (php8.3, php8.4). Refer to alias strategies in the documentation for common patterns.
Runtimes are Regional resources. You must create a runtime, its versions, and its aliases in each AWS Region where you need them. We recommend using consistent names across Regions so that ARNs differ only in the Region component. Use ECR cross-Region replication to distribute your images, and roll out alias updates one Region at a time to limit the impact of a faulty version.
Consuming a runtime
For function developers, the only change is how you specify the runtime source. In the Lambda console, specify whether the runtime is in the function’s account or shared from a different account, and provide the runtime alias ARN:
Figure 3: The Lambda console Create Event Function page with customer-managed runtime selection
In the AWS CLI (and similarly in AWS CloudFormation), instead of specifying a Lambda runtime identifier like python3.14, you set the runtime to custom and provide the runtime ARN and alias name:
Everything else works the same, including function configuration, invocation, logging, monitoring, layers, and infrastructure-as-code tools. Developers deploy .zip files, use the same CLI, and don’t need to learn containers or new tooling.
Runtime updates and monitoring
As a runtime publisher, you own the update process. Lambda doesn’t patch customer-managed runtimes for you. If you build your runtime from a Lambda base image, you get the operating system, language runtime, and Lambda runtime interface client as a starting point. AWS regularly updates the base images with security patches. You can also build your runtime image from scratch for maximum control.
To patch your runtime, first rebuild your runtime image from the updated base image. You then publish a new runtime version referencing the new image, test it, and roll out the new version by updating your runtime aliases. To create a new runtime version and update an alias:
Lambda publishes two Amazon CloudWatch metrics in the runtime publisher’s account: RuntimeInvocations (total invocations of functions using the runtime) and RuntimeInvocationErrors (invocations that result in errors). You can view these by runtime, runtime version, or runtime alias.
Your runtime updates need to be backward-compatible with existing functions. Lambda strives to provide backward-compatible updates to its base images, which you can use as your starting point. However, as with any change, there’s always the possibility of an unexpected compatibility issue. During a rollout, you can compare the error rate of the new runtime version against the previous version. If the new version shows a higher error rate under similar traffic, it’s a signal to pause or roll back by re-pointing the alias to the previous runtime version. You can also track rollout progress as Lambda replaces execution environments, shifting invocations from the old version to the new one. We recommend creating a CloudWatch alarm on the error rate of each alias and configuring your deployment pipeline to halt when an alarm fires.
Cross-account sharing and trust
For customer-managed runtimes, we expect most usage to be cross-account: the runtime publisher shares a runtime with runtime consumer accounts by applying a resource-based policy on the runtime. You can share with individual AWS accounts, an AWS Organizations organization or organizational unit, or publicly. Consumers in shared accounts also need an identity-based policy granting lambda:AssociateRuntimeAlias permission. Both the resource-based and identity-based policies must allow the action for cross-account access to work. To allow consumers to use runtime management controls to roll back a function to a specific runtime version, they also need lambda:AssociateRuntimeVersion permission. For details and example policies, refer to Sharing and controlling access to customer-managed runtimes.
A runtime publisher can push code into the execution environments of every function that uses their runtime. This is by design. It’s how runtime updates work. The runtime publisher can also ship updates that break your functions, or delete the runtime causing your functions to fail. This means you must trust the runtime publisher the same way you would trust anyone managing your application or running code with your permissions.
Organization administrators can use service control policies (SCPs) to govern which runtimes are allowed in their organization. For example, allowing only runtimes from specific trusted accounts, or blocking all external runtimes entirely. To consume a third-party runtime, you may wish to retain control by using their container images to build a customer-managed runtime that you manage. The image-centric model means you can use standard container tooling for vulnerability scanning, compliance checks, and supply chain security. These are the same tools you already use for your other container workloads.
Deletion guardrails
Deleting a runtime resource can break many functions, including functions in other accounts. Because of this, Lambda enforces built-in guardrails to help prevent and recover from accidental deletion:
Deletion isn’t immediate. Lambda schedules the runtime, version, or alias for deletion with a waiting period you choose, from 7–30 days (default 30). During this period, you can restore the resource.
You can’t delete a runtime version while an alias points to it.
You can’t delete a runtime while it has versions or aliases that aren’t scheduled for deletion. You must delete aliases first, then versions, then the runtime.
When a runtime alias or version is deleted (or scheduled for deletion), functions that use it enter the Inactive state and invocations fail on cold start. If you restore the resource during the waiting period, functions recover automatically, with no redeployment needed.
Before deleting any runtime resource, check the RuntimeInvocations metric to verify usage. You can monitor runtime metrics during the scheduled for deletion window to check whether the pending deletion is causing function invocations to fail.
To manage the runtime lifecycle, you can set a release lifecycle stage (Preview, GenerallyAvailable, or Deprecated) and optionally block new function creation or function updates after a specified date. Refer to runtime lifecycle management in the documentation for details.
Pricing
There’s no additional charge for customer-managed runtimes. Event Functions that use a customer-managed runtime cost the same as functions that use a Lambda-managed runtime. There’s no charge for creating runtime versions or aliases. However, runtime publishers must keep the container image for each runtime version in Amazon ECR for as long as the version exists. Standard Amazon ECR storage pricing applies to these images.
Conclusion
With customer-managed runtimes, platform teams have central control over the Lambda runtimes used across their organization. As runtime publishers, they control the runtime contents, updates, access, and lifecycle. Alternatively, they can publish base images that application teams use to build and manage their own runtimes. Developers keep the .zip deployment experience they’re familiar with and receive runtime updates automatically.
To get started, visit the customer-managed runtimes documentation and the step-by-step tutorial. Customer-managed runtimes are available today across commercial AWS Regions through the Lambda console, AWS Command Line Interface, and AWS CloudFormation.
We would love to hear how you use customer-managed runtimes. Share your feedback in the comments, in the Lambda public roadmap, or reach out through AWS re:Post.
With Amazon EMR Serverless and AWS Glue ETL, you can run Apache Spark applications without provisioning or managing clusters. You submit jobs, the service allocates the compute, scales it during execution, and releases it when the job finishes. Both services deliver a balanced performance profile by default. However, because of different datasets and transformations, customers who want to push further on cost or performance still need to tune Spark settings. Investigating why a specific job is slow or expensive often requires deep Spark expertise: analyzing Spark History Server timelines, shuffle metrics, executor sizes, and task distributions. That work falls to the few Spark experts on the team, and their time is often the bottleneck.
Today we are announcing the general availability of the Apache Spark optimization agent for Amazon EMR Serverless and AWS Glue ETL. The agent analyzes completed Spark job runs and delivers optimization recommendations in minutes, replacing hours of manual analysis by Spark experts. Any engineer can select a cost or performance goal and receive specific configuration changes grounded in evidence from the job’s own Spark telemetry. The agent supports single job-run analysis as well as comparison against a known-good baseline job run.
The Apache Spark optimization agent is available at no additional charge.
In this post, we explain what the agent does, how it works, and how to use it.
What the Apache Spark optimization agent does
The optimization agent analyzes Spark jobs and recommends changes that reduce cost, improve performance, or both. You can access the agent from the EMR Studio UI, AWS Glue Studio UI, or through the Amazon SageMaker Unified Studio MCP Server using any MCP-compatible client such as Kiro. You point it at a completed job run, choose either cost or performance as the intent, and receive recommendations that cite the specific metrics from that run. Often tuning for faster performance also lowers resource usage and cost, but in some cases a faster job requires more resources, which increases cost. The agent optimizes for the goal you choose, cost or performance, and makes sure the one you did not pick does not get noticeably worse. For example, a cost recommendation can make a job run slightly longer, but no more than the normal variation between runs. For larger and more expensive jobs, the agent tightens the threshold further.
There are two ways to analyze a Spark job:
Single job-run analysis. The agent examines one completed run and identifies common sources of inefficiency: data skew, memory pressure, excessive shuffle and disk spill, undersized or oversized workers, suboptimal join strategies, and input layout issues such as small files. Each recommendation shows the Spark properties to change, the current and proposed values, and the telemetry evidence behind the suggestion.
Baseline comparison. When a job that used to meet its targets starts running longer or costing more, compare it against a run that performed well. Provide the current run and the earlier baseline, and the agent compares their configuration, metrics, and stage behavior to pinpoint what changed.
The agent is read-only. It does not change your code or job settings. You decide which recommendations to apply.
How the Apache Spark optimization agent works
The following diagram shows how a request flows from the AWS console or your MCP-compatible client to the remote MCP server, through feature extraction and the recommendation engine, and back to you as recommendations.
Figure 1: How a request flows from the console or MCP client through the recommendation engine and back as recommendations
The workflow consists of the following steps:
State your intent in plain language, such as performance or cost for a completed job run.
Your MCP client or the AWS console sends the job run to the remote MCP server.
The agent reads the run’s Spark History Server telemetry, configuration, logs, and cost through existing APIs, over TLS-encrypted connections, and uses them for feature extraction and context building.
A recommendation engine combines rule-based investigations, intent-based deterministic models, and a knowledge base to find the bottleneck and determine the fix.
You get back labeled recommendations, each with the evidence behind it.
The agent approaches each request with the objective to optimize either performance or cost. It then uses read-only access through AWS APIs and the Persistent Spark History Server or AWS Glue Apache Spark Web UI to gather the Spark configuration and telemetry. Additionally, the configuration inspector collects the job’s settings and compares them against a baseline run when one is provided.
The investigation and recommendation engine looks at these artifacts together to find what is driving runtime and cost. A slow stage may stem from too little parallelism, a skewed join key, memory pressure that forces spill, or a slow upstream read. High cost might come from idle executors or capacity well beyond what the job uses.
Rule-based investigations and an intent-based deterministic model calculate the recommended values. An AI model combines the findings with a knowledge base of the settings most often tuned across millions of Spark jobs on AWS. The agent only recommends changing a setting when the evidence supports it. When cost and runtime trade off against each other, the agent optimizes for the metric you choose and keeps any impact on the other within defined limits.
Note: The agent does not use customer data to train or build the knowledge base.
The Spark optimization agent includes built-in guardrails for personally identifiable information (PII), sensitive data, security, and cost thresholds to make sure recommendations are safe.
Each recommendation is labeled with what it changes:
[infra]: the compute resources your job runs on, such as the EMR Serverless application’s pre-initialized and maximum capacity, the worker vCPU and memory size, or the AWS Glue worker type and number of workers.
[config]: Spark configuration, such as spark.sql.shuffle.partitions, spark.executor.memory, or an Adaptive Query Execution (AQE) setting.
[data]: a change to the underlying data’s physical layout, such as repartitioning a table on a different key or compacting small files.
Each category needs a different level of review. A [config] change can typically be validated in the next run without any code change. A [data] change modifies the job’s actual behavior, or the data it depends on, and should go through the same review and testing discipline as any other production change before it ships.
How to use the Apache Spark optimization agent
You can run the optimization agent from the AWS console or from any MCP-compatible client, such as Kiro, Claude Code, or Codex, through the analyze_spark_workload tool on the Amazon SageMaker Unified Studio remote MCP server. From an MCP client, ask in plain language, and words like “faster” or “cheaper” set the goal. For setup steps, see Use Spark Optimization Agent.
The following steps show how to use the agent in the AWS console.
EMR Serverless
In EMR Studio, select your Application, and choose the Batch job that you want to optimize.
Choose Analyze with AI.
Figure 2: Choosing Analyze with AI for a batch job in EMR Studio
You can select to optimize for Performance or Cost. If you have a previous job run that was faster, you can also choose to Compare with a baseline job. Then, choose View Recommendations.
Review the recommendations in the AI Analysis tab and apply them to the next run.
Figure 3: AI Analysis tab in EMR Studio showing the agent’s recommendations
AWS Glue
Go to the AWS Glue console.
Under ETL jobs, choose the AWS Glue ETL job that you want to optimize.
Choose the Runs tab, select the succeeded job run and choose Analyze with AI.
Figure 4: Selecting a succeeded run on the AWS Glue console Runs tab and choosing Analyze with AI
You can select to optimize for Performance or Cost. If you have a previous job run that was faster, you can also choose to Compare with a baseline job.
Once the AI Analysis has completed, you can view the recommendations, apply the changes, and perform the next run.
Figure 5: Reviewing the agent’s recommendations in the AI Analysis tab on the AWS Glue console
Use cases
The agent works across many situations. The following table shows sample prompts for each goal. In an MCP-compatible client, include the job run ID, and for a comparison, the baseline run ID.
Goal
Sample prompts
Performance
“My job is slow. How do I make this job faster?”
Cost
“My bill is too high.” / “Reduce spend without impacting reliability.”
Baseline comparison
“Why is my job running slowly today?” / “My job used to finish in 10 minutes but now it takes an hour.”
The following three use cases are common situations that data teams run into. Each one describes a scenario, the Spark issues that the agent looks for, and what you get back. They apply to both Amazon EMR Serverless and AWS Glue ETL.
My job is missing its SLA. How do I make it finish sooner?
A nightly orders pipeline that feeds an 8 AM dashboard takes longer as time goes on, and adding more compute power is not always a good practice. You ask the agent to optimize the run for performance. It identifies the bottleneck and then recommends the exact settings to change for that stage so the job finishes sooner.
How can I make this job cheaper?
The bill keeps rising, but every job finishes on time, so the jobs rarely get reviewed for optimization. You ask the agent to optimize the run for cost without significantly affecting the runtime. It compares the executors a job held with what its stages kept busy, exposing over-provisioning, such as a minimum executor count set too high or dynamic allocation left uncapped. It then sizes capacity to actual use. Before you apply these changes, it shows the runtime trade-off between cost and performance. For example, reducing the number of executors can improve resource utilization and lower cost but can also increase the job’s runtime.
Why is this run slower than my baseline run?
A job now takes several times as long on the same datasets compared to previous runs. This is a baseline comparison scenario. You give the agent the slow run and an earlier run that finished on time. Instead of tuning the slow run in isolation, the agent compares the two runs side by side, covering their configuration, metrics, and stage behavior. It isolates the differences that explain the regression, and tells you which settings to restore to get back to baseline performance.
Optimization results
The agent tunes every recommendation to the specified goal and checks to confirm it does not regress the other dimension beyond tolerance.
We tested the Apache Spark optimization agent across hundreds of workloads on Amazon EMR Serverless and AWS Glue ETL. The tests included industry benchmarks (derived from TPC-DS and TPC-H) at various scale factors, along with customer-representative workloads shared by enterprise AWS Glue and Amazon EMR customers.
The evaluation set is made up of Spark workloads that follow common patterns from multiple different industries such as ecommerce, industrial telemetry, manufacturing, and more. Each workload copies the structure of a typical production job, including its join strategies, shuffle sizes, and skew, so the agent’s recommendations can be checked against realistic performance. Together, the workloads cover most production ETL patterns: ingestion, multi-way joins, upserts, slowly changing dimensions, rollups, and full query benchmarks. They run on several open table formats and on standard columnar storage.
The following table shows the ranges of cost improvement observed when invoking the agent with the cost intent and the performance improvement observed with the performance intent. Across hundreds of workloads, the agent reduced cost by 24-31% with the cost intent and improved performance by 23-49% with the performance intent.
Workload
Cost improvement
Performance improvement
Aggregate (across 100+ workloads)
24–31%
23–49%
TPC-DS 3 TB
30–78%
32–44%
TPC-H 3 TB
10–64%
19–33%
The ranges in the table reflect testing across different versions of Amazon EMR Serverless and AWS Glue ETL.
Note: The cost or performance improvement you see depends on your workload, its current configuration, and the version of Amazon EMR Serverless or AWS Glue ETL you are running.
Conclusion
In this post, we introduced the Apache Spark optimization agent for Amazon EMR Serverless and AWS Glue ETL. We showed how the agent analyzes successful Spark runs and recommends changes that reduce cost and improve runtime, how it explains why a run regressed against earlier faster runs, and how each recommendation points back to the measurement behind it. We also walked through how the agent works and different ways to use it.
If a job run fails, the Apache Spark troubleshooting agent under the same MCP endpoint analyzes the run’s logs and Spark event data, identifies the root cause, and explains it in plain language.
To get started, pick a job that you run often or that you want to optimize, and ask the agent how to optimize it for cost or performance. Validate the recommendations in a test run before you apply them in production. If you already use the Apache Spark troubleshooting agent, you can start right away because both agents use the same MCP server.
Teams use Amazon Kinesis Data Streams to ingest data once and make it available to every application that needs to consume it in real time. Some of those applications process related records in sequence, building each result on the records before it. Others process each record independently.
Consider an online store that writes every order event to a stream. One application processes the orders in sequence to catch possible fraud. Its state is a count of each customer’s recent orders. It updates that count with every order and flags any customer who places an unusual number in a short time (stateful processing). The fulfillment application processes each order independently, reserving inventory and starting the shipment. It treats every record as a self-contained unit of work that it can process and retry by itself (stateless processing).
Kinesis Data Streams and the Amazon Kinesis Client Library (KCL) are built for the first job. The KCL assigns each shard to one consumer instance at a time, using a lease table in Amazon DynamoDB. The records for a customer reach the same instance in the order they were written. The application saves its progress as a checkpoint, a position in the shard, so after a restart it resumes from where it left off instead of starting over. Applications that read the stream directly this way are called stream consumers in this post. For the fraud check described earlier, each of these mechanics is what keeps its counts accurate.
The fulfillment application doesn’t need orders in sequence, but because it reads shards, it still gets one consumer instance per shard. An on-demand stream sizes its shards for throughput, not for processing time. With 10 shards, at most 10 instances process orders, no matter how far the application falls behind. A checkpoint is a single position in the shard, so the application can’t mark one order as failed and the next one as done. Teams build that per-record tracking, retries, and failure handling themselves. An order that keeps failing either holds up every order behind it in the shard or is skipped, unless their code sets it aside. They still run the lease table and per-shard custom metrics in Amazon CloudWatch to coordinate and monitor their instances. Other teams copy the records into an Amazon Simple Queue Service (Amazon SQS) queue to get per-record tracking without building it. This means ingesting the same data twice and running a relay in between.
Today, AWS introduced queues in Amazon Kinesis Data Streams. A queue delivers the records of an on-demand data stream to your application and tracks the delivery state of each record. The application acknowledges each record when it’s done instead of checkpointing a position. Consumer instances don’t lease shards, so you add instances to process more records in parallel. The queue redelivers any record that isn’t acknowledged in time, and sets aside records that keep failing as dead-letter records. A record that repeatedly fails stops wasting consumer resources and can be inspected and triaged separately. Because the queue does this tracking and publishes its own metrics, your consumer no longer needs a lease table or per-shard custom metrics. This also lowers what it costs to run. You ingest your data once, and the same stream feeds stream consumers, queues, and managed delivery to streaming tables or Amazon Simple Storage Service (Amazon S3) for batch processing. There’s no relay or second copy of the data. Figure 1 illustrates these three consumption and delivery options.
Figure 1: One stream, three ways to consume and deliver its records
Receiving records through a queue is priced at the same rate as data retrieval from the stream. The cost difference comes from the DynamoDB and CloudWatch charges you no longer pay and from compute you use more efficiently. Each consumer instance can run as many parallel threads as it needs to use its CPU fully. Kinesis Data Streams consumers can reduce the cost of processing data by up to 43 percent by using queues instead of the Kinesis Client Library. Actual savings depend on your workload and configuration.
In this post, we walk through how queues work, explain when to use a queue and when to read the stream directly, show where the saving comes from and how AWS measured it, and introduce a sample repository with working code for the main scenarios.
How queues work
A queue is a Kinesis resource that you create for an existing on-demand stream with CreateQueue. Your consumer application, called a queue consumer in this post, then reads records from the queue instead of from shards. Each running copy of the application is a consumer instance. A queue consumer works in three steps:
Receive – Your application polls the queue with ReceiveQueueRecords and gets a batch of up to 10 records. Each record it receives is hidden from other consumer instances for a period called the visibility timeout, so two consumer instances don’t process the same record at the same time.
Process – Your application does the work that the record represents, such as reserving inventory for one order.
Acknowledge – When it finishes, your application calls AcknowledgeQueueRecords, and the queue doesn’t deliver the record again. If the consumer instance fails before it acknowledges, the visibility timeout expires and any consumer instance can receive the record again.
Consumer instances compete for records: each receives the next available records, so you add instances when the backlog grows. Delivery is at least once, and ordering is best effort.
Where a queue starts and what it tracks
You can create several queues for a stream, one for each consuming application. Queues count toward the stream’s limit on registered consumers, which they share with enhanced fan-out consumers: 50 for an On-demand Advantage stream and 20 for an On-demand Standard stream. A queue’s receive throughput is virtually unlimited, and adding a queue doesn’t change anything for your producers or your existing stream consumers. Each queue also tracks its own delivery state: acknowledging a record in one queue doesn’t affect other queues or the record in the stream.
When you create a queue, you choose where in the stream it starts delivering records:
Starting position
The queue delivers
LATEST (default)
Records that arrive after the queue is created
TRIM_HORIZON
All records still in the stream, starting with the oldest
AT_TIMESTAMP
Records from a point in time that you choose
With TRIM_HORIZON or AT_TIMESTAMP, a new application starts with data that’s already in the stream.
The lifecycle of a record
Figure 2 shows the states of a record in a queue and the operations that move it between them.
Figure 2: The lifecycle of a record in a queue
A record that a consumer instance receives is in flight and hidden from other consumer instances until its visibility timeout expires. The timeout defaults to 30 seconds and can be set up to 12 hours. A consumer instance can extend it with UpdateQueueRecordsVisibility, or set it to 0 to release the record immediately. If the timeout expires before an acknowledgment, the record becomes visible again and its receive count goes up by one.
Handle records that keep failing
A record can keep failing because of its content, for example a malformed payload or an order for a product that no longer exists. It can also fail because of a problem on your side, such as an unavailable downstream service or a bug in your consumer. Dead-letter handling, enabled by default, moves a record to the dead-letter state after MaxReceiveCount receives without an acknowledgment (six by default), so that it stops taking capacity from your consumer instances. You can change the count or disable dead-letter handling with CreateQueue or UpdateQueue, or by using the console. With dead-letter handling disabled, failing records keep returning until their retention period in the stream ends.
You work with dead-letter records through a separate set of operations: ReceiveDeadLetterQueueRecords to receive them, RestoreDeadLetterQueueRecords to return them to the normal receive path with a reset receive count, and AcknowledgeDeadLetterQueueRecords to discard them. These operations have their own AWS Identity and Access Management (IAM) actions, so an operator role can handle dead-letter records without changing your consumer’s permissions. The queue also publishes dead-letter metrics such as VisibleDeadLetterQueueRecords, so you can alarm on them. Acknowledge records that can never succeed to discard them. For records that failed because of a broken dependency or a consumer bug, fix the cause first, then restore them. Like any other record, a dead-letter record expires when its retention period in the stream ends.
Design consumers for at-least-once delivery
A consumer instance can receive a record more than once: after a visibility timeout expires, after a restore, or on rare occasions even after an acknowledgment. Because delivery is at least once, make your processing idempotent. Each record carries a RecordId that stays the same across redeliveries and across queues on the stream. A producer retry, however, writes the same data to the stream a second time, and the duplicate arrives as a new record with a different RecordId. Key your side effects on a business ID, such as the order ID, for example with a conditional write. Where records carry no business ID or you don’t control the producers, fall back to RecordId. Size the visibility timeout to your processing time, and extend it for the occasional long-running record. AcknowledgeQueueRecords returns HTTP 200 with separate Successful and Failed lists, so check the Failed list on every call.
Monitoring a queue
Each queue publishes its own metrics to CloudWatch, including VisibleQueueRecords for records ready to be received, InFlightQueueRecords for records that are received but not yet acknowledged, and matching metrics for dead-letter records. Scale your consumer instances on VisibleQueueRecords, and alarm on VisibleDeadLetterQueueRecords so that you notice failing records early.
Choosing between a queue and a stream consumer
With the addition of queues, Kinesis Data Streams now offers two ways to process a stream’s records in real time, and each application can use the one that fits its work:
Read the stream directly with a stream consumer when handling a record depends on the records before it, as the fraud check’s running counts do.
Receive records through a queue with a queue consumer when each record can be handled on its own, without strict ordering requirements, as reserving inventory for one order can.
The following table compares the two:
Stream consumer
Queue consumer
Typical work
Aggregations, windowed analytics, fraud and anomaly detection
Order fulfillment, per-record inference, record enrichment, search indexing
Ordering
In order for each partition key
Best effort
Parallelism
Each shard is read by one sticky consumer instance of an application at a time
Add consumer instances as needed, independently of the shard count
Progress tracking
The application stores its read position, for example in the KCL lease table
The queue tracks the delivery state of every record
Failed records
Retried in place, which holds up the shard, or skipped and tracked by your code
Redelivered individually, then set aside as dead-letter records
Tooling
KCL, Amazon Managed Service for Apache Flink
AWS SDK
What consuming with a queue costs
Besides the DynamoDB and CloudWatch charges, the saving comes from compute. A KCL consumer instance processes each shard’s records one batch after another, so with I/O-bound processing it spends much of its time waiting. The load also depends on partition keys: if most records share one partition key, that shard is processed in sequence while the instances that lease other shards sit idle. A queue consumer instance can run as many parallel threads as it needs to use its CPU fully, so fewer instances handle the same throughput.
An AWS benchmark measured the saving with a synthetic workload, not a real-world customer workload, for which AWS specified the record size, rate, partition-key distribution, and handler cost. A KCL 3.5.3 fleet and a queue fleet consumed the same On-demand Advantage stream at the same time, at a sustained throughput of 25 MB/s with a warm throughput of 100 MB/s. Each fleet was sized to process 99 percent of records within 10 seconds. The comparison covers data retrieval or queue consumption, DynamoDB, CloudWatch, and Amazon Elastic Compute Cloud (Amazon EC2) at US East (Ohio) prices. It excludes ingestion, which costs the same for both. The benchmark tested one handler profile, with 1 ms of CPU and 10 ms of wait per record. This I/O-bound profile is the most favorable condition for the compute part of the saving, and a CPU-bound handler narrows it. Of the $15.09 saving per TiB, $11.55 comes from DynamoDB and CloudWatch, which don’t depend on the handler. Even with no compute advantage, the saving would still be 33 percent. The KCL fleet ran with its default configuration, including detailed metrics with the shard dimension, which produced 1,580 metric series at 190 shards. If you reduce KCL metrics to the summary level without the shard dimension, this part of the saving shrinks, at the cost of per-shard observability.
How queues in Kinesis Data Streams relate to Amazon SQS
Queues in Kinesis Data Streams are powered by Amazon SQS. Built on that foundation, they use familiar queue concepts such as visibility timeouts, acknowledgments, and dead-letter handling. They’re a capability of Kinesis Data Streams, and you work with them through the Kinesis Data Streams APIs.
Amazon SQS continues to be the place to start for point-to-point messaging between application components, such as buffering requests, decoupling services, and background jobs, where no other application needs the same data.
Choose queues in Kinesis Data Streams when the same records are needed by more than one application. There’s no dual ingest and no relay to operate. Applications that process each record independently receive and acknowledge each record through the AWS SDK, with no KCL, lease table, or shards to manage.
Explore the sample repository
The GitHub repo contains working code for six scenarios, written in TypeScript, with Java for the KCL consumers, and deployed with the AWS Cloud Development Kit (AWS CDK). Each scenario builds on a quickstart with an on-demand stream, an order producer, and a KCL consumer on AWS Fargate, and the README lists the prerequisites and the cleanup steps. The scenarios are the following:
Build your first queue consumer – A receive, process, and acknowledge loop on the AWS SDK alone, with long polling. Shown in TypeScript, and it works the same in any language with an AWS SDK.
Process records safely – An idempotent handler keyed on the order ID, which any at-least-once consumer needs, KCL applications included.
Scale out independently of shards – More consumer instances on Amazon Elastic Container Service (Amazon ECS) than the stream has shards, scaled on the backlog metric.
Handle failures and dead-letter records – A transient error that succeeds on redelivery, and a malformed record that an operator restores or discards.
Consume one stream in more than one way – The fraud check and a fulfillment queue on the same stream, plus a second queue that starts at AT_TIMESTAMP.
Migrate an existing consumer – From a stateless KCL application, and from a relay into an SQS queue.
In the KCL migration, a receive and acknowledge loop replaces the KCL, its lease table, and custom metrics, and the processing logic stays. When the SQS queue behind a relay carries only records from the stream, a queue in Kinesis Data Streams replaces both the relay and the SQS queue. If other applications also send messages to that SQS queue, keep it. The consumer’s API calls map as follows:
Dead-letter state in the same queue, restored with RestoreDeadLetterQueueRecords
Both migrations pick a starting position that skips no records, and tolerate duplicates while old and new consumers overlap.
Conclusion
Queues in Kinesis Data Streams are built for work where each record stands on its own. They scale with your backlog instead of your shard count, track every record for you, and set failing records aside so that they don’t hold up the rest. Stream consumers remain the right choice for work that depends on the order of records. Kinesis queues are powered by Amazon SQS and use familiar queue concepts such as visibility timeouts, acknowledgments, and dead-letter handling. You ingest your data once, and stream consumers, queues, and delivery to Amazon S3 all read from the same stream. If you run stateless KCL consumers, moving them to a queue can also lower your processing cost.
For Regional availability, see Supported AWS Regions. For pricing, see Amazon Kinesis Data Streams pricing. To get started, create a queue for an on-demand stream on the Kinesis console or with CreateQueue, and run the scenarios in the GitHub repo. For more information, refer to Consume records from a stream with queues in the Amazon Kinesis Data Streams Developer Guide. For help with your use case, contact your AWS representative.
About the authors
The collective thoughts of the interwebz
Manage Consent
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional
Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes.The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.