Skip to content
Engineering11 min read

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

Share

We tested Response.clone() with Node's native fetch and found that a 4 KB preview could retain an entire download. Here's why and how we avoided it.

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

While working on the Monitoring side of Octri, one thing we've had to be extremely careful about is the amount of work we do on the user's end whenever we have to report something. Since we're generating SDKs that other developers integrate in their apps, the user can also enabled the monitoring feature from within the generated SDK to collect performance data from both ends (Client-side and Server-side), so anything we do to collect the telemetry data would probably impact their app's UX in general and use up additional memory, so we had to be extra careful regarding this.

Something particularly interesting for us was, what would happen if we wanted to preview a small portion of the response without interfering with it, this is mostly useful to determine early on in the response's life cycle to locally check why the response failed to parse (if it did), without having to save the entire response in our servers (which is only possible if the user allowed that specific body field) and consume their monthly allowance.

On the JavaScript side of things, one way we had in mind was this:

javascript
const response = await fetch(url);
const copy = response.clone();

The first thing someone might think of is to just copy the response to grab a preview and inspect it, the preview would be limited to 4 KB so we can run our checks/analysis on a small sample of the response and then act on it accordingly, the interesting part of the experiment is that after downloading the 64 MB file, the application would still be holding on to another 64 MB of memory on top of the original response so we'd be using up to 128 MB of memory for a longer time than originally intended by the app's developer and if there are multiple background process running simultaneously in the background, this could easily balloon up to enormous amounts of memory and cause the app to crash at some points so we had to come up with another more efficient solution for this.

A tiny diagnostic sample leaves an entire streamed download queued in memory.

Running the test on a small sample of downloads

To start, we've setup a small toy server that sends back a 64 MB file made up of duplicate bytes, the server sends the file in separate chunks and waits for its write buffer to drain when needed.

On the client side, we wanted to make sure we're consuming the file as a stream during this test since if we attempted to use something like response.arrayBuffer() we'd be allocating memory for the entire file anyways which would make it hard for us to tell how much the clone's cost is.

So our first test was basically just reading the chunks off of the response asynchronously:

javascript
const response = await fetch(url);

for await (const chunk of response.body) {
  // The application's work goes here.
}

For the second test, we cloned the response without consuming it and kept the copy around until the download was complete, after the download is complete, we'd read 4,096 bytes into our preview buffer and cancel the rest of the cloned stream since we no longer need it.

We compared the two tests head-to-head and also run both tests on a 16 MB file as well to see if the amount memory usage would change with the size of the response, and here's what we got:

Response size Array buffers without cloning Array buffers with an unread clone
16 MB 0.07 16.07
64 MB 0.07 64.07

