DEV Community

Dudko Development
Dudko Development

Posted on Originally published at ireceipt.pro

Invoice PDF times out at random? It's waiting for a file that never arrives

The setup is common. An app renders an invoice view to an HTML string, hands the string to headless Chrome, and attaches the PDF to an email. Most of the time it takes a second. Every so often it hangs until the timeout, on a laptop and in production alike, and raising the timeout doesn't help.

This Stack Overflow question is a clean example: a Rails 7 invoice mailer using Grover (Puppeteer underneath) fails at random with Grover::JavaScript::TimeoutError: Timed out after waiting 30000ms. The asker's own answer was one option, display_url, which had been nil. They guessed at a race condition. It isn't one, and the same thing happens with Puppeteer and Playwright directly, so it's worth knowing what's going on.

An HTML string has no address

When you pass a URL to the browser, relative paths like /assets/application.css or /logo.png resolve against that URL. When you pass a string, there's nothing to resolve against, so the library picks a base. Grover's README says that for raw HTML, if display_url isn't set, http://example.com is used. So the invoice asks example.com for your stylesheet.

Then the render waits for those requests. Grover's default wait_until for HTML content is networkidle0, and Playwright's setContent waits for load by default. Both mean "wait until the sub-resources are done". If the host answers quickly, even with a 404, you get a PDF. If it accepts the connection and then says nothing, you get a timeout. Whether it answers depends on the network that day, which is why the failure looks random.

What we measured

Playwright 1.63 driving Chromium 157 headless, Node 22, a 4-vCPU container. A 40-row invoice, page.setContent() then page.pdf() on US Letter, a fresh context for each case. The "stalled host" is a local TCP server that accepts the connection and never replies. That's the bad case: a request that neither succeeds nor fails.

the invoice links to… wait until setContent pdf result
nothing (all inline) load 9–34 ms 7–22 ms PDF
a stylesheet on a stalled host load 10,003 ms — timeout
a logo <img> on a stalled host load 10,001 ms — timeout
a @font-face on a stalled host load 10,002 ms — timeout
any of the three, stalled networkidle 10,005 ms — timeout
any of the three, on a host that refuses the connection load 8–13 ms 8–11 ms PDF

With a 10-second cap the stalled cases failed at 10 seconds, every time. With a 30-second cap the stylesheet case failed at 30,006 ms. The cap isn't something the render is approaching. It's just how long you wait before being told it failed. That's why a longer timeout doesn't help: it only makes the failure slower.

The refused-connection row matters. The file is just as missing there, but the render finishes in milliseconds, because the browser gets an answer and moves on. The problem is the stall, not the missing file.

The tempting fix makes it worse

If waiting for load is the problem, wait for less. With waitUntil: 'domcontentloaded', setContent returned in 6 ms in every stalled case. Then page.pdf() took 2,010–2,012 ms (we measured that, we didn't trace why), and it produced a PDF with no error.

But look at what's in it. With the stylesheet stalled, the PDF was 15,520 bytes, which is exactly what the same invoice with no stylesheet at all produced. With the logo stalled, the logo was missing. The invoice came out unstyled, nobody was told, and that PDF is the one that reaches the customer. A timeout is the better failure.

The fixes, cheapest first

None of these needs a new service. They're a few lines each on the stack you already have.

1. Put everything the invoice needs inside the HTML. CSS goes in a <style> block, and the logo becomes a data: URI. Fonts are either installed in the container (then a font-family name is enough) or embedded as base64 in the @font-face. An invoice is one page of mostly text, and inlining it costs nothing at runtime. This is the real fix, because then there's nothing to wait for.

2. If assets have to stay external, give the string a real base URL. That's Grover's display_url, or a <base href="https://your-app.example/"> in the head. Point it at a host you control and that the render machine can actually reach. It's the asker's fix, and it works because now the requests go somewhere that answers.

3. Block everything else at render time. Even with 1 or 2 in place, a template edited next year can pick up a Google Fonts link or a CDN stylesheet. Abort every request that isn't a data: URI, and a stray link fails in milliseconds instead of holding a worker:

const { chromium } = require('playwright');

async function renderInvoice(html) {
  const browser = await chromium.launch();
  try {
    const page = await browser.newPage();
    // Nothing leaves the page: data: URIs load, every other request fails at once.
    await page.route('**/*', (route) =>
      route.request().url().startsWith('data:') ? route.continue() : route.abort()
    );
    await page.setContent(html, { waitUntil: 'load', timeout: 5000 });
    return await page.pdf({ format: 'Letter', printBackground: true });
  } finally {
    await browser.close();
  }
}
Enter fullscreen mode Exit fullscreen mode

In our run, with this route in place, every stalled case went back to 6–9 ms for setContent (about 510 ms with networkidle, which always waits out its idle window) and 7–11 ms for the PDF. Puppeteer does the same with page.setRequestInterception(true) and a request handler that calls abort() or continue(). The catch is that blocking is silent too: a linked stylesheet is simply dropped. So treat it as a backstop for fix 1, not as a replacement for it, and check the output when you change the template.

4. Set the timeout to what the work needs. A self-contained invoice rendered in well under a second here. A 30-second timeout on that job doesn't give it more room to succeed. It just ties up a worker for 30 seconds before reporting a failure. Five seconds is generous, and a retry is cheaper than a stuck queue.

Where we fit

If this is your bug and you already run Grover or Puppeteer, you don't need us. Inline the assets, set the base URL, block the rest, and it's fixed in an afternoon. At a handful of invoices a day, a script and a cron job is the right answer.

We make iReceipt PRO, an API that takes a template id and JSON and returns the PDF or image, so there's no browser on your side at all. Its templates are HTML, CSS and Mustache, and per the FAQ they "do not support javascript and links to external sources". Images are base64, in the template or passed as an argument. So the rule from fix 1 is built into the product rather than something you have to keep remembering. The cost of that comes with it: no linked webfonts, no CDN stylesheets, the logo travels as base64, and the template lives with the renderer instead of in your app's views. It's worth it when the reason you're reading this is that you're tired of running the browser, not because of one timeout.


Originally published at https://ireceipt.pro/blog/invoice-pdf-timeout-stalled-asset.

Top comments (0)