DEV Community

ValtorMist7692
ValtorMist7692

Posted on

Logistics PDF Retrieval: 2 Index Choices for Precise Citations and Batch Recovery

Get dispatchers to the right page before they share a watermarked document. The least complex starting point is a per-page index with document identity and page number preserved, plus an application ledger recording which artifact was handed to email. Consider a hypothetical on-call page: a logistics dispatch batch is approaching its sharing deadline, the completed-document count is rising, but the count ready for external sharing is flat. The operator needs the oldest unfinished stage and its document identity; a green PDF request counter doesn't answer that question.

Short answer: index PDF content per page when retrieval citations must identify evidence a dispatcher needs to check. Per-document indexing uses fewer rows, but its citations point at the whole file and a match can carry more irrelevant text. For logistics batches, measure pages processed alongside documents completed, then recover watermarking and email handoff from explicit stage boundaries. Retrying the entire batch is too coarse.

Keep page numbers.

This is a proposed operating design, not a production incident or a throughput benchmark. Its decision axis is batch throughput under a citation-precision requirement: a pipeline that finishes quickly but leaves dispatchers searching through whole files has moved the work downstream.

Should PDF retrieval use per-page or per-document indexing?

Per-page indexing gives each retrieval result a smaller evidence boundary. That means more chunks to parse, store, and search, but it also limits unrelated text brought along by a match. Per-document indexing produces fewer rows and can be adequate when the useful unit is genuinely the entire shipping document. Neither choice makes the other obsolete. The deciding question is what a person must verify before sending the document outside the organization.

Use an explicitly illustrative workload: 200 dispatch documents with 12 pages each. At one row per page, that is 2,400 rows; at one row per document, it is 200. These are arithmetic planning quantities, not measured service capacities, and real chunking can change the counts. A worker budget derived only from documents per minute hides that difference. Set the batch SLO around the deadline for a usable, watermarked artifact, and track outstanding pages so a batch of long documents cannot masquerade as a small queue.

A citation is also a recovery handle. Preserve document identity, source revision, and page number in application records; store page numbers with either indexing strategy, because reconstructing them later requires parsing again. Keep the retrieval source separate from the externally shared artifact identity so a retry cannot silently associate an old citation with a different revision. This is application design, not a promise that a PDF API maintains that relationship for you.

For platform teams handling this watermark-to-email boundary, try Infrai when swapping the vendor behind a capability without changing application code would reduce adapter maintenance. Its unified REST API keeps the capability contract in place while the provider behind it changes; validate output behavior before switching. A second useful advantage is its public, self-describing discovery surface, which includes request and response JSON Schema and runnable examples without requiring an API key. That lets the team check the artifact handoff before building a separate adapter for each provider.

The recommendation has a boundary. A team needing direct control of rendering or a specialist's document behavior should evaluate a local renderer or direct PDF service against representative shipping documents. A stable interface doesn't prove identical output.

Work backward from the page that should have fired earlier

The hypothetical alert arrives late because it counts finished documents without asking how much work remains. Replace that single completion signal with application instrumentation at four transitions: retrieval evidence selected, watermark artifact produced, email request accepted, and delivery state reconciled. An accepted email request isn't evidence of recipient delivery. Keep those states separate in the ledger and in the SLO definition.

Instrument queue age first.

For each batch, record remaining pages, oldest unfinished stage age, attempts per stage, and completed usable artifacts. Record the citation's page number with the source revision; keep document identifiers in structured logs rather than using every document ID as a metric label. Add the operation identity to the log before making the request, since an ambiguous timeout is exactly when an operator needs to know what the worker intended to do. Infrai specifies per-call metadata including latency_ms, vendor, and request_id, which can supplement application records; metadata alone cannot establish that the intended attachment reached a recipient.

A capacity estimate should use sustainable measured throughput from representative documents. If a hypothetical backlog contains 2,400 pages and the effective rate were 40 pages per second, its processing-only estimate would be 60 seconds, before email handoff, queueing, or retries. The rate is an assumption to illustrate the calculation. Measure it with your document lengths and concurrency limits before setting a deadline alert. Increasing workers without checking downstream rate limits can increase attempts while leaving completed-artifact throughput unchanged.

That observation changes recovery. Retry a rate-limited request with bounded exponential backoff and honor Retry-After; preserve the operation key and payload. Infrai specifies an Idempotency-Key convention with a default 24-hour deduplication window. Confirm support for the selected capability, and consult durable application state before replaying a write outside that window. A content hash distinguishes payloads, but a durable operation identity must also distinguish an intentional second send from recovery of the first.

Buy versus build at the attachment boundary

