AWS Builder Center
Build a Free Tier Kill Switch: Tiered Budget Alerts That Throttle Your Lambda Functions Automatically

Build a Free Tier Kill Switch: Tiered Budget Alerts That Throttle Your Lambda Functions Automatically

A CloudFormation template that turns a budget email nobody reads into an action that stops the spending, with an audit trail and a one-command restore.

Founder & Director @ OmniAi Global Solutions | AWS UG Kolkata Leader, AWS Community Builder

TL;DR / Key Takeaways

  • AWS Budgets can notify three SNS topics at 50%, 80% and 100% of actual spend. The first two are logged to DynamoDB. The third runs a Lambda that finds every function tagged kill-switch=enabled and sets its reserved concurrency to 0.
  • Tags decide what gets stopped. In my live test the two tagged functions were throttled and the untagged one kept running.
  • It is one CloudFormation template (Budgets, SNS, Lambda, DynamoDB, SSM, IAM) and fits in the Free Tier.
  • I deployed it, ran 14 live checks, recorded a demo from the deployed stack and deleted the stack. The checks, the code and a failure I hit are all below.
  • It is a damage limiter, not a hard cap. Budgets data lags by hours, and only Lambda functions are throttled.


Introduction

A budget alert usually ends in an email. If you are asleep, travelling or not checking, nothing stops. For a learning account with public Lambda Function URLs, a loop or a burst of traffic can run up compute charges before anyone reads the message.
I wanted an alert that acts. This article builds that: tiered alerts, a function that finds its targets by tag, an audit table, and a tested way to turn everything back on. It covers the template, the code, how I tested it, what failed, and how to delete it.

Table of Contents

1. What it does
2. Why I built it
3. How I built it
4. AWS services used
5. Key decisions and challenges
6. Deploy, verify, restore, clean up
7. Live results
8. What I learned
9. FAQ
10. Conclusion

What It Does

Tier
Budget alert (actual spend)
SNS topic
Action
1
above 50%
alert-50
Notifier Lambda writes a WARN item to DynamoDB
2
above 80%
alert-80
Notifier Lambda writes a CRITICAL item
3
above 100%
alert-100
Kill-switch Lambda throttles every tagged function and writes a KILL item
Reserved concurrency is the number of concurrent executions set aside for a function. Setting it to 0 means no execution is allowed, so every invocation is throttled. Deleting the setting restores normal behaviour. Nothing is deleted or redeployed, so the code, configuration, URL and logs all stay for investigation.
The stack includes three demo functions with public Function URLs:  target-a  and  target-b  tagged  kill-switch=enabled , and a  bystander  tagged  disabled . A small console Lambda lets me send requests, publish the three alerts and restore the functions, so the whole flow can be driven and recorded.

Why I Built This

Cost alerts are passive. The cheapest control that is also reversible is to stop the compute and leave everything else alone. Throttling keeps the evidence, and a tag-based selection means the switch only touches functions that opted in. The audit table answers the question that follows any incident: what fired, when, and what was stopped.


How I Built It

Architecture

+--> SNS alert-50 --> Notifier Lambda --> DynamoDB (WARN)
AWS Budgets (actual) ----+--> SNS alert-80 --> Notifier Lambda --> DynamoDB (CRITICAL)
+--> SNS alert-100 --> Kill-switch Lambda
|-- Tagging API: kill-switch=enabled
|-- PutFunctionConcurrency(0) on each match
+-- DynamoDB (KILL)
Console Lambda (Function URL, token) --> reads state, publishes the three alerts, restores



Three topics, three policies

Budgets must be allowed to publish to each topic. I scoped each topic policy to the budgets service principal and my own account, so no other account can use a topic as an alert source:
KillTopicPolicy:
Type: AWS::SNS::TopicPolicy
Properties:
Topics: [!Ref KillTopic]
PolicyDocument:
Version: "2012-10-17"
Statement:
- Sid: AllowBudgetsToPublish
Effect: Allow
Principal: { Service: budgets.amazonaws.com }
Action: sns:Publish
Resource: !Ref KillTopic
Condition:
StringEquals:
aws:SourceAccount: !Ref AWS::AccountId
ArnLike:
aws:SourceArn: !Sub arn:${AWS::Partition}:budgets::${AWS::AccountId}:*



The budget

One budget carries three notifications, each pointing at its own topic. The budget depends on all three policies, because Budgets validates that it may publish when it is created:
MonthlyBudget:
Type: AWS::Budgets::Budget
DependsOn: [WarnTopicPolicy, CriticalTopicPolicy, KillTopicPolicy]
Properties:
Budget:
BudgetName: !Sub ${AWS::StackName}-monthly
BudgetType: COST
TimeUnit: MONTHLY
BudgetLimit: { Amount: !Ref MonthlyLimitUsd, Unit: USD }
NotificationsWithSubscribers:
- Notification: { NotificationType: ACTUAL, ComparisonOperator: GREATER_THAN, Threshold: 100, ThresholdType: PERCENTAGE }
Subscribers:
- { SubscriptionType: SNS, Address: !Ref KillTopic }
# the 50% and 80% notifications follow the same shape



