Home > Enterprise >  Invoke a lambda function after a delay - but be able to cancel it if required
Invoke a lambda function after a delay - but be able to cancel it if required

Time:01-06

I'm looking for some advice on how best to implement the following (abstracted):

Let's say I have two lambda functions:

  • A - console.log('hello');
  • B - console.log('world')

Acceptance Criteria:

  1. User clicks a button, it "queues" up a lambda function A which fires after a delay e.g. 1 minute.
  2. If the user clicks another button within that 1 minute, it will cancel the queued execution of lambda function A and invoke lambda function B.

I see that there are AWS Step Functions that could do this, but is that the best practice for the above use case?

Edit: Idea of implementation:

  1. Call step function from API Gateway, in the response return executionId to store on FE.
  2. Step function "waits" to invoke lambda A.
  3. If user clicks another button - cancel step function based on executionId and fire separate lambda B.

Is that a good approach?

CodePudding user response:

This is a very open ended question because there are lots of different ways you can achieve this.

  1. You can use Step Functions like you mentioned.

  2. You can use your own server to simply handle the queue/cancel logic.

  3. You can add a third Lambda function called "cancel". If the user cancels the queue, you can invoke the third Lambda function to update some database value (ex: DynamoDB). In Lambda function A, you can check that value first and do nothing if the user already cancelled.

I'd probably go with option 2 if the use-case involves a server.

If not, option 3 seems easier than setting up a State machine (Option 1).

CodePudding user response:

You can use CloudWatch Events Lambda. When the user click on the button, you can create a cloudwatch event to trigger your lambda A function after 1 min. When it click button again, within that 1 min, you can trigger a lambda B function that will delete the cloudwatch event and run your code.

  • Related