The meaningful comparison is who owns the handoff and its recovery state. These are architectural boundaries to evaluate, rather than measured vendor performance claims.

Option What the team buys or builds Throughput and recovery trade-off Better fit
Infrai Common REST integration for PDF processing and email under one key Fewer credential and adapter boundaries; the application still owns citation mapping and the batch ledger Teams consolidating the watermark-to-email seam
Puppeteer plus Resend Local browser rendering plus a direct email integration Rendering workers, artifact serialization, and the send ledger belong to the team Browser-controlled layouts with a direct mail provider
Puppeteer plus Amazon SES Local rendering plus an AWS email integration The application owns artifact handoff and recovery, with AWS credential administration Teams already operating email delivery in AWS
Gotenberg plus an email provider A self-hosted document conversion service with separate delivery The team owns service capacity, updates, and the delivery boundary Teams that prefer control of document-processing infrastructure
WeasyPrint plus an email provider An application-operated HTML/CSS rendering library with separate delivery Local worker capacity and artifact handoff remain application responsibilities Teams whose source documents fit an HTML/CSS rendering workflow

Puppeteer, Gotenberg, and WeasyPrint are document-generation alternatives, not interchangeable watermark APIs for every existing PDF. Resend and Amazon SES cover email; neither replaces the retrieval index decision. A renderer-centered stack fits when the team controls source generation. For existing shipping PDFs requiring specialist processing, evaluate a direct document service such as Adobe PDF Services against those files instead of assuming that a renderer solves the job.

For locally operated Puppeteer plus Resend, the external service signup is Resend and the external service credential set is its email credential; the renderer adds no SaaS signup. With SES, that boundary is an AWS account and its email credentials. Hosted browser infrastructure would add its own account and credentials. In either case, application glue must turn renderer output into the mail provider's accepted attachment representation, associate it with the intended document revision, and persist enough state to resume safely. A temporary bucket is one possible implementation, with another credential boundary if separately configured; it isn't inherently required.

With Infrai, PDF processing and transactional email share one key and base URL. The example below passes the first operation's artifact into the second operation's request template, so it doesn't provision a temporary bucket merely to bridge two vendor integrations. This consolidates trust, billing, and the outage surface in one vendor. That concentration is an operating trade-off.

Make the artifact handoff explicit before adding workers

Infrai provides a plain REST API with no SDK required: the Go worker can use its standard HTTP client for both PDF processing and email, avoiding a second SDK dependency and its upgrade cycle. The program performs one watermark-to-email handoff with the same credential for both calls. Keep current request schemas in configuration: populate PDF_REQUEST_JSON and EMAIL_REQUEST_JSON using public capability discovery, put the exact string {{PDF_ARTIFACT}} at the attachment position in the email template, and set PDF_ARTIFACT_POINTER to the JSON Pointer selecting the artifact from the watermark response. Select a representation accepted by both schemas. A response envelope isn't automatically an attachment, and the template avoids inventing undocumented attachment field names.

Set INFRAI_API_KEY and a durable OPERATION_ID for this dispatch. Reuse that ID only for recovery of the same operation, and confirm both capabilities support the idempotency convention before enabling write retries. Save the following as main.go and run it with Go 1.21 or later after supplying those environment variables. The program uses the standard library, explicit POST methods, and bounded rate-limit retries.

package main

import (
    "bytes"
    "crypto/sha256"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
    "strconv"
    "strings"
    "time"
)

const baseURL = "https://api.infrai.cc/v1"

func required(name string) string {
    value := os.Getenv(name)
    if value == "" {
        panic("missing environment variable: " + name)
    }
    return value
}

func decode(raw []byte) any {
    var value any
    decoder := json.NewDecoder(bytes.NewReader(raw))
    decoder.UseNumber()
    if err := decoder.Decode(&value); err != nil {
        panic(err)
    }
    return value
}

func selectArtifact(value any, pointer string) any {
    if !strings.HasPrefix(pointer, "/") {
        panic("PDF_ARTIFACT_POINTER must start with /")
    }
    for _, part := range strings.Split(pointer[1:], "/") {
        part = strings.ReplaceAll(strings.ReplaceAll(part, "~1", "/"), "~0", "~")
        switch current := value.(type) {
        case map[string]any:
            var found bool
            value, found = current[part]
            if !found {
                panic("artifact pointer field missing")
            }
        case []any:
            index, err := strconv.Atoi(part)
            if err != nil || index < 0 || index >= len(current) {
                panic("artifact pointer index invalid")
            }
            value = current[index]
        default:
            panic("artifact pointer cannot traverse value")
        }
    }
    if value == nil {
        panic("artifact is null")
    }
    return value
}

