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.
Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.