Run OCR only on pages that lack usable text, preserve the original PDF, and treat extraction, recognition, normalization, and indexing as four independently replayable stages. That decision rule protects fidelity while putting a hard boundary around render cost: a born-digital page should not be rasterized merely because it arrived in the same archive as a scan.

TL;DR: classify every page before rendering; retain coordinates and provenance with the recognized text; publish a new search generation only after relevance and fidelity checks pass. Use content-addressed artifacts and idempotent jobs so that a parser, OCR engine, or index mapping can change without forcing the whole archive through an expensive and risky rebuild.

This matters in a fintech archive because finding a customer name is insufficient if the result points to the wrong page, drops a minus sign, or detaches a value from its table heading. Searchability is an operational promise: given a query, return the right document and a defensible page location within an explicit service objective. OCR confidence can help triage work, but it is not the promise.

Why does searchable PDF fail even when OCR succeeds?

PDF is a presentation format with a defined document model, not a guarantee that reading order, words, or searchable text will be available in the form an indexer expects. ISO 32000-2 defines the format. An archive can therefore contain text-bearing pages, image-only scans, mixed pages, rotated pages, forms, signatures, and tables under the same file extension.

The first costly mistake is file-level classification. A PDF with one cover page containing selectable text and 80 scanned statement pages is not “already searchable.” The opposite mistake is equally bad: rendering all 81 pages throws away usable character data and pays OCR cost where extraction would have been cheaper and more faithful. Classify pages, not files.

Recognition has a second failure boundary. A text string without page number, bounding box, source digest, method, and pipeline version cannot support a trustworthy result view or a controlled reprocessing job. Indexing that string may produce a hit, yet an operator cannot trace the hit back to the evidence. That is a data-lineage defect disguised as a search feature.

Small errors carry unequal risk. Losing punctuation in a mailing address differs from losing the decimal point in an amount, so a single document-wide confidence threshold is a weak control. Route low-confidence regions, fields with financial significance, and pages with suspiciously sparse output to separate queues. Do not let one average hide them.

This approach has a limitation: it is a poor fit when the archive cannot retain page-level artifacts or when the search experience needs only document titles supplied by a trusted catalog. In those cases, the provenance machinery costs more to operate than it protects. It is also unsuitable as the sole control for extracting regulated financial fields; retrieval-oriented OCR should identify evidence for review, not silently become an accounting system of record.

Build the four stages around immutable evidence

The safe data flow is source PDF -> page inventory -> text observations -> search generation. Each arrow produces an immutable artifact identified by the source digest and the stage version. Metadata can advance; evidence does not get overwritten.

Stage 1 validates the input, computes a digest, inventories pages, and attempts native text extraction. It records enough signals to decide whether each page needs rendering, including extracted character count, geometry availability, and obvious image coverage. The classifier should be conservative and testable. There is no universal character-count threshold; derive one from a labeled sample of the archive, then version it.

Stage 2 renders only pages selected for OCR. Keep the render configuration in the job identity because resolution, color handling, crop boxes, and rotation affect both recognition and cost. Enforce page, pixel, byte, and processing-time limits before work enters the expensive queue. A malformed or extreme document should be rejected or isolated, not allowed to consume unbounded capacity.

That boundary is expensive.

Stage 3 normalizes native extraction and OCR into the same observation shape. Preserve the raw output beside the normalized form. Hyphen repair, whitespace folding, Unicode normalization, and reading-order heuristics can improve retrieval, but every transformation is another place where financial meaning can change. Store transformation versions and retain offsets back to raw observations.

Stage 4 writes a new index generation. Documents become visible only after every required page observation is durable, and an alias or generation pointer moves only after verification. Partial indexing is acceptable only if the product explicitly exposes partial status; silently presenting a half-indexed statement as complete breaks the service contract.

