I have a Lambda function that is triggered by API Gateway.
Based on request parameters, this function may call another API endpoint(s).
The URL of the other API endpoint(s) are passed by parameter in the request.
So, for example, I can call my endpoint like this:
And as a result, the Lambda function will at some point call the other API: https://api.example.com/
My real function have some complex logic before calling other APIs, but you got the idea.
There are some cases where the function will call its own endpoint (recursion), but passing different parameters to process some logic, so that it will not cause infinite loop.
But someone may accidentally configure parameters incorrectly so that it will cause an infinite loop, causing the function to be called millions of times per hour, leading AWS charges to the top.
How can I prevent this Lambda function to cause an accidental infinite loop and avoid enormous AWS bills?
Here are some options I have found so far:
You can use a custom HTTP header (for example "CALL_CHAIN_LENGTH") to count and send the call chain length to subsequent API calls.
In the beginnig of your function, check if this header exists. If it doesn't exist, set it to 1. If it exists, increment the value by 1 and send it in the HTTP header before any subsequent API calls. If the value is greater than a theresold, you stop the function and return an error (for example HTTP error 429 - Too Many Requests).
This depends on the application, but if the function logic is simple, you may be able to check if it will lead to an infinite loop by just checking the endpoint URL and params.
Additionally you can create an alarm and send emails in case your lambda was called more than a x times in a time period.