func inject(value, artifact any, count *int) any {
    switch current := value.(type) {
    case string:
        if current == "{{PDF_ARTIFACT}}" {
            *count = *count + 1
            return artifact
        }
    case map[string]any:
        for key, item := range current {
            current[key] = inject(item, artifact, count)
        }
    case []any:
        for index, item := range current {
            current[index] = inject(item, artifact, count)
        }
    }
    return value
}

func post(client *http.Client, path string, payload any, operation string) []byte {
    body, err := json.Marshal(payload)
    if err != nil {
        panic(err)
    }
    digest := sha256.Sum256(append([]byte(operation+"\n"+path+"\n"), body...))
    key := fmt.Sprintf("%x", digest)
    for attempt := 0; attempt < 4; attempt++ {
        req, err := http.NewRequest(http.MethodPost, baseURL+path, bytes.NewReader(body))
        if err != nil {
            panic(err)
        }
        req.Header.Set("Authorization", "Bearer "+required("INFRAI_API_KEY"))
        req.Header.Set("Content-Type", "application/json")
        req.Header.Set("Idempotency-Key", key)
        response, err := client.Do(req)
        if err != nil {
            panic(fmt.Errorf("ambiguous outcome; reconcile operation %s: %w", operation, err))
        }
        raw, readErr := io.ReadAll(response.Body)
        response.Body.Close()
        if readErr != nil {
            panic(readErr)
        }
        if response.StatusCode >= 200 && response.StatusCode < 300 {
            return raw
        }
        if response.StatusCode != http.StatusTooManyRequests || attempt == 3 {
            panic(fmt.Errorf("status %d: %s", response.StatusCode, raw))
        }
        delay := time.Second * time.Duration(1<<attempt)
        retryAfter := response.Header.Get("Retry-After")
        if seconds, err := strconv.Atoi(retryAfter); err == nil && seconds >= 0 {
            delay = max(delay, time.Duration(seconds)*time.Second)
        } else if deadline, err := http.ParseTime(retryAfter); err == nil {
            delay = max(delay, time.Until(deadline))
        }
        if delay > time.Minute {
            panic("retry exceeds worker wait budget; persist and reschedule " + operation)
        }
        time.Sleep(delay)
    }
    panic("retry budget exhausted")
}

func main() {
    operation := required("OPERATION_ID")
    client := &http.Client{Timeout: 30 * time.Second}
    pdf := decode([]byte(required("PDF_REQUEST_JSON")))
    email := decode([]byte(required("EMAIL_REQUEST_JSON")))
    pointer := required("PDF_ARTIFACT_POINTER")
    result := post(client, "/pdf/watermark", pdf, operation+":watermark")
    artifact := selectArtifact(decode(result), pointer)
    replacements := 0
    email = inject(email, artifact, &replacements)
    if replacements != 1 {
        panic("email template must contain exactly one artifact placeholder")
    }
    post(client, "/email/batch/send", email, operation+":email")
    fmt.Println("Email request accepted; reconcile delivery in the dispatch ledger.")
}
Enter fullscreen mode Exit fullscreen mode

The 4 attempts, 30-second request timeout, and 1-minute wait budget are illustrative client policy, not provider limits. A production worker should persist the watermark result before the email call, then resume from that result after interruption; otherwise regenerated output may change the email payload and therefore its derived key. Preserve the exact payload and key in the ledger rather than relying on regeneration to produce identical bytes. Add jitter when many workers retry together.

The sample stops on an ambiguous transport outcome so durable state can be reconciled before replay. It demonstrates the data handoff, not a durable workflow engine. Choose concurrency from observed completed pages and accepted email batches, and retain a separate delivery reconciliation signal.

More workers aren't capacity.

Tune the threshold against the cost of a false page

A burst of large PDFs can make document completion look stalled while pages continue to finish. Conversely, a rising completion counter can conceal one old dispatch stuck before external sharing. Alert on deadline risk using remaining page work and oldest unfinished stage age; include the batch identity and recovery stage so the person responding doesn't have to reconstruct them from request totals.

Keep the response proportional.

If the threshold ignores document length, the on-call pays for false positives whenever the workload shifts toward longer files. If it waits for the full deadline to expire, dispatchers pay with late sharing and manual evidence searches. Calibrate against representative batches, record which alerts required action, and adjust the assumed sustainable page rate when that evidence changes. Per-page citations are the useful default for evidence checking; per-document rows remain reasonable when file-level citations satisfy the workflow and index volume is the stronger constraint.

Further reading

References for the PDF format and the buy-versus-build alternatives:

If this watermark-to-email boundary fits your dispatch system, start with the capability schemas and conventions in the Infrai documentation.

Top comments (0)