aws-cdk-lib: significantly more memory used as module than commonjs
- Dominant language
- TypeScript
- Stars
- 12.9k
- Forks
- 4.6k
- Avg merge
- 2d 3h
- Merged PRs (30d)
- 83
Description
### Describe the bug
```
~/projects/cdk-test » node --expose-gc test.mjs
HEAP 17.45mb RSS 111.25mb EXT 2.03mb
~/projects/cdk-test ∷ node --expose-gc test.cjs
HEAP 2.91mb RSS 43.34mb EXT 1.07mb
```
test.mjs and .cjs are the same except `import 'aws-cdk-lib` vs `require('aws-cdk-lib)`.
I see similar differences when importing `aws-cdk-lib/core` or `aws-cdk-lib/aws-lambda`.
I don't see similar issues with other large libraries (like @aws-sdk/client-ec2)
### Regression Issue
- [ ] Select this option if this issue appears to be a regression.
### Last Known Working CDK Version
_No response_
### Expected Behavior
Similar memory use between ESM and CJS
### Current Behavior
importing cdk uses more memory than requiring it.
### Reproduction Steps
```
// test.cjs
require('aws-cdk-lib')
const MB = 1024 * 1024
function mb(n) {
return (n / MB).toFixed((2))
}
global.gc?.()
const mem = process.memoryUsage()
console.error(`HEAP ${mb(mem.heapUsed)}mb RSS ${mb(mem.rss)}mb EXT ${mb(mem.external)}mb`)
```
```
// test.mjs
import 'aws-cdk-lib'
const MB = 1024 * 1024
function mb(n) {
return (n / MB).toFixed((2))
}
global.gc?.()
const mem = process.memoryUsage()
console.error(`HEAP ${mb(mem.heapUsed)}mb RSS ${mb(mem.rss)}mb EXT ${mb(mem.external)}mb`)
```
```
~/projects/cdk-test » mise exec node@18 -- node test.mjs
HEAP 21.22mb RSS 84.24mb EXT 1.49mb
~/projects/cdk-test ∷ mise exec node@18 -- node test.cjs
HEAP 4.12mb RSS 40.49mb EXT 0.18mb
~/projects/cdk-test ∷ mise exec node@22 -- node test.mjs
HEAP 27.54mb RSS 110.08mb EXT 2.03mb
~/projects/cdk-test ∷ mise exec node@22 -- node test.cjs
HEAP 3.37mb RSS 43.00mb EXT 1.07mb
```
test.mjs uses significantly more heap and rss
### Possible Solution
_No response_
### Additional Information/Context
_No response_
### CDK CLI Version
N/A
### Framework Version
2.173.2
### Node.js Version
18, 20, 22
### OS
Arch Linux
### Language
TypeScript
### Language Version
N/A (JavaScript)
### Other information
_No response_
Contributor guide
Research direction
Start by running the provided test.mjs and test.cjs reproductions with the listed Node.js versions and compare process.memoryUsage() after garbage collection. Investigate loading aws-cdk-lib, aws-cdk-lib/core, and aws-cdk-lib/aws-lambda through ESM versus CommonJS; done means identifying and reducing the unexplained memory difference, with regression coverage for the measured behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- aws, node.js, typescript
- Domain
- cloud, infrastructure
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100