1 – Enable throttling in API Gateway:
2 – Configure a proper reserved concurrency for the Lambda function:
3 – Limit the call chain length using a custom HTTP header
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).
4 – If possible, validade the API URL before calling
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.
5 – Use CloudWatch to monitor the number Lambda invocations
Additionally you can create an alarm and send emails in case your lambda was called more than a x times in a time period.