Design a PDF-to-Markdown Document Conversion System
System DesignModel answerLast updated
Design a scalable, multi-stage document processing architecture to transform complex PDFs into Markdown across synchronous streaming and asynchronous batch workflows.
Architect an enterprise-grade inference engine that converts incoming PDF documents into formatted Markdown text.
Assume the following pretrained/prebuilt modules are available as black-box dependencies:
split_pdf(pdf_bytes) -> List[np.ndarray]: A CPU-bound task that extracts individual pages from a document and rasterizes them into high-resolution image matrices.ocr(page_images) -> List[str]: A GPU-bound deep learning model that performs visual layout detection and optical character recognition on a batch of page images, returning structured text elements.to_markdown(ocr_elements) -> str: A memory-bound post-processing worker that formats OCR structured outputs into Markdown syntax and assembles final page sections.
System Requirements & Bottlenecks
The processing pipeline contains three distinct, resource-heterogeneous phases:
- CPU-heavy page extraction & rendering
- GPU-heavy deep-learning OCR inference
- Memory-heavy document assembly and post-processing
You must account for two distinct operating modes:
- Low-Latency Synchronous Pipeline (Single-Doc Focus): A client submits a single large PDF (up to ~1,000 pages) over an active API connection and expects formatted Markdown results returned with minimal end-to-end processing delay.
- High-Throughput Asynchronous Pipeline (Multi-Tenant Focus): Hundreds of tenants concurrently submit documents of varying sizes (from 1 page to thousands of pages). The service must optimize for overall throughput, cost efficiency, GPU utilization, and fair multi-tenant queue scheduling.
Your architecture should specify API contracts, stream/batch orchestration, dynamic scaling mechanisms, failure recovery, state persistence, and resource management across both modes.
Hints
Hint 1
Consider using object storage references (S3 pointers) rather than passing raw image bytes across network boundaries or message queues.
Hint 2
For synchronous streaming, map-reduce page processing using HTTP/2 Server-Sent Events (SSE) or WebSockets allows progressive delivery while maintaining strict page ordering.
Hint 3
Dynamic micro-batching on the GPU stage is critical to prevent idle GPU cycles during low-traffic periods while maintaining high batch efficiency under heavy load.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Architecture Overview
Converting high-volume PDFs to Markdown requires orchestrating three distinct computational profiles:
- Page Extraction & Rendering: CPU-heavy (rasterization, image extraction).
- Visual OCR & Layout Parsing: GPU-heavy (deep learning inference using model workers).
- Markdown Reconstitution: RAM-heavy (AST manipulation, cross-page entity resolution, layout alignment).
To achieve efficiency, raw rasterized page images (which can exceed tens of megabytes per page) must never be passed directly through message broker payloads. Instead, intermediate outputs are offloaded to an Object Store (e.g., AWS S3 or MinIO), and lightweight metadata pointers are passed between pipeline stages via queues.
+-----------------------------------------------------------------------------------+
| Ingestion Layer |
| +---------------------+ +----------------------------+ |
| | Sync API (gRPC/SSE)| | Async API (REST / Webhook) | |
| +----------+----------+ +-------------+--------------+ |
+--------------|-------------------------------------------------|------------------+
| |
v v
+-----------------------------+ +----------------------------------+
| In-Memory Pipeline (Sync) | | Durable Event Bus (Async) |
| Task Orchestration | | Kafka / RabbitMQ Topics |
+--------------+--------------+ +---------------+------------------+
| |
+-----------------------+-------------------------+
|
v
+-----------------------------------+
| Stage 1: CPU Worker Pool |
| - split_pdf() |
| - Write page images to Object Store|
+-----------------+-----------------+
|
v
+-----------------------------------+
| Stage 2: GPU Inference Pool |
| - Dynamic Batching Engine |
| - ocr() running on CUDA |
+-----------------+-----------------+
|
v
+-----------------------------------+
| Stage 3: Memory Worker Pool |
| - to_markdown() |
| - Page reordering & Markdown AST |
+-----------------+-----------------+
|
v
+-----------------------------------+
| Object Store & Result Delivery |
| - S3 Storage / Client Stream |
+-----------------------------------+
Part 1: Synchronous API Pipeline (Single Large Document SLA)
When a client submits a massive document (e.g., 1,000 pages) over a synchronous connection, executing the stages serially across the whole document creates high latency and violates HTTP connection timeouts.
1. Synchronous API Interface
A streaming API contract prevents connection timeouts and provides progressive delivery. We utilize HTTP/2 or HTTP/3 Server-Sent Events (SSE) or gRPC bi-directional streaming.
POST /v1/convert/stream HTTP/2
Host: api.pdf-parser.io
Content-Type: application/pdf
Accept: text/event-stream
[Binary Data Payload]
Stream Response Payload (SSE Events):
event: page_complete
data: {"page_number": 1, "total_pages": 1000, "markdown": "# Section 1\nExecutive Summary..."}
event: page_complete
data: {"page_number": 2, "total_pages": 1000, "markdown": "## Financial Statements..."}
event: job_finished
data: {"status": "COMPLETED", "total_pages": 1000}
2. Micro-Pipelining & Streaming Execution
To minimize time-to-first-token (TTFT) for page 1 and maintain continuous GPU utilization:
- Streaming Splitter: The CPU worker reads the PDF byte stream and yields rasterized pages as soon as individual page objects are decoded, rather than waiting for the entire document to split.
- Page Worker Pipelining: As soon as page $i$ is rendered:
- Page $i$ image is stored in temporary high-speed NVMe storage / Redis / S3.
- A lightweight execution context containing
(job_id, page_number, image_ptr)is pushed to the GPU queue.
- Single-Job Dynamic Micro-Batching:
- The GPU inference engine pulls pages for this job into micro-batches (e.g., optimal throughput size $B = 8$ or $16$).
- The worker executes
ocr(micro_batch)and immediately pushes the outputs to the post-processing worker queue.
- Reorder Buffer (Priority Heap):
- Because pages within a batch or parallel worker pools finish out-of-order (e.g., page 5 finishes before complex page 3), the sync API worker maintains a Min-Heap Reorder Buffer keyed by
page_number. - A pointer tracks
next_expected_pagestarting at1. - As tasks complete, outputs enter the heap. The stream flushes elements from the heap to the client as long as
heap.peek().page_number == next_expected_page.
- Because pages within a batch or parallel worker pools finish out-of-order (e.g., page 5 finishes before complex page 3), the sync API worker maintains a Min-Heap Reorder Buffer keyed by
import heapq
from typing import Dict, Generator
class PageReorderBuffer:
def __init__(self, start_page: int = 1):
self.next_expected_page = start_page
self.min_heap = [] # Stores tuples: (page_number, markdown_str)
def add_page(self, page_number: int, markdown: str) -> Generator[str, None, None]:
heapq.heappush(self.min_heap, (page_number, markdown))
while self.min_heap and self.min_heap[0][0] == self.next_expected_page:
_, md_content = heapq.heappop(self.min_heap)
yield md_content
self.next_expected_page += 1
Part 2: Asynchronous API Pipeline (Multi-Tenant High-Throughput)
Under heavy multi-tenant load, system objectives shift from minimizing latency for a single job to maximizing global GPU throughput, ensuring operational isolation, and enforcing tenant fairness.
1. Asynchronous API Interface
POST /v1/jobs HTTP/1.1
Host: api.pdf-parser.io
Content-Type: application/json
{
"document_url": "s3://customer-bucket/doc_10k_pages.pdf",
"webhook_url": "https://client.internal/hooks/pdf_callback",
"priority": "standard"
}
Response (202 Accepted):
{
"job_id": "job_9f8a7b6c5d",
"status": "QUEUED",
"poll_url": "https://api.pdf-parser.io/v1/jobs/job_9f8a7b6c5d"
}
2. Queue Architecture & Cross-Job GPU Batching
To maximize GPU utilization, GPU workers pull pages across different jobs and tenants to fill batches completely.
[ Job 1 Pages ] [ Job 2 Pages ] [ Job 3 Pages ]
\ | /
v v v
+-------------------------------------------------------+
| Multi-Tenant Priority / Fair Queue |
+---------------------------+---------------------------+
|
v
+-----------------------------------+
| Dynamic Adaptive Batcher Engine |
| Timeout: 10ms OR Max Batch: 32 |
+-----------------+-----------------+
|
v
+-----------------------------------+
| GPU Tensor Core Array |
+-----------------------------------+
Dynamic Batching Logic in GPU Workers
To balance latency and saturation, the GPU service implements an Adaptive Dynamic Batcher:
- Max Batch Size ($B_{max}$): 32 pages (saturates GPU memory without causing OOM).
- Max Wait Window ($\Delta t$): 10 ms.
- Worker Execution: The worker collects page references from the queue until $B_{max}$ pages are accumulated OR $\Delta t$ expires.
import time
from typing import List, Any
class AdaptiveGPUBatcher:
def __init__(self, queue, max_batch_size: int = 32, max_delay_ms: float = 10.0):
self.queue = queue
self.max_batch_size = max_batch_size
self.max_delay_sec = max_delay_ms / 1000.0
def collect_batch() -> List[Any]:
batch = []
start_time = time.time()
while len(batch) < self.max_batch_size:
time_left = self.max_delay_sec - (time.time() - start_time)
if time_left <= 0:
break
item = self.queue.pop(timeout=time_left)
if item:
batch.append(item)
elif len(batch) > 0:
# If we have items and timeout hit, exit loop
break
return batch
3. Fair Multi-Tenant Scheduling
Without fair scheduling, a single tenant submitting a 10,000-page document would starve all other users sharing the GPU cluster.
Implementation: Weighted Fair Queueing (WFQ) / Deficit Round Robin (DRR)
- Instead of a single FIFO queue for page OCR tasks, maintain per-tenant queues (
queue:tenant_A,queue:tenant_B). - The central scheduler selects tasks using Weighted Round Robin.
- Per-Tenant Page Ingestion Limits: A rate limiter caps the number of active, un-processed pages a single job can inject into the GPU queue to $N = 200$. Additional pages remain unrendered on CPU workers until the job's inflight GPU quota frees up.
Technical Trade-offs & Production Considerations
1. Scaling Signals & Autoscaling Policy
Each worker pool scales independently using metrics tailored to its bottleneck:
| Worker Pool | Primary Resource | Autoscaling Signal (KEDA / HPA) | Target Metric Value |
|---|---|---|---|
| CPU (Splitter) | Compute / Disk | Queue Depth of incoming unparsed PDFs | > 5 items per worker |
| GPU (OCR Engine) | Tensor Cores / VRAM | Average Batch Size & GPU Duty Cycle | GPU Util < 85% triggers scale-up |
| Memory (Markdown) | System RAM | Unordered Page Reorder Buffer Depth | Consumer lag < 100ms |
2. Fault Tolerance, Retries, and Idempotency
- Page-Level Checkpointing: Job progress is tracked in a distributed database (e.g., DynamoDB or PostgreSQL) using a page state bitmask.
- Page states:
PENDING->SPLIT->OCR_DONE->MD_DONE.
- Page states:
- Idempotency: If a GPU node crashes mid-batch, the message broker visibility timeout expires, re-queueing only the unacknowledged pages of that batch.
- Poison Pill Routing: If a specific page image triggers an unrecoverable CUDA fault or memory access error, a retry counter increments. After 3 retries, the page is routed to a Dead Letter Queue (DLQ), and a placeholder comment
<!-- Page X conversion failed -->is injected into the final Markdown AST so the entire document does not fail.
3. Intermediate Artifact Retention & Memory Management
To prevent out-of-memory crashes when parsing huge documents:
- Storage Offloading: Rasterized page images are immediately written to object storage under
s3://bucket/tmp/{job_id}/pages/{page_num}.pngwith an automated 24-hour lifecycle expiry policy. - Zero-Copy Payload Passing: Queue messages contain short JSON pointers:
{
"job_id": "job_9f8a7b6c5d",
"page_num": 42,
"s3_image_uri": "s3://bucket/tmp/job_9f8a7b6c5d/pages/42.png"
}
- GPU workers download images asynchronously via high-throughput localized memory caching or shared local NVMe drives.
Architectural Comparison Matrix
| Architectural Axis | Synchronous Pipeline (Part 1) | Asynchronous Pipeline (Part 2) |
|---|---|---|
| Primary Goal | Minimize End-to-End Latency & TTFT | Maximize Throughput & GPU Efficiency |
| Transport Layer | HTTP/2 Streaming (SSE) / gRPC | REST API + Event Queue (Kafka/S3) |
| Batching Horizon | Micro-batching within single document | Cross-tenant macro-batching across job queues |
| Backpressure | Backpressure propagated directly to HTTP stream | Enforced via tenant queue caps & rate limits |
| Ordering Engine | Transient In-Memory Priority Heap | Persistent Distributed KV / Database Index |