DEV Community

Cover image for Why My PDF Export "Hung" for Minutes: Connect Timeouts, Dead Image Links and No Deadline
NAN
NAN

Posted on Edited on

Why My PDF Export "Hung" for Minutes: Connect Timeouts, Dead Image Links and No Deadline

A user wrote in: "Exporting the full chat to PDF just spins forever."

It did not spin forever. It spun for several minutes, and then produced a perfectly good PDF. That is worse than an error: nobody waits that long, so from the outside it looked broken, and the logs showed nothing wrong.

The cause turned out to be three image links in the chat, and two kinds of timeout I had not set. Here is the trail, because I suspect a lot of "export to PDF" code has the same hole.

The setup

The tool exports AI chat conversations to PDF, Word and other formats. A full export has two stages:

  1. In the browser, the extension collects the conversation and tries to inline every image as base64 (so the server does not have to fetch anything behind a login).
  2. On the server, the HTML is turned into a PDF with a PHP library (mPDF).

The chat in question had three Markdown images the model had invented, pointing at a placeholder-image site:

![Illustration of the 3 layers of a website](https://placeholder.example/id/0/500/200)
Enter fullscreen mode Exit fullscreen mode

The chat UI did not even display them. The export tried very hard to.

Stage 1: the browser, ~90 seconds

The image inliner looked reasonable:

for (const img of images) {
  try {
    img.src = await toBase64(img.src); // 10 s timeout, retry up to 3 times
  } catch {
    // keep the original URL
  }
}
Enter fullscreen mode Exit fullscreen mode

Each image: three attempts × a 10-second timeout. Three images, one after another. That is up to 90 seconds before the request even leaves the browser, for images that were never going to load.

Two mistakes stacked:

  • Sequential awaits for independent work.
  • Retrying a timeout. A host that did not answer in 10 seconds is not going to answer on the second or third try. Retries make sense for fast failures (a flaky 502), not for silence.

Stage 2: the server, ~120 seconds

The server then received HTML that still contained the three remote URLs, and mPDF fetched them itself. On the server I timed a single image:

curl: connect OK, then 0 bytes received for 30 s -> timeout
mPDF, one remote <img>: 39.8 s
same document without remote images: 0.98 s
Enter fullscreen mode Exit fullscreen mode

The interesting part is connect OK, then nothing. The host accepted the TCP connection and never sent a byte. That defeats the one timeout most HTTP setups do have:

  • CURLOPT_CONNECTTIMEOUT caps the time to establish the connection. It passed instantly.
  • CURLOPT_TIMEOUT caps the whole transfer. mPDF's default leaves that unset (curlExecutionTimeout => null).

And PHP's max_execution_time did not save me either, because on Linux it counts CPU time, and a process waiting on a socket uses almost none.

So the request "hung" at 0% CPU, finished two minutes later, and logged nothing.

The fix

1. Don't fetch what the user can't see

The chat UI does not render external Markdown images, so the export should not either. The server-side parser now writes them as links:

<a href="https://placeholder.example/id/0/500/200">[Illustration of the 3 layers of a website]</a>
Enter fullscreen mode Exit fullscreen mode

The document matches the screen, and there is nothing to fetch.

2. Fetch the rest in parallel, with one budget

For images that do need fetching, the server downloads them all at once with curl_multi, each with a total timeout, and the whole batch has a hard deadline:

$deadline = microtime(true) + 8;          // budget for ALL images
foreach ($urls as $u) {
    $ch = curl_init($u);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 4,
        CURLOPT_TIMEOUT        => 5,     // total time, not just connect
        CURLOPT_PROTOCOLS      => CURLPROTO_HTTP | CURLPROTO_HTTPS,
    ]);
    curl_multi_add_handle($mh, $ch);
}
do {
    curl_multi_exec($mh, $running);
    if ($running) curl_multi_select($mh, 0.5);
} while ($running && microtime(true) < $deadline);
Enter fullscreen mode Exit fullscreen mode

Whatever arrived is embedded as a data URI. Whatever did not becomes a link. The document is never held hostage by the slowest host.

Two things worth adding while you are in there, because you are now fetching user-supplied URLs from your server:

  • Block private addresses. Resolve the host first and refuse loopback and private ranges, then pin curl to the address you checked, so a URL cannot be used to poke at your internal network.
  • Cap the size. Abort a download past a few megabytes per image and a total for the document.

3. Belt and braces in the PDF library

mPDF can still fetch things on its own (CSS backgrounds, for example), so it now has a total timeout too:

