Streaming an upload into sharp saved me about 9% of peak memory, not the order of magnitude people expect. Eight parallel uploads of a 65.5 MB PNG peaked…

Streaming an upload into sharp saved me about 9% of peak memory, not the order of magnitude people expect. Eight parallel uploads of a 65.5 MB PNG peaked at 1,533 MB when I buffered them and 1,398 MB when I piped them. The same eight uploads were refused at 85 MB by checking Content-Length before reading a byte. The cheap check beat the clever one. Below is the server I tested, the five cases, and what to put at the front of your upload route.

Why would streaming not save memory? Decoding dominates. A 65.5 MB PNG is 8000 × 6250 pixels, and in my companion measurement of a 50 MP decode a full decode of that size needs about 150 MB of raw pixels. Eight of those in flight is over a gigabyte, whether the compressed bytes arrived in one Buffer or in chunks. The compressed body is 8 × 65.5 MB = 524 MB on top. The point here is that you cannot stream your way out of a decode. What did I test?

A plain node:http server with two routes, no framework, so only sharp and the body handling are in play: import http from 'node:http'; import sharp from 'sharp'; : {}; The server samples its own resident memory every 5 ms and reports the peak. A client sends the same file N times in parallel with http.request. I started a fresh server for every run and took the median of 5. What were the results?

Eight parallel uploads of p50.png (65,506,064 bytes, 50 megapixels): Case Status Server peak Slowest client buffer, no pixel cap 200 1,533 MB 1,803.2 ms stream, no pixel cap 1,398 MB 1,644.3 ms buffer, limitInputPixels 20,000,000 422 1,147 MB 282.3 ms stream, limitInputPixels 20,000,000 1,144 MB 275.7 ms client sends Content-Length, limit 20 MB 413 85 MB 14.7 ms Streaming saved 135 MB (1,533 against 1,398) and 160 ms. Useful, not decisive. A pixel cap refused the image fast but not cheaply. Both routes returned 422 in under 300 ms, yet peaked at about 1,145 MB. The 524 MB of bodies had already arrived and sat in memory.

That the stream route did the same suggests sharp takes the whole stream before it rejects; I did not trace the cause. The Content-Length check is the winner. It returned 413 in 14.7 ms and the server stayed at 85 MB. Note: a client can leave out Content-Length and send the body chunked. I tested that: 4 clients each sent a 300,000,000-byte file of random bytes with a 10,000,000-byte cap on the server.

Source disclosure

This is a source-linked briefing. Read the original report from Dev Community .