How AWS built Spend Limits: Turning Cost Alerts into Cost Enforcement

In the new AWS experience, you can set an upper limit on your bill. This is the story of the engineering challenges we had to solve to deliver this.

Sr. Principal Engineer

Introduction

For years, developers have asked AWS for a simple promise: let me set a number, and don't let my bill go past it. With spend limits in the new AWS experience, you can now set a monthly dollar limit on a project. AWS tells you as you approach it, takes progressively stronger action to slow your spend, and never charges you more than the limit you chose. You're notified when actual costs reach 50%, 75%, and 90% of your limit, or when you're on track to hit it within 10 days. If you enable optional early cost controls, AWS acts before you reach the limit: about 7 days out it stops new resource launches, 5 days out it pauses idle resources, and 4 days out it pauses your highest-cost active resources. At the limit, AWS pauses the project and stops its resources. Your data is preserved, and raising the limit reactivates the project.

The Spend Limits problem statement is easy to explain. Under the hood, delivering it changed what AWS Budgets is. Until now, Budgets told you about your spend and supported actions that you configured yourself. With spend limits, AWS takes the action for you and takes responsibility for it working. If we're slow and your usage reaches 21 USD against a 20 USD limit, we don't charge you more than 20 USD.

This creates several hard engineering problems. To act on your behalf, we have to make decisions from cost data that is fresh but incomplete, about resources that may be running your application. Act too early and we break something that was working. Act too late and AWS incurs unnecessary cost, because you never pay more than your limit. And the estimate we act on has to match what you're billed. We had to get better data sooner, act early without overreacting, act safely, and prove the quality of our system to ourselves before we touched a single customer project. We also needed to ensure that our system enabled customers to let their agents act without worrying the agent would circumvent the spend limit.

Design tenets

At Amazon, we frequently create tenets that we then use to guide our decision making throughout a project. We wrote the following tenets down early:
  • Never surprise the customer. Every action we take has to be predictable, explained in advance, and reversible.
  • Simple enough to explain. When AWS acts on your behalf, you should be able to tell why. Where a simpler approach is nearly as good, we choose it over a smarter one you can't reason about.
  • Degrade gracefully. Warn first, block new spend next, pause what's idle before pausing what's running, and pause the whole project only at the limit.
  • Build on a proven system. Spend limits are a feature of AWS Budgets, not a new system.

The main design challenges with enabling spend limits

In building the systems that support spend limits, there were five themes we had to tackle throughout our work. These weren't challenges with individual systems - they were all cross-cutting.

Lowering latency from usage to cost

The hardest problem for spend limits was speed. Spend happens in milliseconds, across many services at once. Traditionally, cost data reaches cost-management tools only after bill computation finishes, which can take hours. You can't enforce a limit on a number that's half a day old: by the time it says costs have gone over the limit, they have gone significantly over the limit.

So we built a faster path for cost data. Instead of waiting for complete bills, we collect usage in small increments as it arrives. We chose more granular usage data even when less granular data would have been cheaper to produce. More granularity improves data completeness: at any moment, less of your usage is waiting for a long interval to close, so month-to-date spend is closer to the truth. Forecasts get data points that are finer granularity and fresher, which matters most for new projects with only days of history.

We price incoming usage at AWS's standard published rates, including lower rates that apply as usage grows (e.g., S3's tiered pricing). Because commitment-based pricing (Savings Plans and Reserved Instances) isn't available in the new AWS experience, and spend limits exclude credits, that fast estimate matches the charges that count toward your limit.

Faster pricing alone wasn't enough, because some usage records take time to arrive. For some services, we use an earlier signal: the AWS CloudTrail record of a resource launching tells us it's running, and roughly what it costs, before its usage records arrive. For example, when you launch an Amazon EC2 instance, the CloudTrail record of that launch lets us start counting its cost right away.

These fast estimates are provisional. When usage records come through the traditional billing path, they replace the fast estimates. Reconciling an estimate against the final number isn't new, since AWS has always charged customers on a complete view of cost. What's new is doing that reconciliation much earlier and more frequently. Also, since the fast path runs ahead, if it ever comes back lower than the complete data available at that moment, we fall back to the complete data and log the issue for investigation.

Every time new cost data arrives, Budgets evaluates the project's current month-to-date spend and its forecast for the rest of the month. Current spend drives the hard stop at the limit. The forecast drives the earlier cost controls, because the point of slowing spend down is to act before you hit the limit, not at it.

