An app that renders contracts and receipts with Puppeteer had
an issue opened about it last week. The setup
is a common one: a single shared Browser, a new page per download, no limit on how many
pages are open, and setContent(html, { waitUntil: 'networkidle0' }). The worries in the
issue are the usual ones too. Concurrent downloads "spawn multiple heavy Chromium pages
concurrently (~150MB+ RAM each)", a Chromium crash makes later requests fail, and the wait
adds latency to HTML that is already inlined. The fix it proposes is a job queue on Redis
or a separate microservice.
Before reaching for a queue, it's worth knowing what those pages actually cost. So I measured it.
The setup
One 40-row invoice, CSS inlined, rendered to a Letter PDF. Puppeteer 25.19.0 driving Chrome for Testing 158 in Puppeteer's default headless mode, on a 4-vCPU, 16 GB Linux box. Every case runs in a fresh Node process, three or four times; the table shows the range.
Memory is taken three ways, across every Chromium process:
- summed RSS, which is what you get adding up
psortop; - summed PSS (from
/proc/<pid>/smaps_rollup), which splits shared memory between the processes that share it; - the drop in
MemAvailable, i.e. what the machine actually lost. This one is noisy.
Times come from separate runs with no memory sampling at all. That matters more than I expected, and there's a note on it at the end.
| what you do | time for the batch | summed RSS | summed PSS | machine lost |
|---|---|---|---|---|
| 1 invoice, browser already open | 64-81 ms | ~0.98 GB | ~320 MB | 45-150 MB |
| 10 at once, one browser | 341-361 ms | 2.1-2.3 GB | 454-475 MB | 122-211 MB |
| 20 at once, one browser | 0.66-0.73 s | 3.4-3.8 GB | 612-636 MB | 321-394 MB |
| 40 at once, one browser | 1.30-1.41 s | 5.6-5.7 GB | 883-931 MB | 718-757 MB |
| 10 at once, a browser each | 2.30-2.38 s | 8.5 GB | 1.46-1.49 GB | 1.18-1.34 GB |
| 20 submitted, one browser, max 3 pages | 0.89-0.93 s | 2.3 GB | 469-472 MB | 163-289 MB |
| 40 submitted, one browser, max 4 pages | 1.61-1.70 s | 2.4-2.5 GB | 484-501 MB | 211-257 MB |
A page is cheaper than top says. A browser isn't.
Add up RSS and each extra page looks like 100+ MB, which is about where the issue's
"150MB+" comes from. Most of that is shared code and memory that every renderer process
maps, counted again for each one. By PSS an extra page cost about 15 MB here, and the
machine lost 15-18 MB per page going from 1 to 40. That's for a small text invoice; a
template with a large logo or embedded fonts will cost more, so measure yours with the
number your container limit actually uses (the cgroup's memory figure, not a sum over
ps).
A browser per request is a different animal. Ten of them cost roughly 120-150 MB each in real memory, and the batch took 2.3 seconds instead of 0.35, because each one has to launch. That's the shape of this Stack Overflow question, where every request launches, navigates and prints in "7~8 seconds" and the asker expects 30 simultaneous requests to take "about 40 to 50 seconds". If you launch per request, stop. The issue's app already shares one browser, which is the right call.
What a cap buys, and what it costs
Without a cap, memory follows your traffic: 20 invoices at once held about 620 MB by PSS, 40 held about 900 MB, and nothing stops the next burst from asking for more. With a cap of four pages, 40 invoices went through at about 490 MB, the same as 20 through a cap of three. Flat, whatever the batch size. That's the whole argument for a limit. A month-end burst queues up instead of spreading itself across every megabyte the container has.
Two things I didn't expect. First, the capped runs didn't sit at "one browser plus three pages". The Chromium process count under a cap of three stayed around 40, the same as ten pages open at once, so closed pages' renderers seem to linger for a while. A busy cap of 3-5 settled at 470-510 MB by PSS rather than ~370. It still stayed there.
Second, the cap wasn't faster. On this 4-core box, 20 pages opened at once finished in 0.66-0.73 s, and the same 20 through three slots took 0.89-0.93 s (five slots: 0.75-0.79 s). Forty uncapped took 1.30-1.41 s against 1.61-1.70 s through four slots. So a cap costs you something like 20-30% of burst throughput on small invoices, and buys predictable memory. For a download button behind a container limit, I'd take that trade every time. Start at three to five pages on four cores and measure on your own hardware.
The 2-second wait
With waitUntil: 'networkidle0', setContent on our inline invoice took 1,975-1,994 ms,
every run. With 'load' it took 2-15 ms. The PDF that came out was identical apart from
its creation timestamp. (networkidle2 behaved the same as networkidle0.) Puppeteer's
docs define networkidle0 as no connections
"for at least 500 ms"; in our
runs the call took about four times that. I didn't trace why.
On its own that's two seconds per download. Put it behind a cap and it compounds, because every page holds its slot for two seconds doing nothing. Twenty invoices through three slots:
waitUntil: 'load': 0.89-0.93 swaitUntil: 'networkidle0': 14.5 s
Sixteen times slower, same memory. (Uncapped, the twenty waits overlap and the batch takes
2.3-2.4 s.) If your HTML is self-contained, load is the right wait. If it references
anything over the network, that's a different bug: one slow or missing asset holds the
render until it times out, which is what
our earlier piece on random invoice timeouts
is about. Inline the assets first, then drop to load.
The code
One browser per process, relaunched if it dies; at most three pages at a time; a load
wait plus a check that fonts are ready. No dependencies beyond Puppeteer.
import puppeteer from 'puppeteer';
const MAX_PAGES = 3;
// One browser for the whole process, relaunched if it dies.
let browserPromise = null;
function getBrowser() {
if (!browserPromise) {
browserPromise = puppeteer.launch();
browserPromise.then(
(browser) => browser.on('disconnected', () => { browserPromise = null; }),
() => { browserPromise = null; },
);
}
return browserPromise;
}
// At most MAX_PAGES renders at once; the rest wait their turn.
let active = 0;
const waiting = [];
async function withSlot(fn) {
if (active < MAX_PAGES) active++;
else await new Promise((resolve) => waiting.push(resolve)); // slot handed over
try {
return await fn();
} finally {
const next = waiting.shift();
if (next) next();
else active--;
}
}
export function renderInvoicePdf(html) {
return withSlot(async () => {
const browser = await getBrowser();
const page = await browser.newPage();
try {
await page.setContent(html, { waitUntil: 'load', timeout: 10_000 });
await page.evaluate(async () => { await document.fonts.ready; });
return await page.pdf({ format: 'Letter', printBackground: true });
} finally {
await page.close().catch(() => {});
}
});
}
Two details matter. The slot is handed straight to the next waiter rather than released and
re-taken, so a new caller can't slip in between and make it four. And the disconnected
handler is what fixes "a crash breaks every later request": the next render launches a
fresh browser.
I ran it (with --no-sandbox added to launch(), because the test box runs as root): 20
concurrent calls gave 20 valid PDFs in 0.74-1.04 s. Then I killed every Chromium process
with SIGKILL while six calls were in flight. Three of the six failed; the other three,
still queued, ran on a relaunched browser, and the next five calls after that succeeded in
183-242 ms. One catch: a call that was mid-way
through opening its page when the browser died sometimes took 30 seconds to fail, on
Puppeteer's own internal wait, holding its slot the whole time. Whoever calls this should
retry once, and if a 30-second stall after a crash matters to you, put your own deadline
around fn().
Do you need the Redis queue?
Not for this. An in-process cap solves "too many pages at once" for a download button, and the user still gets the PDF in the same request.
A real job queue earns its keep when the work shouldn't live in the request at all: emailing 500 statements on the 1st, retrying a failed render tomorrow, surviving a deploy halfway through a batch, rendering on a different machine from the web server. If that's you, BullMQ or similar is fine, and the worker should still use one browser and a page cap inside it. A queue in front of unbounded pages just moves the problem.
Or don't run the browser
The other way out is to stop owning Chromium. iReceipt PRO, which publishes this blog, is a hosted rendering API: a template plus JSON in, a PDF (or PNG, JPG, WEBP) out. Templates are HTML and CSS with Mustache, and they can't run JavaScript or load external resources, so the "what should I wait for" question goes away. The official JS SDK retries 408, 429 and 5xx responses on its own, up to five attempts.
What it costs you: a network call per document, the invoice data leaves your infrastructure, the template lives on our side instead of in your repo, and authoring your own template needs a paid plan. You'd still want a modest limit on how many requests you send at once.
And if you render a few invoices a day, none of this is worth changing. Keep Puppeteer,
share the browser, switch networkidle0 to load, and you're done.
A note on measuring this yourself
My first pass sampled memory every 20 ms by reading smaps_rollup for every Chromium
process. With 20 or more renderers alive, that sampling ate enough of the four cores to
make 20 uncapped pages take 16-25 seconds instead of 0.7, and it pushed a capped
networkidle0 batch past Puppeteer's 30-second navigation timeout. Reading PSS for dozens
of processes is not free. Time your renders in one run and measure memory in another, or
sample far less often.