The kill switch

The Lambda asks the Resource Groups Tagging API for every function tagged  kill-switch=enabled , throttles each one, and records the result. A failure on one function is recorded and does not stop the rest:
def handler(event, context):
done, failed = [], []
for n in tagged():
if n == os.environ["SELF"]:
continue
try:
L.put_function_concurrency(FunctionName=n, ReservedConcurrentExecutions=0)
done.append(n)
except Exception as x:
failed.append(n + ": " + str(x)[:80])
msg = "throttled %d: %s" % (len(done), ", ".join(done))
# ... writes a KILL item with this message to DynamoDB


Its IAM role can read tags ( tag:GetResources  only supports a wildcard resource), write to the one audit table, and call  lambda:PutFunctionConcurrency  on functions named after the stack. A tagged function outside that scope shows up as  failed  in the audit item instead of being throttled, so protecting your own functions means adding their ARNs to that statement.

The audit table

The table is on-demand with a TTL attribute, so items expire after 30 days and the table never grows without bound. The notifier writes  WARN  and  CRITICAL , the kill switch writes  KILL , and the console writes  RESTORE .

The console and the two Function URL permissions

The console is a Lambda behind a Function URL. Its API is guarded by a  DemoToken  parameter ( NoEcho , 12 or more letters and digits) compared with  hmac.compare_digest , and its role is limited to the calls it needs. The page itself lives in an SSM parameter: the console code did not fit CloudFormation's 4,096-byte inline limit with the HTML inside it, and moving the page out was cleaner than minifying the code.
A public Function URL needs two resource-based permissions, and my first version had only one:
UrlPermission:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !Ref TargetAFunction
Action: lambda:InvokeFunctionUrl
Principal: "*"
FunctionUrlAuthType: NONE
InvokePermission:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !Ref TargetAFunction
Action: lambda:InvokeFunction
Principal: "*"
InvokedViaFunctionUrl: true


Without the second statement, new function URLs can return 403 even though the first permission looks correct.


AWS Services Used

Service
Role
Cost note
AWS Budgets
One budget, three actual-spend notifications
The first budgets are free
SNS
Three topics, one per tier
Free Tier covers the demo
Lambda (arm64, 128 MB)
Notifier, kill switch, console and three demo functions
Free Tier covers the demo
DynamoDB (on-demand)
Audit trail with a 30-day TTL
Free Tier covers the demo
SSM Parameter Store
Holds the console page (standard parameter)
No charge for standard parameters
Resource Groups Tagging API
Finds functions by tag
No charge
CloudWatch Logs
Function logs, 7-day retention
Retention keeps storage minimal
IAM
One role per function, least privilege
No charge
I did not use API Gateway, S3 or a state machine. The alert path needs none of them.

Key Decisions and Challenges

Throttle instead of delete
Deleting a function or a stack is irreversible and loses the evidence. Reserved concurrency 0 is reversible with one command and keeps logs and configuration.
Tags instead of a hard-coded list. A hard-coded list means editing the template for every new function. A tag lets a function opt in on its own, and the live test shows an untagged function is left alone. The cost is that tag changes are an access path: anyone who can tag can add a function to the kill list, so tagging permissions deserve care.

Budgets Actions versus a Lambda
Budgets has a native actions feature that applies IAM policies or service control policies. I chose a Lambda because it can target individual functions, which is the smallest blast radius. The trade-off is that I own the code and its permissions.

Three topics instead of one router
A Budgets message is text, and I did not want to parse it. Three notifications with three topics means each subscriber knows its tier from where the message arrived.

Actual spend only, no forecast
Forecasted notifications need usage history before Budgets can forecast, so a new account would not exercise them. I left them out and say so in the README.

A deploy failure I hit: one-letter environment variables
My first deploy failed while CloudFormation was creating the change set, with the message "The following hook(s)/validation failed: [AWS::EarlyValidation::PropertyValidation]". The message alone says little. The  describe-events  API with the change set name listed the real cause:  Unsupported property [T]  (and  [A] ,  [N] ,  [U] ) at  /Resources/ConsoleFunction/Properties/Environment/Variables . Lambda environment variable names must start with a letter and have at least two characters, and I had used single letters to keep the inline code short.  validate-template  does not catch this because it checks syntax, not resource property rules. I renamed the variables and added a test that checks every environment variable name in the template:
aws cloudformation list-change-sets --stack-name kill-switch
aws cloudformation describe-events --change-set-name <name> --stack-name kill-switch


