Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does AWS Lambda cache API responses?

My Lambda function invokes CloudWatch describe-alarms API. Then those alarms are removed. I'm using CloudWatch Cron Event as a trigger.

The impression I have is that responses with alarms are cached, that is even if they are deleted are still being appeared.

Is there any caching system within AWS Lambda?

like image 556
YasiuMaster Avatar asked Dec 12 '17 08:12

YasiuMaster


2 Answers

It's your code that's caching the response. Not Lambda.

To fix it, you have to fix your code by making sure that you invoke the API inside your handler and return it without storing it outside your handler function's scope.

For illustration purposes,

Don't

const response = callAnApi()

async function handler(event, context, callback) {
  // No matter how many times you call the handler,
  // response will be the same
  return callback(null, response)
}

Do

async function handler(event, context, callback) {
  // API is called each time you call the handler.
  const response = await callAnApi()

  return callback(null, response)
}

Reference: AWS Lambda Execution Model

Any declarations in your Lambda function code (outside the handler code, see Programming Model) remains initialized, providing additional optimization when the function is invoked again. For example, if your Lambda function establishes a database connection, instead of reestablishing the connection, the original connection is used in subsequent invocations. We suggest adding logic in your code to check if a connection exists before creating one.

like image 141
Noel Llevares Avatar answered Sep 21 '22 23:09

Noel Llevares


There is no caching mechanism in AWS Lambda to my knowledge,

That said, after a (successful) request the container Lambda created is "frozen" to preventing it from doing "async" or "background" work. A subsequent request will reuse the container and pass the new event to your function handler. This container will remain in the cluster, ready to be reused and serve requests so long that it isn’t idle for too long, after which it may be discarded entirely. These details are unspecified by AWS.

Because the container sits around waiting for subsequent requests and the memory allocated to it does not magically disappear each time, we can store data for future requests. (But would not recommend it)

like image 22
jarnohenneman Avatar answered Sep 20 '22 23:09

jarnohenneman