package pipeline import ( "context" "crypto/sha256" "encoding/hex" "fmt" ) type PageObservation struct { DocumentDigest string Page int Method string // "native" or "ocr" PipelineVersion string Text string Boxes []Box } type Box struct { X, Y, Width, Height float64 } type Store interface { Exists(ctx context.Context, key string) (bool, error) Put(ctx context.Context, key string, value PageObservation) error } func observationKey(digest string, page int, version string) string { sum := sha256.Sum256([]byte(fmt.Sprintf("%s:%d:%s", digest, page, version))) return hex.EncodeToString(sum[:]) } func persistOnce(ctx context.Context, store Store, obs PageObservation) error { key := observationKey(obs.DocumentDigest, obs.Page, obs.PipelineVersion) ok, err := store.Exists(ctx, key) if err != nil || ok { return err } return store.Put(ctx, key, obs) } 

The interface is deliberately boring. A retry writes the same logical artifact, while a pipeline change creates a different key. In production, the store must provide an atomic create-if-absent operation; the separate Exists and Put calls above express the contract but do not prevent concurrent writers by themselves.

Set budgets from page traffic, not archive size

Capacity planning starts with pages requiring OCR per unit of time, not PDF count or stored bytes. Track the distribution of pages per document and the fraction selected for OCR. Then model steady-state ingest separately from a backfill, because allowing a historical migration to share an unconstrained queue with fresh uploads is an avoidable SLO failure.

A useful envelope is arrival rate x OCR-page fraction x render-and-recognition time. Measure those terms on representative documents; do not borrow throughput figures from a different corpus. Add headroom for retries and skew, cap concurrency against memory and downstream quotas, and apply backpressure before the worker pool saturates. Fast failure is preferable to a queue whose age grows without a bound.

Define separate objectives for availability, freshness, and quality. For example, “search generation published within the agreed ingest window” is a freshness objective, while “verified query returns the labeled document and page” is a quality objective. The actual targets belong to the service owner and risk function; inventing a percentage without a corpus and business requirement creates theater, not reliability.

The buy-versus-build decision should follow the operational boundary the team is prepared to own:

Boundary Managed capability Self-hosted capability Decision pressure
Rendering and OCR Less engine maintenance; external limits and data handling require review More tuning and isolation control; more patching and capacity work Fidelity needs, residency, on-call load
Workflow state Faster adoption if retries and idempotency are explicit Full control over queues and artifact lifecycle Backfill scale, auditability, lock-in
Search index Operations may be delegated; mappings and export paths still matter Portable data path; team owns upgrades and recovery Query behavior, recovery objective, staffing

No row decides the architecture alone. A managed OCR boundary can coexist with a self-controlled observation schema and index, which limits replacement cost, while a self-hosted engine is not truly portable if its output leaks directly into a proprietary mapping. The durable asset is the tested corpus plus the normalized, traceable observation contract.

The trade-off is concrete. Suppose an 81-page statement package contains one native-text cover, 79 scanned statement pages, and one intentionally blank separator. File-level detection marks the package searchable and misses 79 pages; unconditional rendering pays for all 81 and asks recognition to reproduce text that was already exact on the cover. Page classification sends 79 pages to OCR, retains the native cover, and records the blank page as an expected observation rather than a processing failure. Yet the classifier itself now needs a version, test cases, and an escalation path for ambiguous pages. That extra operational state is the price of controlling render cost without pretending mixed PDFs are homogeneous. A small archive with infrequent ingest may reasonably accept unconditional rendering because its simpler runbook reduces on-call burden; once backlog age or render demand threatens the freshness objective, page classification earns its keep.

Verify relevance and fidelity before publication

Create a labeled evaluation set before choosing thresholds. It should represent born-digital statements, low-resolution scans, rotated pages, tables, handwriting if the archive accepts it, and documents whose contents challenge the parser. Keep evaluation documents out of tuning decisions when possible; otherwise improvements can be memorization wearing a benchmark label.

Verification needs three layers. First, structural checks confirm that page counts match, every indexed observation points to a source digest and page, boxes remain inside page bounds, and no required stage is missing. Second, recognition checks compare text and critical fields against labels. Third, retrieval checks issue realistic queries and verify the returned document, page, snippet, and highlight position.

Test the miss path too.

False evidence is worse.

A result for an account identifier that is absent can be more dangerous than a missed result because it creates false evidence. Include confusable characters, punctuation-sensitive amounts, repeated headers, empty pages, and near-duplicate documents. Record metrics by document class rather than reporting one archive-wide average; class-level regressions are what a rollout can act on.

Observability should connect queue age, stage latency, retry count, OCR selection rate, pages processed, rejected limits, and publication lag through the same job and source identifiers. Do not put document text, customer identifiers, or raw financial fields into logs. Emit bounded metadata and keep sensitive artifacts in access-controlled storage with an explicit retention policy.

Roll out by generation and make rollback cheap

Start with a shadow generation that receives the same accepted documents but serves no user traffic. Compare it against the current generation on the labeled queries, inspect class-level deltas, and reconcile document and page counts. Promotion is a metadata operation only after those checks pass.

Then expose the candidate to a limited read cohort while writes continue producing immutable observations. Monitor freshness, retrieval quality signals, queue age, and resource saturation together; a faster recognizer that increases false matches has not improved the service. Keep the previous index generation readable through the observation retention window.

Rollback should move the read pointer to the previous verified generation. It should not rerun OCR, mutate source files, or depend on deleting the candidate. Pause publication when an invariant fails, quarantine the affected document class, and replay only the stage whose version or configuration changed. This is why stage boundaries and provenance matter: they convert recovery from a full archive rebuild into a bounded operation.

The final acceptance test is mundane and strict: retrieve a document using a representative query, open the original PDF at the returned page, and confirm that the highlighted region supports the result. If the system cannot make that chain auditable, the archive is indexed but not yet dependable.

References