15

I have an API Gateway with Lambdas behind, for some of the endpoints I want to schedule an execution in the future, to run once, for example the REST call was made at T time, I want that lambda to schedule an execution ONCE at T+20min.

The only solution I found to achieve this is to use boto3 and Cloudwatch to setup a cron at the moment the REST call was made, send an event with the payload, then when the delayed lambda runs, it removes the rule.

I found this very heavy, is there any other way to achieve such pattern ?

Edit: It is NOT A RECURRING Lambda, just to run ONCE.

e-nouri
  • 2,576
  • 1
  • 21
  • 36

2 Answers2

14

One option is to use AWS Step Functions to trigger the AWS Lambda function after a given delay.

Step Functions has a Wait state that can schedule or delay execution, so you can can implement a fairly simple Step Functions state machine that puts a delay in front of calling a Lambda function. No database required!

For an example of the concept (slightly different, but close enough), see:

John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
  • 2
    Thank you @John for your answer, will I be billed for the delay ? or just the actual execution time only that counts ? – e-nouri Jul 08 '19 at 15:54
  • 3
    AWS Step Functions is billed as "$0.025 per 1,000 state transitions". The delay probably triggers a state transition, so it would be $0.000025. There is no Lambda cost for the delay because Lambda is not being used during the delay. – John Rotenstein Jul 09 '19 at 04:13
  • 1
    Thank you this is way better than the Cloudwatch solution. – e-nouri Jul 09 '19 at 05:00
1

A much more efficient solution than step functions are SQS message timers

https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-message-timers.html

With this you can set a delay for a message when sending it (DelaySeconds property). The message will only become visible to the consumer when the delay expired.

The handler on the other side consuming this SQS message is not aware of this delay and processes the message like any other SQS message.

From the Javascript SDS V3 docs of the DelaySeconds property

The length of time, in seconds, for which to delay a specific message. Valid values: 0 to 900. Maximum: 15 minutes. Messages with a positive DelaySeconds value become available for processing after the delay period is finished. If you don't specify a value, the default value for the queue applies. When you set FifoQueue, you can't set DelaySeconds per message. You can set this parameter only on a queue level.

Mathias Dpunkt
  • 11,594
  • 4
  • 45
  • 70
  • Sorry, but if the question specifically mentions "T+20 Minutes", then an answer limited to 15 minutes is not a solution… I got to this question exactly because 15 minutes are not enough (this is actually much nicer on Azure, where you can just schedule a message for any future UTC time). – Henning Jul 31 '23 at 10:58