Lambda cold starts increase to 8–12 seconds after migrating to Node.js 20
Problem
After migrating AWS Lambda functions from Node.js 18 to Node.js 20, INIT_DURATION in CloudWatch logs jumps from ~400ms to 8–12 seconds. Warm invocations are normal speed. The regression is caused by Node.js 20 changes to module loading combined with webpack-bundled code that initializes all modules eagerly, including heavy AWS SDK v2 imports that are not tree-shakeable.
Error Output
INIT_DURATION: 11423.45 ms DURATION: 234.12 ms MAX_MEMORY_USED: 312 MB
Unverified for your environment
Select your OS to check compatibility.
1 Fix
Switch to esbuild bundling and tree-shake AWS SDK v3
Webpack bundles include all imported modules eagerly. AWS SDK v2 is not tree-shakeable. Moving to esbuild with AWS SDK v3 per-client imports and --external:@aws-sdk/* (excluding the runtime-available SDK) reduces bundle size and init time dramatically.
Trust Score
3 verifications
- 1
Switch from AWS SDK v2 to v3 per-client imports
Replace monolithic SDK import with specific clients:
typescript// ❌ SDK v2 — not tree-shakeable, large bundle import AWS from 'aws-sdk' const s3 = new AWS.S3() // ✅ SDK v3 — tree-shakeable, import only what you need import { S3Client, GetObjectCommand } from '@aws-sdk/client-s3' const s3 = new S3Client({ region: 'us-east-1' }) - 2
Bundle with esbuild and exclude AWS SDK
AWS SDK v3 is available in the Lambda runtime — exclude from bundle:
bashnpx esbuild src/handler.ts \ --bundle --platform=node --target=node20 \ --external:@aws-sdk/* \ --minify --outfile=dist/handler.js - 3
Move SDK client initialization outside handler
Module-level code runs once per container, not per invocation:
typescript// Module level — runs once (warm invocations reuse this) const s3 = new S3Client({ region: 'us-east-1' }) export const handler = async (event) => { // s3 already initialized }
Validation
Check INIT_DURATION in CloudWatch Logs Insights. Should drop from 8–12s to under 500ms.
Verification Summary
Sign in to verify this fix
Environment
- Product
- AWS Lambda
- Version
- Node.js 20
- Environment
- production
Submitted by
Alex Chen
2450 rep