Automatically Shutdown Your API on Amazon API Gateway When It Breaches a Certain Spending Threshold

Amazon API Gateway provides usage plans with quotas that can be used to limit the number of requests to your API. Quotas are enforced on a per-customer basis so a quota of 10K/month will allow 10K requests from a single customer/consumer of your API. This is the proper design for most real-world API projects.

But what if you’re building small-scale projects or personal projects where the cost incurred to you by your API in your AWS account is the biggest concern. What if you have a hard spending limit for API Gateway in your AWS account & you’re OK with shutting down the API for everyone as soon as the spending limit is reached. This can be achieved by creating an AWS Budget as shown below.

Start by visiting & click Create a Budget:

In the next screen, set a budget amount & a filter for API Gateway:

In the next screen, set an alert threshold & provide an SNS topic that AWS Budgets can publish to:

Finish creating the budget, head on over to the SNS topic you provided above & create an AWS Lambda subscription to the topic. The Lambda function can then go & disable the API by zeroing out the method throttling limits of the API’s stage, as shown below:

This can be done using the AWS SDK & programming language of your choice or if you prefer to use the AWS CLI from a Lambda function to do the same, create a Bash Lambda as described here & use the following AWS CLI command in it:

aws apigateway update-stage \
--rest-api-id rxb7jktrj6 \
--stage-name my-stage \
--patch-operations \
aws apigateway update-stage \
--rest-api-id rxb7jktrj6 \
--stage-name my-stage \
--patch-operations \

Similarly, you can also create & schedule another Lambda function to be run on the first day of every month that resets the throttles so everyone can use the APIs again.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.