Next.js expands request.body in memory
Nobody has claimed this yet.
- Dominant language
- JavaScript
- Stars
- 142k
- Forks
- 32.4k
- Avg merge
- 2d 14h
- Merged PRs (30d)
- 351
Description
Link to the code that reproduces this issue
https://github.com/mtsmfm/nextjs-memory-issue
To Reproduce
- clone https://github.com/mtsmfm/nextjs-memory-issue
- npm install
- npm run dev
- fallocate -l 100M 100mbfile
- curl localhost:3000/debug -X POST -F 'file=@./100mbfile'
- fallocate -l 1G 1gbfile
- curl localhost:3000/debug -X POST -F 'file=@./1gbfile'
Current vs. Expected behavior
I expect request.body behaves like a stream and it consumes fixed amount of memory.
But currently Next.js consumes 300MB+ for 100MB file and 1200MB+ for 1GB file.
Actually with plain http.createServer, it only consumes ~40MB on my machine.
https://github.com/mtsmfm/nextjs-memory-issue/blob/4d1a347f2e59c4f3ae0b3f775f47327088bbc1b0/plain.mjs#L63-L79
I guess one of the cause is conversion from http.IncomingMessage to Request class.
https://github.com/vercel/next.js/blob/v14.0.4/packages/next/src/server/web/spec-extension/adapters/next-request.ts#L99
https://github.com/mtsmfm/nextjs-memory-issue/blob/4d1a347f2e59c4f3ae0b3f775f47327088bbc1b0/plain.mjs#L24
https://github.com/mtsmfm/nextjs-memory-issue/blob/4d1a347f2e59c4f3ae0b3f775f47327088bbc1b0/plain.mjs#L81-L97
Verify canary release
- I verified that the issue exists in the latest Next.js canary release
Provide environment information
Operating System:
Platform: linux
Arch: x64
Version: #1 SMP Thu Oct 5 21:02:42 UTC 2023
Binaries:
Node: 20.9.0
npm: 10.1.0
Yarn: 1.22.19
pnpm: N/A
Relevant Packages:
next: 14.0.5-canary.7
eslint-config-next: N/A
react: 18.2.0
react-dom: 18.2.0
typescript: 5.3.3
Next.js Config:
output: N/A
Which area(s) are affected? (Select all that apply)
Not sure
Additional context
No response
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the linked reproducer and its plain.mjs comparison, following the listed npm and curl steps to measure memory use for 100MB and 1GB uploads. Then read packages/next/src/server/web/spec-extension/adapters/next-request.ts around line 99 and compare the IncomingMessage-to-Request conversion. Done means the reproduction no longer expands request.body proportionally beyond the expected streaming behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, next.js, node.js
- Domain
- api, backend
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100