WeCanBeFriends
WeCanBeFriends

Reputation: 691

How would I create a global Counter for AWS Lambda functions?

If I wanted to launch a lambda function every 2 minutes, that makes a call to an api with an index number. How would I store the index number for lambda to read upon initialisation and increment it by one every time the lambda function makes a successful api call?

I think that having a dynamo table just for a counter is overkill.

Upvotes: 3

Views: 6753

Answers (3)

Hugodby
Hugodby

Reputation: 1183

Make your lambda handler callback/throw an error if the API call fail. Example for JS :

export.handler = function(event, context, callback) {
  apiCall().then(resp => callback(null, resp).catch(err => callback(err));
}

Using CloudWatch you can get metrics about the lambda invocation and error. By using a math expression you can do invocation-error that will give you the number of successful call. You can define the period and the time frame.

Lambda Counter

If you need programmatic acces use the AWS CLI or AWS SDK. AWS CLI get-metric-data

Upvotes: 0

Exelian
Exelian

Reputation: 5888

Thinking out of the box, you could log messages to CloudWatch Logs. You could then create a metric filter to get an actual value.

You can even trigger CloudWatch events with this.

Upvotes: 0

Noel Llevares
Noel Llevares

Reputation: 16067

I would argue that using something else other than dynamoDB would be overkill.

DynamoDB is made for this exact purpose. And it is virtually free for your use case. And will only add around more or less 10ms to your run time. Very negligible compared to the cold starts your Lambda will be getting.


If you really want to trim both your DynamoDB cost and your Lambda runtime, you can cache the counter inside the Lambda container (outside your handler).

Assuming, there are no concurrent invocations (triggered via scheduled events only), I would do something like this for each invocation:

  1. Check for cached counter value.
  2. If counter == 0, read value from DynamoDB. If counter > 0, use that value.
  3. Do whatever you want to do.
  4. Increment counter in DynamoDB and the cached value.

Upvotes: 7

Related Questions