new \Mpdf\Mpdf([
    'curlTimeout'          => 4,
    'curlExecutionTimeout' => 6,
    'curlFollowLocation'   => true,
]);
Enter fullscreen mode Exit fullscreen mode

4. In the browser: parallel, one attempt, short timeout

const cache = new Map();
let next = 0;
await Promise.all(Array.from({ length: Math.min(6, images.length) }, async () => {
  while (next < images.length) {
    const img = images[next++];
    if (!cache.has(img.src)) cache.set(img.src, toBase64(img.src, { timeoutMs: 6000 }));
    try { img.src = await cache.get(img.src); } catch { /* keep the link */ }
  }
}));
Enter fullscreen mode Exit fullscreen mode

A small worker pool, deduplicated URLs, a 6-second ceiling, no retry on timeout. And for exports that read the conversation from the API rather than the page, the browser now skips this step entirely and lets the server handle images.

Result

Same conversation:

Before After
Browser image step ~90 s skipped (API export)
Server PDF ~120 s ~8 s (including the 5 s wait on the dead host)
Server PDF, images shown as links n/a ~2 s (PDF rendering alone took 1.25 s)

The general lesson

If your code fetches URLs that came from users (or from an LLM, which is the same thing), check three things:

  1. Is there a total timeout, not just a connect timeout? "Accepts the connection, sends nothing" is a real behaviour, and it is the one that hurts.
  2. Is there one deadline for the whole batch? Per-request timeouts multiplied by N requests is not a deadline.
  3. What does the failure look like to the user? Here the best failure is a link in the document, not a spinner.

Disclosure

This came from Chat Exporter, a set of browser extensions I build for exporting ChatGPT, Gemini, Claude, DeepSeek and other AI chats to Word, PDF, Google Docs, Notion, Markdown, TXT or JSON. The bug was in the DeepSeek exporter; there is a step-by-step guide here.


Have you been bitten by "connect OK, then silence" somewhere else? I am collecting the places where a connect timeout looked like enough and wasn't.

Top comments (4)

Collapse
 
astap profile image
Юрий •

Solid debugging story. Setting explicit connect/read timeouts and validating external asset URLs upfront can save a lot of pain with PDF generation. A small "preflight" check for images (HEAD request + fallback) often prevents these hangs in production.

Collapse
 
anuis258 profile image
NAN •

Thanks! Agreed on explicit timeouts. Preflight was the first thing I tried, and it taught me something.

A HEAD request hangs on exactly the same host. This one accepted the TCP connection and then sent nothing, so the HEAD needs the same total timeout as the GET. At that point the preflight costs a full round trip and doesn't save anything. Some image hosts also answer HEAD with a 405, or with a different status than GET.

What worked better was skipping the preflight: fire the real GETs in parallel with one shared deadline, then keep whatever arrived. Anything that missed the deadline becomes a link in the document. One wait for the whole batch instead of one per image.

Where preflight does shine is when you can cache the result. Remembering "this host is dead" for a few minutes means the next export doesn't wait at all. Do you cache yours?

Collapse
 
komopdf profile image
KomoPDF •

One subtle trap in that mPDF config: setting curlFollowLocation => true can bypass your private-IP check if an external URL redirects (301/302) to 127.0.0.1 or a cloud metadata endpoint like 169.254.169.254. When pinning IPs with CURLOPT_RESOLVE, disabling redirects or validating each hop inside a custom redirect loop closes that SSRF gap.

On the browser side, AbortSignal.timeout() bundles DNS, TLS, and transfer into one clock, matching CURLOPT_TIMEOUT. Sharing a single AbortController across Promise.allSettled gives you that same hard batch deadline on the client so one stalled host never holds up the rest of the PDF export.

Collapse
 
anuis258 profile image
NAN •

Good catch, thanks! In this setup mPDF never actually gets a remote URL: the RemoteImages pass runs first and every <img> becomes either a data: URI or a plain link. That pass doesn't use CURLOPT_FOLLOWLOCATION either; it reads the Location header, resolves the next host, rejects private/reserved IPs again and pins it with CURLOPT_RESOLVE, max 3 hops. So curlFollowLocation in mPDF is only a dead fallback, and you're right that it's safer to just set it to false so it can't become a hole later. I'll flip it.

Agreed on AbortSignal.timeout() too. One shared AbortController (or AbortSignal.any() with a per-image timeout) gives the client the same "one deadline for the whole batch" behaviour as curl_multi on the server.