Budgets data lags. Budgets updates spend data only a few times a day, so the switch limits damage after the fact. It is not a hard cap and does not replace watching a risky workload.
Testing without spending. I did not want to cause a real overage. Publishing to the same topics Budgets uses exercises everything after Budgets: SNS delivery, the Lambda permissions, the tag lookup, the IAM policy, the throttle and the audit write. The one piece it does not exercise is Budgets itself.

Deploy, Verify, Restore, Clean Up

Deploy:
aws cloudformation deploy --template-file template.yaml --stack-name kill-switch --capabilities CAPABILITY_IAM --region us-east-1 --parameter-overrides MonthlyLimitUsd=1 DemoToken=<12+ letters and digits>
aws cloudformation describe-stacks --stack-name kill-switch --region us-east-1 --query "Stacks[0].Outputs"

Verify from the CLI:
aws sns publish --topic-arn <KillTopicArn> --message "simulated 100% alert" --region us-east-1
aws lambda get-function-concurrency --function-name kill-switch-target-a --region us-east-1


The concurrency of the two tagged functions reads 0, and  kill-switch-bystander  has none. Calling the tagged functions' URLs returns 429.
Restore:
aws lambda delete-function-concurrency --function-name kill-switch-target-a --region us-east-1
aws lambda delete-function-concurrency --function-name kill-switch-target-b --region us-east-1

Clean up:
aws cloudformation delete-stack --stack-name kill-switch --region us-east-1
aws cloudformation wait stack-delete-complete --stack-name kill-switch --region us-east-1


Everything is in the stack, so deleting it removes the budget, topics, subscriptions, functions, roles, table, parameter and log groups.

Live Results

I deployed the stack to us-east-1, ran a script that drives the live console API, and recorded a 118-second demo of the deployed console with Playwright. The 14 live checks all passed:
PASS starts with no throttle on any function
PASS all three functions answer 200
PASS 50% alert is audited in DynamoDB
PASS 50% alert throttles nothing
PASS 80% alert is audited in DynamoDB
PASS 80% alert throttles nothing
PASS 100% alert throttled both tagged functions (concurrency 0)
PASS untagged bystander is NOT throttled
PASS kill action is audited
PASS tagged functions return 429 and the bystander returns 200
PASS restore removes the throttle
PASS all three functions answer 200 again
PASS restore is audited
PASS wrong token is rejected (403)

The audit table after the kill alert shows the tag lookup working:
10:16:18 KILL throttled 2: kill-switch-target-b, kill-switch-target-a
10:16:06 CRITICAL simulated crit alert
10:15:52 WARN simulated warn alert

One limit of the test: the alerts come from publishing to the topics, not from real spend crossing a limit.


Screenshots














Five captures from the live console: all functions running, the 50% alert audited, the 100% alert with two functions throttled and the bystander running, requests rejected with 429, and everything restored.

What I Learned

·  validate-template  is not enough. Early validation checks resource properties at change set creation, and  describe-events  shows the real reason.
· A public Function URL needs two permission statements.
· Tags make the target list self-service, and an untagged control function is the cheapest proof that the selection works.
· Reserved concurrency 0 is a clean, reversible off switch, and an audit table makes it easy to explain afterwards.
· The honest framing matters: this reduces damage, but it is not a guarantee.

FAQ

Will this stop all my AWS charges?
No. It only throttles Lambda functions that carry the tag. Other services keep running and billing.
Why not a hard spending cap?
AWS does not offer one for a standard account, and Budgets reports spend with a delay, so any automation built on it reacts after the fact.
How do I protect my own function?
Tag it  kill-switch=enabled  and add its ARN to the  lambda:PutFunctionConcurrency  statement of the kill-switch role.
How do I turn the functions back on?
Run  delete-function-concurrency  on each, as shown above, or use the console's Restore button.
Is the Function URL safe?
The demo functions are public by design. Do not put real traffic behind them.

Conclusion

A budget alert becomes much more useful when it can act. With one template, three Budgets notifications, three topics, a tag lookup and a function that sets concurrency to 0, an overspend turns into a reversible throttle with an audit trail. I deployed it, triggered every tier, restored the functions and deleted the stack, and the live checks and the demo video are the evidence.

Call to Action

Deploy the template in a learning account, tag a function, and run the 100% test alert. Then widen the IAM statement to the functions you actually want protected.

About the Author

Soumyadeep Mandal builds small, low-cost AWS projects and writes about the engineering decisions behind them.

👉 Let's Connect:  LinkedIn  ·  GitHub  ·  X (Twitter) 

Related Reading:
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