Following our tenet of simplicity, we chose the simplest forecasting model: project your most recent rate of spend forward. A more sophisticated model might look smarter, but it would be harder to explain why AWS stopped a launch or paused a resource. With a simple projection, you know exactly what we base our decisions on. Think of a car's collision warning: it looks at how fast you're going right now and warns you that if nothing changes, you'll hit the obstacle ahead. Spend limits work the same way. If your recent spend rate would carry you past your limit within the next few days, we act now, while you still have room to change course.

A simple projection has one weakness: it reacts to every spike. Early on, we saw that extrapolating from the most recent cost could push a forecast across a threshold and pull it back shortly after. Left alone, that would block and unblock new launches repeatedly within a few hours. We fixed it the way control systems usually do: we only act on a signal that holds, not on a single reading, and once we take an action, we keep it in place for a cooling-off period instead of lifting it the moment the forecast dips.

Designing for the half-finished action

When automation acts on a customer's resources, the riskiest outcome usually isn't a clean failure. We're more worried about an action that we started on your behalf, and then left half-finished. Imagine we block new launches in your project, you raise your limit, and the system that should lift the block stalls partway through: you're stuck, and nothing is in place to finish the job or undo it. A few principles guided how we built enforcement to rule that out. We consistently separated deciding from doing: deciding what should happen is cheap and safe to repeat, so we re-check it every time new cost data arrives, while carrying out an action is where things can go wrong, so it gets its own retries and a confirmation that it actually happened. Next, we built a mechanism to never lose track of an action in progress: every action has a deadline. If it stalls, it's retried automatically, and if retries don't fix it, an AWS team member is alerted so that they can restore the system to normal operation. Lastly, for every action, we also built a way back: whatever point an action has reached, there's a known way to return your project to normal, where new resources can launch again, even if you change or remove your limit midway.

The same thinking shaped how actions reach into your project:
  • Use controls that are already understood. Blocking new launches uses a standard AWS Organizations service control policy (SCP), managed by AWS. Pausing a whole project goes through AWS's existing account lifecycle path, with the same validations as any other lifecycle change.
  • Tie a step to the steps it depends on. Some steps stand on their own; others only work if something else is in place. Blocking new launches stands on its own, and it's the first step we take. Pausing resources doesn't: a paused resource that can be restarted a minute later is a flimsy barrier, and something an agent might gleefully work around. So a pause always comes with a block on new launches, and the two are coupled: they go on together, share one cooling-off period, and come off together.
  • Start with what the customer will miss least, and focus on actions that make the most difference. Idle resources go first, using Compute Optimizer recommendations and automation that already had the permissions and rollback we needed. If this is insufficient to get the account on a track to stay under the spend limit, only then do we pause the resources driving the most cost. "Pause" means something different for every service, so rather than try to cover every AWS service, we focused on a small set of high-profile ones, and the teams that own each of them defined what a safe pause looks like for their resources. We didn't impose one generic action across all of them.
  • Track every reason for an action, not just your own. A project can be paused for more than one reason at the same time. Say your project is paused because it hits its spend limit, and separately all the projects in your account are also suspended for non-payment. If you raise your limit, the spend-limit reason goes away, but the non-payment reason doesn't, so the project has to stay paused. Before reactivating a project, we check with every system that can pause one, and the project comes back only when none of them still needs it paused.
  • Be clear about the limits of our control. Some costs, such as Amazon S3 storage, can't be gracefully slowed down. For these, we simply rely on the existing account lifecycle path. So if the early steps turn out not to slow cost drivers enough, the hard stop at the limit is still there.

Designing for agents

More and more of the code in new projects is written and deployed by coding agents. That changes what a spend limit has to guarantee. An agent can launch resources faster than a person, retry a failing deployment in a loop, or route around a restriction it doesn't understand. A spend limit is only worth having if it holds against the agent too.
  • The agent can't move the limit. The spend limit lives outside the project the agent works in, and only the account owner can change it, in AWS Settings. An agent working inside the project, with the project's permissions, can't raise it or turn it off.
  • Blocks the agent can't remove. The block on new launches is an AWS-managed policy applied from outside the project, so nothing running inside the project can detach it. In our previous discussion of policies, we emphasized how the blocking new launches SCPs can occur on their own, but pausing resources needs to be coupled to the blocking new launches SCPs to be effective; the reason SCPs are effective at all is that they are applied from outside the project.
  • A bounded worst case. With a limit in place, you can let an agent experiment in a project knowing the most it can cost you is a number you chose.

Handling failure across a pipeline that spans multiple teams

