loading...

re: Help me understand how AWS Lambda reuses object VIEW POST

FULL DISCUSSION
 

Your current approach isn't wrong but it might not be the most "Lambda" way of doing this. Your second example is more in line with what I have seen a lot of other folks use (myself included). The advantage of the second approach is no if statement needed and everything remains initialized in memory across invocations.

The key bit is the function handler and what is outside of it, as shown below.

const myVar = 3;
const myDBConnection = new DbConnection();

export async function handler(
  event: APIGatewayEvent,
  context: Context,
): Promise<APIGatewayProxyResult | void> {
  if (!endpointHandler) {
    await setupBotHandler();
  }

  return await endpointHandler.handler(event, context);
}

When the function is first invoked, Lambda is going to set up the entire context top to bottom. So myVar and myDBConnection will get initialized and then the function handler will be invoked. This is what is commonly referred to as a "cold start", it's the first time the function has been invoked.

However, Lambda optimizes invocations by reusing contexts as long as they meet certain conditions, i.e. they remain "hot". In that scenario, myVar and myDBConnection do not get reinitialized, in fact, that code doesn't get executed again because it's already happened in that context. In this scenario, the function handler is invoked because everything outside of it is already in memory.

 

Could you please explain about certain conditions for remaining 'hot'?

And if lambda decides to not reuse the execution context, will lambda re-initialize everything outside the function handler before executing the function?

Code of Conduct Report abuse