- Newest
- Most votes
- Most comments
Your approach is on the right track, but there's a key issue with how you're handling asynchronous initialization in Lambda with provisioned concurrency.
When using provisioned concurrency, Lambda initializes the execution environment ahead of time, but there's a critical detail about how asynchronous code behaves during initialization. The initialization phase isn't guaranteed to wait for asynchronous tasks to complete unless you use specific patterns.
For Node.js functions, the recommended approach is to deploy your code as an ECMAScript module (ES module) and use top-level await to ensure all initialization is completed during the function's INIT phase. This ensures that your asynchronous initialization tasks are fully completed before any handler invocations.
Here's how you should modify your approach:
- Use ES modules by either:
- Changing your file extension to
.mjs - Or specifying
"type": "module"in your package.json
- Use top-level await in your initialization code:
// Top-level await (only works in ES modules) console.log("Warmup: Fetching secrets"); const secret = await fetchSecretFromSecretsManager(); console.log("Warmup: Fetching database"); await connectToDatabase(secret.databaseConfig); console.log("Warmup: complete"); // Export your handler export const handler = async (event) => { // Your handler code };
Without using ES modules and top-level await, your asynchronous initialization tasks may not complete during the INIT phase, which explains why you're seeing the initialization process pause after the first async call and only resume when the first actual invocation occurs.
This approach will maximize the effectiveness of provisioned concurrency by ensuring all initialization is truly completed during the INIT phase, eliminating cold start latency from your function invocations.
Sources
Building Lambda functions with Node.js - AWS Lambda
How Smartsheet reduced latency and optimized costs in their serverless architecture | AWS Architecture Blog
Configuring provisioned concurrency for a function - AWS Lambda
I started down this path and gave up at the 80% mark because it was turning into a bit of work and I couldn't find any documentation that it would help. But I'll go back to this and report results.
answered a year ago
I confirmed that this is correct. I did a quick test version of my lambda that mocks a few delays and saw it complete fully before initializing the lambda.
answered a year ago
Relevant content
asked 2 years ago
asked 3 years ago
- AWS OFFICIALUpdated 4 years ago