A spend limit decision depends on many hops, from usage collection and cost computation through Budgets evaluation to the systems that block launches or pause resources. Different teams own different parts of the pipeline. Cost updates move through it in waves: each wave carries the latest batch of fresh updates for every project through every hop. If something goes wrong, we need to know quickly, and be able to stop it before it reaches a customer.
  • One orchestrator, explicit hand-offs. A central orchestrator drives each batch of cost updates through the pipeline in waves. Every hop reports back for every project it handles, and a hop that doesn't answer in time counts as a failure.
  • Wait for fresh input, but not forever. Each stage waits for the stage ahead to deliver, up to the time that stage has committed to. If the upstream stage misses that window, the next stage moves on with the latest good input it already has and records which version it used, instead of stalling everything downstream behind one late hop. A slow stage can delay its own output, but not everyone else's.
  • "Nothing to do" needs to be explicit. When a hop correctly does nothing, because a project opted out or there's no cost data yet, it reports success with an explicit reason: skipped because not spend-limited, or skipped because no data. Monitoring watches those reasons too. If a project were to keep coming back "no data" across waves, this would indicate a bug and raise an alarm instead of quietly looking healthy.
  • Watch every hop, wave by wave. Each wave has its own monitoring view across every team's hop, so when an update stalls, any team can see where. A missed hand-off alerts the team that owns that hop, and if the problem repeats across waves, it escalates to get more attention on resolution. On top of the per-hop views, end-to-end monitoring watches the pipeline as a whole, so a slowdown that no single hop owns still gets caught.
  • A switch to stop acting, without stopping thinking. Every action is gated by configuration, so we can turn actions off while the system keeps evaluating and recording what it would have done. That's how we tested our software before launch, and it still exists as a lever we can pull in production, as a last resort, if something goes wrong. Even in that worst case, while we're temporarily not pausing some projects, your bill is still capped at your limit.

How we validated it before acting on customer projects

We had numerous unit tests in our software, but we also knew from experience that this was insufficient to get to confidence in the complete system. To get there, we first ran our entire system against production data but with all actions turned off. Estimated charges matched the final bill to the penny for the overwhelming majority of accounts, and the few differences pointed us to edge cases in the fast estimate, which we fixed before any customer relied on it. We then went beyond the cost-level accuracy to also systematically measure when the actions would fire. The large majority triggered close to the time that the cost crossed the target threshold. The long tail came from services that report usage less frequently, and which empirically almost never have significant cost fluctuations. Lastly, we load-tested continuous operation on production-scale historical data. We ran this wave after wave, at the same pace as production. While every single wave would have succeeded on its own, we found some problems that only appeared when waves ran back to back: a wave that ran long or timed out could leave work behind, and that work spilled into the next wave and kept growing. One-off scale tests didn't catch this kind of bug. Before launch, we fixed this, and now one slow wave can no longer snowball into the next.

Conclusion

For a long time, we thought we could consistently better meet customer needs by providing cost management tools - enabling our customers to react to cost spikes without AWS ever stopping a running application and potentially disrupting a customer's business. With the new AWS experience, we're now providing two different experiences - one for when customers are just at the beginning of using cloud, and one for later in their journey. This enables us to do exactly what customers have been asking for with spend limits, by scoping it to the experience of customers that are just beginning their journey, and likely don't yet have a large number of paying customers. They turn AWS Budgets from a tool that tells you about your spend into one that acts to keep your spend inside a number you choose. Building it taught us lessons that may apply to many other systems that act automatically on someone's resources.

The first lesson is about speed and data. Latency is an end-to-end number. Our ability to economically offer spend limits is only as good as the time between usage and action, and every hop adds to the total time, no matter which team owns it. Teams had autonomy about how they got their work done in their hop, subject to meeting their time budget. To keep latency low, we used the earliest signal we could and reconciled it with a more complete one. Early signals let us act in time, and the traditional billing path fills in what they miss. Neither alone would have been enough.

The second is about decisions and failure. We kept automated decisions simple enough to explain: a simple, steady forecast beats a smarter model that customers wouldn't be able to reason about. When automation acts on someone's resources, every state needs a known outcome and a way out, including the rare ones, like a limit removed in the middle of enforcement. And in a pipeline that spans many teams, every hop needs to say what it did and why, including when that thing is "nothing."

The third is about testing. Every convenient way of choosing test accounts skewed the sample. Finding one that looked like the customers we actually serve took deliberate work that needed to be incorporated in to our project plan.

The foundation we built for spend limits - a near-real-time cost path, an action engine built so nothing is left half-done, and SCP-based enforcements - are ones we plan to build on in future releases.

To experience spend limits yourself, sign up for AWS and  set a spend limit on your project . If you have feedback about this post, submit comments in the Comments section below.

-- John Dunagan and  Divya Arora 
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article