The values in the table are in MB and were taken from 3 runs of each test on Node.js v22.16.0. We took the median of the readings after the original download was done (but before we'd read anything from the clone) and after letting the garbage collector do its thing. Since we were streaming the original response in this test, we weren't keeping its 64 MB in a separate buffer, so what we're seeing here is roughly 64 MB of additional array buffer memory, not 128 MB of measured memory usage. We'd have the original file in memory as well if we were to collect its contents into a buffer and keep it around, which would bring the two bodies alone to roughly 128 MB.

Something else we noticed while looking at those numbers was how little the JavaScript heap usage had changed. It went from about 6.69 MB to 6.91 MB for the larger file, which wouldn't have given us much of an indication that an entire file was still in memory had we only been looking at heapUsed. Node reports the memory used by the backing buffers separately under arrayBuffers (it's also included in external, so don't add those two together!).

Why was the entire file still in memory?

We had a look at what Response.clone() does with the response's body and it turns out it splits the original stream into two readable streams, which is something you can do yourself using ReadableStream.tee(). Both streams receive the contents of the same response, and we're able to read from either of them independently of the other one.

Let's say we're downloading a file and the application has processed its first chunk, so it's ready to receive the next one, but our monitoring code hasn't read anything from its copy of the stream yet. If we were to make the original stream wait until both consumers had processed the chunk before sending the next one, we'd essentially be preventing the app from downloading the file until our monitoring code got around to reading its copy of it too.

So what happens instead is that the original stream keeps supplying data as the faster consumer requests it, and the chunks that the other consumer hasn't gotten around to reading get queued up for it. This is actually mentioned in the MDN docs for Response.clone(), and there isn't a fixed limit on the amount of data that can be queued on that second branch.

A teed response queues unread chunks for the slower preview consumer.

This explains why the amount of array buffer memory went up by pretty much exactly the size of the file in both of our tests. Every time the application was done with a chunk, the copy of the response would still need to be able to give us that chunk when we eventually decided to read from it, and by the time the application was done downloading the file, we'd queued the entire file on the other side of the stream. It didn't matter that we were only going to read 4,096 bytes from it afterwards since the stream had no way of knowing that ahead of time.

What if we read the preview off the clone before downloading the file?

So the first thing we thought of trying was to read the first 4,096 bytes off the clone as soon as we created it and cancel its stream once we had enough data to work with. This way we wouldn't have to keep queuing up the remaining chunks for the clone while the application was downloading the rest of the file.

There's one thing to be careful about when doing this though, if we were to call await reader.cancel() on the clone's reader before letting the application consume the original response, we'd potentially be stuck there waiting for the original stream to finish since canceling one branch of a teed stream can leave the cancellation promise pending until the other branch finishes or is canceled. So we started the cancellation without awaiting it, let the application download the file and then awaited the cancellation promise afterwards.

We ran both downloads again and ended up with about 0.26 MB of array buffer memory in both tests, which was quite a bit more reasonable! This still meant we'd be reading from a second stream before the application got a chance to consume the body in our experiment though, so we wanted to see if we could avoid splitting up the stream altogether.

Collecting the preview as the application consumes the stream

Since we'll be getting all of the chunks when the application reads the response anyways, why not take the first few bytes we need as the chunks pass through and let the application handle the original chunks as it normally would? Once we've collected enough bytes for our preview, we'd just pass all subsequent chunks through without copying anything else.

We can do this with a TransformStream:

javascript
const preview = new Uint8Array(4096);
let captured = 0;

const body = response.body.pipeThrough(new TransformStream({
  transform(chunk, controller) {
    const count = Math.min(chunk.byteLength, preview.length - captured);

    if (count > 0) {
      preview.set(chunk.subarray(0, count), captured);
      captured += count;
    }

    controller.enqueue(chunk);
  }
}));

Instead of consuming response.body directly, the application would consume body, and we could get the bytes we'd collected so far from preview.subarray(0, captured). We allocated the 4 KB buffer beforehand and copied the bytes into it because if we were to just keep a subarray of one of the incoming chunks, we'd be holding on to a view of that chunk's backing buffer and could end up keeping a much larger allocation around just to use a few bytes from it (which would be quite ironic given what we're trying to fix here).

The other interesting thing about doing it this way is that if the application stops reading the chunks for a bit, our monitoring code won't keep pulling the response independently while the application is busy. The backpressure from the application can propagate through the transform and we only need to account for the fixed preview buffer on our end, in addition to the normal buffering done by the HTTP client and the streams.

Inline stream inspection copies a bounded preview while forwarding the original chunks.

We ran the same tests one more time with the transform in place and here are all 4 approaches side-by-side (in MB):

Response size No preview Unread clone Read and cancel clone early Inline preview
16 MB 0.07 16.07 0.26 0.07
64 MB 0.07 64.07 0.26 0.07

So we were able to collect the same 4,096 bytes we were getting from the clone without having to retain the entire response while the application was downloading it. We also checked the SHA-256 hash of the file received by the application in all 4 tests at each file size to make sure we hadn't accidentally dropped any of the bytes when passing the chunks through the transform.

Retained array buffer memory grows with the unread clone but stays small with inline capture or early cancellation.

A few things to consider before using this in an SDK

One thing we'd have to account for with the second approach is that we can't collect anything if the application never actually reads the response, which is perfectly fine for what we were trying to do here. If the application only consumes part of the response before canceling it then we'd only have access to the bytes that had made it through the transform. We'd also have to keep the original response's metadata and cancellation behavior in mind if we wanted to expose the transformed body through a Response object, since just constructing a new one with that body wouldn't preserve everything from the original response (such as its url and redirected properties).

For most of the things we'd want to report to our monitoring service such as how long an operation took, the status code it returned or the exception raised by the SDK's existing parser, we wouldn't even need to read the body separately. And for the diagnostic experiment above, we only used dummy bytes and kept the preview local. A 4 KB sample could help us identify something like an HTML error page being returned where we expected JSON, but it wouldn't necessarily tell us why parsing failed if the problematic data appeared later in the response. Even a small preview can contain sensitive information, so the decision to inspect a response locally should be kept separate from any decision to send data to a server.

If you're already cloning responses in your HTTP client or middleware just to inspect them later, it might be worth trying the same test on one of your endpoints that returns a large file. We'd initially been thinking of the memory cost in terms of how much of the response we'd be reading from our copy, but what ended up making the difference was when we were reading from it.

Share

Octri