Invoking a Lambda function every 5 seconds
Thought I'd still answer this.
Your whole problem is that serverless is not a great fit for near constant workloads. They are more designed for quickly scaling in and out. But if that isn't your use-case then you will almost certainly be better off cost wise using an ec2 instance, you can even reserve one. But I do get that you lose the high-availability and some of the other benefits of Lambda, which might want you to still go with this approach.
If you want to use a sledge hammer to make this approach work you could use a StepFunction. StepFunctions can wait in terms of seconds, but the only catch is that they are not suppose to run indefinitely and will die after 1 year, so your StepFunction will need to start another StepFunction before it dies, or you will have to by some other mechanism, i.e. cloud watch alarms.
This approach also costs a bit of money for the number of invocations you are talking about, would ring up a cost of over
(31,540,000 [seconds/year] / 5 [seconds/invocation] x $0.000025 = $157.7)
Plus your Lambda Costs, (and I think you actually need 2 state transitions so I think you double that figure)
Might be fine if you are only going to run 1. But running lets say 100 would be well over 10k! Most certainly an ec2 instance will cost you less.
you can use step functions and lambda for that - look at https://aws.amazon.com/blogs/architecture/a-serverless-solution-for-invoking-aws-lambda-at-a-sub-minute-frequency/
Although I can not recommend this way, but if you really need to execute a Lambda function every 5 seconds, you can try this:
- Create a Lambda function A which is executed every minute.
- Create a Lambda function B which is triggered every 5 seconds by Lambda function A. (A triggers B, waits 5 seconds, triggers B, waits 5 seconds, ...)
- Stop Lambda function A after approximately one minute. (You can read the remaining miliseconds from the context object => if you reach >55 seconds, stop execution)
Please carefully consider if you really need this.