When we started oMyPDF, the rule was simple: files under 15 MB are processed in your browser, anything bigger goes to the server. It was easy to explain, easy to code, and wrong in both directions.
A 35 MB scanned PDF could have been turned into JPGs in the browser in seconds. Instead it went up to a server that took minutes. Meanwhile a 12 MB Word file was being "converted" in the browser by rasterizing every page into an image.
This post walks through the rules we ended up with, the code behind them, and the bugs that forced each one. Every number below comes from the code or the commit that introduced it.
Key takeaways
- A single size threshold doesn't fit all tools. Split them by what the tool does, not just by file size.
- Device memory matters more than file size for "light" tools. Phones get a lower ceiling than desktops.
- Anything heavy you keep in the browser belongs in a Web Worker, or it freezes the tab.
- On the server, run heavy converters as child processes with a queue and real cancellation, never on the Node event loop.
Two thresholds, not one
The router lives in one small file. The core of it is two constants and a one-line function:
export const SIZE_THRESHOLD = 15 * 1024 * 1024; // 15 MB
export const LIGHT_SIZE_THRESHOLD = 60 * 1024 * 1024; // 60 MB, pdf-lib structural ops (desktop)
export function shouldUseServer(totalBytes: number, threshold: number = SIZE_THRESHOLD): boolean {
return totalBytes > threshold;
}
The split is about what the tool actually does to the file:
- Light tools only move PDF objects around: merge, split, watermark, page numbers, protect, sign, organize. pdf-lib copies and stamps objects without rendering anything, so it barely touches the CPU. These use the 60 MB ceiling.
- Heavy tools rasterize or re-render pages: PDF to image, Office conversions, OCR. A big input freezes the tab, so these keep the 15 MB default.
- Compress is heavy work, but it runs in a Web Worker (more on that below), so the page stays responsive and it gets the light ceiling too.
A few tools skip the browser entirely. OCR runs OCRmyPDF, PDF to Word runs pdf2docx, and Word to PDF runs LibreOffice. All three are server-only whatever the size. Word to PDF used to stay in the browser under 15 MB, but the browser path drew each page with html2canvas and stitched the images into a PDF. The text wasn't selectable and the file was huge. It's now only a fallback for when the server can't be reached.
The ceiling depends on the device
60 MB is fine on a desktop with 16 GB of RAM. On a budget phone, a 60 MB PDF plus pdf-lib's working copy is a good way to get the tab killed. So the light ceiling moves with the device:
if (mem && mem <= 2) return 20 * MB; // very low RAM, any form factor
if (isPhone) return mem && mem >= 6 ? 35 * MB : 25 * MB;
if (isTablet) return mem && mem >= 6 ? 50 * MB : 40 * MB;
if (mem && mem <= 4) return 40 * MB; // low-RAM desktop/laptop
return LIGHT_SIZE_THRESHOLD; // full desktop
mem comes from navigator.deviceMemory. That only exists in Chromium browsers and is capped at 8, so Safari and Firefox fall back to the user agent. One detail took a while to find: iPadOS reports itself as a desktop Mac. The check that catches it is /Macintosh/i.test(ua) && touch > 1, because a real Mac doesn't report multiple touch points.
The hook that reads this starts at 60 MB and switches to the device value after the component mounts. Reading navigator during server rendering would produce a hydration mismatch.
Keeping heavy work off the main thread
Compression and PDF-to-image run in a Web Worker with pdf.js and OffscreenCanvas. The page keeps scrolling while a 40-page scan is being rendered. Safari before 16.4 has no OffscreenCanvas, so it falls back to running on the page.
Workers came with their own bugs. pdf.js binds its own message handler to the worker's global scope and posts its internal traffic to whoever is listening. Our client code treated that traffic as a result, rejected the promise and killed the worker. The fix is a channel tag on every real message:
// pdf.js binds its own MessageHandler to the worker's global scope and posts
// its protocol traffic to us. Ignore it, treating it as a result used to
// reject the promise and kill the worker.
if (msg?.channel !== CHANNEL) return;
The second one was quieter. pdf.js 6 removed pdf.destroy(), and we called it as pdf.destroy?.(). Optional chaining turned a breaking change into a silent no-op. Every document we opened stayed in memory along with its worker: 18 live workers after visiting 8 pages. The fix destroys the loading task in a finally block, and a test now opens and closes a document through every reader to prove it's released.
The third was about honesty. Every TypeError used to show "Couldn't reach the server". A pdf.js crash on Firefox for Android ("getOrInsertComputed is not a function") looked to users like an outage. Errors from inside workers now carry their real name across postMessage, and the network message only appears for a real failed fetch. There's a test for exactly that sentence.
What happens when a file does go to the server
Files over 8 MB are uploaded in chunks, four at a time. Long jobs return 202 Accepted with a job id, and the client polls with a backoff from 2 to 6 seconds. It gives up after an hour.
The biggest lesson was about where conversion runs. Our PDF-to-JPG first rendered pages with pdf.js and a native canvas inside the Express process. A 40-page, 35 MB file took 7 to 8 minutes, and while it ran, the event loop was busy and the whole API froze for everyone. The fix had three parts:
- Rendering moved to a separate process (pypdfium2). The API stays free while it works.
- The queue got two lanes. With one shared queue of two slots, a 3-page render that needs about a second waited 20 seconds behind two long jobs.
- Cancelling now kills the job. The first audit failed: cancel reported success while pdf2docx left three workers running at about 90% CPU and OCRmyPDF sat at 384%. Abandoning the poll on the client isn't enough, so cancel now sends a
DELETEand the server stops the job itself.
We also found pdf2docx defaults to one worker per CPU core for two separate pools, so two PDF-to-Word jobs spawned twice the server's cores. And holding uploads in memory was a big part of a 1.68 GB peak against our process manager's 2 GB restart limit. Tools that start a separate program now write uploads to disk instead. Five concurrent 85 MB jobs went from 1,724 MiB to 1,126 MiB.
Server-side compression has one rule we'd recommend to anyone: never return a bigger file. Ghostscript sometimes makes an already-optimized PDF larger, so we keep whichever is smaller:
// Already-optimized PDFs can come back larger, keep whichever is smaller.
const best = out.length > 0 && out.length < bytes.length ? out : bytes;
Files don't stay
Uploaded files and results are kept for one hour, so you can download again or share the link, and then they're deleted. Two cleaners do it. One runs inside the app every 10 minutes. The other is an hourly cron job that also clears scratch folders left by crashed processes and keeps working when the app is down.
Two details mattered here. The cron line starts with cd into the backend folder, because without it .env isn't found and the sweep "silently does almost nothing". And the recursive delete only touches folders whose names match a strict pattern (/^omy(pdf|image)-[a-z0-9]+-/i), so a bug can't point it at anything else.
Compress to an exact size
One feature was fun to build: compress a PDF to a target like "under 500 KB" for upload forms. It tries the harshest setting first to check the target is reachable, then binary-searches for the gentlest setting that still fits. The tests pin that behaviour by name: "keeps the gentlest rung that fits" and "moves towards the limit without ever crossing it". In Chromium, a 9.4 MB photo PDF with a 500 KB target came out at 491.7 KB in 2.6 seconds, with the text still selectable.
What I'd tell myself at the start
- Don't use one size threshold. Group tools by what they do to the file.
- Make the ceiling device-aware. Phones are not small desktops.
- Put anything heavy in a Web Worker, and tag your worker messages.
- Never run a converter on the Node event loop. Child process, queue, real cancel.
- Keep the smaller file. Users notice when "compress" makes things bigger.
You can try all of this on oMyPDF: merge PDF and compress PDF are two of the tools that use the light path. If you've solved the same problem differently, I'd like to hear about it in the comments.


Top comments (0)