Skip to content

perf: use Content-Length header instead of res.body() for network size#746

Open
Gonzih wants to merge 1 commit intogarrytan:mainfrom
Gonzih:fix/network-size-body-buffer
Open

perf: use Content-Length header instead of res.body() for network size#746
Gonzih wants to merge 1 commit intogarrytan:mainfrom
Gonzih:fix/network-size-body-buffer

Conversation

@Gonzih
Copy link
Copy Markdown

@Gonzih Gonzih commented Apr 1, 2026

The Problem

In `browser-manager.ts`, the `requestfinished` handler calls `res.body()` to get the response size:

```typescript
const body = await res.body().catch(() => null);
const size = body ? body.length : 0;
```

`res.body()` in Playwright buffers the entire response into a Node `Buffer`. For a 2MB JS bundle, that's a 2MB allocation per network request, just to call `.length` on it. Under load (SPA with 50+ network requests on page load), this is significant memory pressure and event loop blocking.

Issue #711.

Fix

Read `Content-Length` from response headers first — it's O(1) and already cached by Playwright. Only fall back to `res.body()` for chunked transfer encoding where `Content-Length` is genuinely absent.

Most HTTP/1.1 and HTTP/2 responses include `Content-Length`. The fallback covers streaming/chunked responses where the header is missing by design.


sent from mStack

…e tracking

res.body() buffers the entire HTTP response into a Node Buffer.
For large responses (JS bundles, images, API payloads) this is
O(response_size) memory pressure per request and blocks the event loop
while Playwright reads the full response body just to get a byte count.

Fix: read the Content-Length response header first (O(1), zero I/O).
Fall back to res.body() only for chunked transfer encoding where
Content-Length is legitimately absent.

This is particularly noticeable on pages with heavy network traffic —
downloading a 2MB JS bundle previously allocated a full 2MB Buffer
just to call .length on it.

Closes garrytan#711
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant