Prompt
How do I process thousands of PDFs per day reliably?
Latest observation
To process thousands of PDFs per day reliably, you want a pipeline that is queue-based, parallel, fault-tolerant, observable, and idempotent. The key is not just “can extract text,” but “can do it consistently under load, recover from failures, and know what happened.”
1) Break the job into stages
A reliable PDF pipeline usually looks like this:
-
Ingest
- Receive PDFs from S3, blob storage, uploads, email, API, etc.
- Validate file type, size, checksum, and source metadata.
-
Queue
- Put each PDF, or each page/chunk, into a message queue.
- Avoid processing directly in the web/API request path.
-
Preflight / classify
- Detect: digital PDF vs scanned PDF vs corrupted vs encrypted.
- Extract basic metadata: page count, file size, language hints, creation date.
-
Extract
- Digital PDFs: use a fast text extractor.
- Scanned PDFs: OCR pipeline.
- Tables/forms: specialized extraction if needed.
-
Post-process
- Normalize text, de-hyphenate, remove boilerplate, preserve page boundaries.
- Chunk for downstream search/LLM/indexing.
-
Persist
- Store output text, page-level results, structured data, and errors.
- Keep raw input and intermediate artifacts for audit/reprocessing.
-
Monitor and retry
- Retry transient failures.
- Quarantine bad files.
- Emit metrics and alerts.
2) Use a queue and worker pool
For thousands/day, a queue is essential.
Recommended pattern
- Producer: accepts PDFs and writes a job message.
- Workers: stateless processing containers/VMs.
- Queue: SQS, RabbitMQ, Kafka, Pub/Sub, Redis streams, etc.
- Result store: database + object storage.
Why this matters
- Smooths bursts
- Allows horizontal scaling
- Prevents request timeouts
- Makes retries and dead-lettering manageable
3) Make processing idempotent
PDF jobs will be retried. They may be duplicated. Design for that.
Use:
- A stable document ID based on checksum or source ID
- Job deduplication
- Output writes that can be safely repeated
- Status transitions like:
received -> processing -> completedreceived -> failed -> retrying -> dead_letter
Example
If a worker dies after writing page 3 of 10, rerunning should not corrupt the final result. Either:
- overwrite safely, or
- write per-page artifacts and assemble at the end, or
- check existing checkpoints before redoing work.
4) Detect PDF type early
Not all PDFs should be handled the same way.
Digital PDFs
- Have embedded text
- Fast to extract
- Usually use tools like
pdftotext,pdfminer,pypdf, or commercial extractors
Scanned PDFs
- Need OCR
- Consider deskewing, denoising, image preprocessing
- Use engines like Tesseract, AWS Textract, Google Document AI, Azure Document Intelligence, or specialized OCR stacks
Corrupt / encrypted / malformed PDFs
- Route to a failure bucket or repair path
- Don’t let these poison the normal pipeline
5) Process at the right granularity
For reliability and throughput, process by:
- document-level for orchestration
- page-level for extraction/OCR if documents are large
- optionally section-level later for NLP/LLM work
Benefits of page-level processing
- Parallelizable
- Easier retries
- Better progress tracking
- A single bad page doesn’t fail the whole file
6) Control concurrency carefully
Thousands/day is not enormous, but if some PDFs are huge, OCR-heavy, or malformed, they can overwhelm resources.
Best practices
- Separate queues for:
- lightweight text extraction
- OCR
- expensive parsing/table extraction
- Limit per-worker concurrency
- Cap memory usage per process
- Use timeouts for each stage
- Kill and retry stuck jobs
Common failure mode
Running too many OCR jobs at once causes:
- memory spikes
- temp disk exhaustion
- slower throughput
- worker crashes
7) Store intermediate artifacts
Keep:
- original PDF
- extracted text per page
- OCR output
- structured JSON
- logs/error traces
This helps with:
- debugging extraction issues
- reprocessing when you improve your pipeline
- audit/compliance
- comparing versions of extractors
Use object storage for large artifacts, not just a database.
8) Build robust retries and dead-letter queues
Not all failures are equal.
Retry automatically for:
- network timeouts
- temporary storage issues
- transient OCR service errors
- temporary dependency outages
Do not endlessly retry:
- corrupted PDFs
- password-protected PDFs with no password
- unsupported file types
- consistently failing parser bugs
Pattern
- retry 3–5 times with exponential backoff
- send permanent failures to a dead-letter queue
- keep failure reason and stack trace
9) Add observability
If you want reliability, you need visibility.
Track metrics
- jobs received/completed/failed
- throughput per minute
- queue depth / lag
- average and p95 processing time
- OCR rate vs text-extract rate
- error categories
- memory/CPU usage
- file size/page count distributions
Logs
- include document ID, job ID, page number, stage, worker ID
- structured logging is much better than plain text
Alerts
- queue backlog growing
- failure rate above threshold
- OCR latency spikes
- worker restarts
- storage/API errors
10) Use a hybrid extraction strategy
A common reliable approach:
- Try fast text extraction
- Check extracted text quality:
- too little text
- garbled output
- empty pages
- If quality is poor, fall back to OCR
- Merge results intelligently
This saves cost and time versus OCR’ing everything.
11) Plan for scale and cost
For thousands/day:
- containerize workers
- autoscale based on queue depth
- use spot/preemptible instances if acceptable
- separate CPU-bound and IO-bound stages
- cache dependencies and models locally
If OCR is expensive:
- prefilter scanned vs digital
- only OCR pages that need it
- batch requests where supported
12) Security and compliance
PDFs can be risky.
Handle carefully:
- malware-embedded files
- external links
- macros are less common in PDFs, but embedded content can still be dangerous
- sensitive data / PII
Good practices
- scan files before processing
- sandbox parser/OCR workers
- run with least privilege
- encrypt at rest and in transit
- redact or tokenize sensitive fields if needed
- isolate tenant data if multi-tenant
13) A practical reference architecture
A solid baseline:
- API/Ingest service
- uploads PDFs to object storage
- creates job record
- Queue
- one message per document
- Orchestrator
- fans out page jobs if needed
- Worker fleet
- digital extraction workers
- OCR workers
- Result store
- Postgres for metadata/status
- object storage for text/JSON artifacts
- Dead-letter queue
- failed jobs after retries
- Monitoring
- Prometheus/Grafana, CloudWatch, Datadog, etc.
14) Tools that are commonly used
Depending on stack:
Parsing/extraction
pypdfpdfplumberpdfminer.sixpoppler/pdftotext
OCR
- Tesseract
- AWS Textract
- Google Document AI
- Azure Document Intelligence
- OCRmyPDF for preprocessing + OCR layer
Orchestration
- Celery
- Temporal
- Airflow for batch workflows
- Step Functions / Durable Functions
- Kafka consumers / queue workers
15) Suggested implementation checklist
Start with this:
- Upload PDFs to object storage
- Create job records with checksum/doc ID
- Send jobs to a queue
- Build stateless workers
- Detect digital vs scanned PDFs
- Extract text or OCR by page
- Save intermediate and final outputs
- Add retries + dead-letter queue
- Add metrics and alerts
- Add idempotency and deduplication
- Add autoscaling and resource limits
- Build a manual review/reprocess path
If you want the simplest reliable setup
A good “minimum production” version is:
- S3/object storage for PDFs
- SQS/RabbitMQ for job queue
- Dockerized Python workers
pdftotext/pdfminerfor digital PDFs- OCR fallback with Tesseract or managed OCR
- Postgres for status and metadata
- Dead-letter queue + retries
- Monitoring/alerts
If you want, I can also give you:
- a reference architecture diagram,
- a Python-based implementation plan, or
- a production checklist for a specific cloud like AWS, GCP, or Azure.