hn.today

How a tiny HTTP response preview ended up buffering a 64 MB download

octri.dev4 points0 comments
Screenshot of How a tiny HTTP response preview ended up buffering a 64 MB download

A monitoring SDK experiment found that cloning a Node.js fetch response to inspect only a 4 KB preview can retain the entire download in memory. In tests with streamed 16 MB and 64 MB files, an unread clone added about 16 MB and 64 MB of array-buffer memory, respectively, even though the monitoring code later read only a small sample. JavaScript heap usage barely changed, so heap measurements alone would have hidden the problem. The cause is Response.clone(), which tees the body into two streams: the application can keep downloading while the slower, unread branch queues every chunk without a fixed size limit.

Reading the preview from the clone immediately and canceling that branch reduced the extra memory to about 0.26 MB, but cancellation can remain pending until the other branch finishes, so it should not be awaited before the application consumes its response. The more efficient option is to capture the first 4 KB in a TransformStream as the application reads the original body, then pass chunks through unchanged. This preserved the file’s hash and used roughly the same memory as no preview - about 0.07 MB in the tests - while maintaining backpressure. This approach only captures data the application actually reads, and wrapping the body may require care to preserve response metadata and cancellation behavior. Previews can also expose sensitive content, so inspecting data locally should be considered separately from sending it to monitoring servers.

Read on octri.dev0 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Programming

Show HN: Rust Commander

Show HN: Rust Commander

Rust Commander is a Rust terminal file manager modeled on Midnight Commander, with dual-pane navigation, a persistent shell, archive and remote browsing, and background file operations. Version 0.3.1 adds file-change alerts, viewer copy controls, customizable skins, and faster SFTP previews and copying. (github.com)

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.