user2148750
user2148750

Reputation: 3

How to limit the number of times an AWS Lambda Function can be triggered within a specific timeframe

I’m working to build an automated process sends a PUT to a rest API when an object is detected by the DeepLens.

DeepLens → IoT → SNS → Lambda → External Rest API

DeepLens is performing object detection. I am running IoT Rules that sends a message to an SNS topic when specific objects are detected. The SNS topic sends an SMS, an Email and triggers a Lambda function. The Lambda function performs a PUT against an external rest API.

I am trying to limit the number of times the lambda function can perform the PUT to once per 60 seconds. Example Lambda code below if

import http.client
import mimetypes
def lambda_handler(event, context):
  conn = http.client.HTTPSConnection("api.who.what")
  payload = " {\"id\" : \"SANITIZED\", \"duration\" : 60}"
  headers = {
    'Authorization': 'Bearer SANITIZED',
    'Content-Type': 'text/plain'
  }
  conn.request("PUT", "/1/get/going/start", payload, headers)
  res = conn.getresponse()
  data = res.read()
  print(data.decode("utf-8"))

Upvotes: 0

Views: 252

Answers (1)

Mark B
Mark B

Reputation: 200511

In this case I would have the SNS topic send the message to an SQS queue instead of directly to Lambda. Then, instead of using the SQS-Lambda integration which can't be limited to one Lambda invocation per minute, I would configure the Lambda function to be invoked exactly once per minute by CloudWatch Events.

Finally, each time the Lambda function is invoked I would have it check for an available message on the SQS queue, and retrieve at most one message from the queue, process that message, remove the message from the queue, and exit.

Upvotes: 2

Related Questions