// Version A
export const handler = async (event) => {
const client = new DynamoDBClient({});
return client.send(new GetItemCommand(params(event)));
};
// Version B
const client = new DynamoDBClient({});
export const handler = async (event) => {
return client.send(new GetItemCommand(params(event)));
};
Version B, because the client is created once per environment and reused by warm invocations
The answer is "Version B, because the client is created once per environment and reused by warm invocations".
Code outside the handler runs once, when the environment starts. Warm invocations (later calls to the same environment) reuse what it created. So Version B creates the client once and reuses it. It also reuses the client's HTTP keep-alive connections, so every warm call is faster.
"They behave the same, because Lambda reloads the module on every invocation" is wrong. Lambda does not reload the module on each call, and that is why this pattern works.
"Version A, because code outside the handler runs only at deployment time" is also wrong. That code runs when each new environment starts, not at deployment time.
Read more