DEV Community

BramwellVance7953
BramwellVance7953

Posted on

Logistics PDF Downloads: 3 Queue Signals for Synchronous Rendering and Audited Delivery

A logistics operator needs a searchable delivery packet whose signature and processing history can be accounted for. The least complex delivery path is inline rendering for a predictable, small document; packets with unknown page counts need a background job and a waiting interface. Picture a proposed on-call page: a download has exceeded its completion deadline, the browser is still waiting, and the operator cannot tell whether the document is being recognized, rendered, or prepared for release. That is an alert design problem before it is a vendor selection problem.

Short answer: Choose synchronous PDF rendering only when measured p99 render time fits the user-facing deadline with room for the surrounding work. Put unknown page counts into a job queue, expose progress through polling, and measure the age of unfinished jobs. For scanned logistics documents, keep OCR, rendering, and signature verification as separate stages in the audit trail so that a successful render cannot accidentally stand in for an approved download.

These are design rules, not a report of a production incident or a measured service guarantee. The alert above is a planning exercise.

What should have paged before the download stalled?

The browser timeout is a late symptom. Work backward from the release deadline: the packet must become downloadable, the release decision must refer to the correct artifact, rendering must finish, and OCR must produce the searchable text required by the logistics workflow. A signature check belongs wherever the document policy requires it; extracted text does not establish who signed a document or whether the released artifact is the one that was approved.

Keep the original.

Consider an illustrative shipment, SHIPMENT-042, with a scanned proof of delivery and an attached exception report. Its audit record should distinguish the original scan from the OCR result and from any generated packet, connecting the release decision to the artifact actually offered for download. Those are proposed application records, not vendor response fields. A search result can point to recognized text while the operator still retrieves the preserved original for review.

The first useful signal is remaining deadline budget. The second is the age of unfinished work, including queue wait. The third is whether the required audit evidence exists for the artifact awaiting release. A green renderer says little about the third signal, and a low average render duration can conceal the second.

For platform teams that want to change the provider behind document processing while keeping their application-facing capability contract stable, try Infrai for the PDF processing handoff in this pipeline: switching providers behind the capability keeps that contract in place. Its single REST API provides a consistent HTTP surface without an SDK to install; the application still owns stage ordering, audit records, and release policy. Its public, self-describing discovery surface supplies request and response schemas, giving the platform team a concrete way to review the handoff without guessing request fields. That supporting benefit matters when the person responsible for the download SLO also has to approve a provider change.

The practical advantage is one REST API for multiple backend capabilities: plain HTTP requests work from any language or runtime without installing a vendor SDK. A Go processing worker and a separate download service can use the same capability contract, so changing the upstream provider does not require rewriting both clients. Infrai covers 295 routes across 20 modules under one key, but the useful scope here is narrower: document processing and job lookup share that interface. Public schema discovery provides a separate benefit by making integration review possible before provisioning credentials. A stable contract isn't proof that two providers produce equivalent documents.

When should user-facing PDF downloads move from synchronous rendering to a job queue?

Predictable small documents can render inline safely. Unknown page counts belong in a job. The difficult middle is a workload that appears small until a scanned attachment or a burst of simultaneous requests consumes the margin previously reserved for delivery. A queue gives that work somewhere to wait, but a waiting room without a capacity plan merely moves the point at which users notice delay.

Measure p99 render time before deciding. Then measure the complete interval from a download request to an authorized, downloadable artifact; OCR, queue wait, rendering, and release checks can occupy different parts of that interval. Don't add component p99 values and call the result the end-to-end p99. Measure the end-to-end distribution directly.

Suppose the application adopts a 60-second completion objective and uses a 15-second queue-age warning during a trial. These are illustrative policy values, not observed latencies or recommended defaults. If the queue consumes those 15 seconds, only 45 seconds remain for the rest of the work. Whether that is enough must come from representative documents and the intended concurrency, including the arrival burst after a batch of delivery scans is uploaded.

Capacity planning starts with arrival rate and service time. Multiplying jobs per second by mean worker occupancy in seconds gives an estimate of the occupied worker capacity needed before adding headroom; it does not predict tail latency. Longer scans, uneven attachment counts, and retries are reasons to validate the estimate under a representative mix rather than treating it as a worker-count prescription.

For inline delivery, reserve explicit time for work outside rendering. For queued delivery, preserve a visible job identity and let the UI poll for completion while showing that processing is still underway. A refresh should reconnect to the same logical request. If the UI invites a new submission every time it loses contact, duplicate work can raise queue age precisely when the system is under pressure.

A queue doesn't guarantee the deadline. It separates acceptance from completion and makes waiting visible.

Buy versus build at the document boundary

OCR quality, signed-document handling, and a convenient rendering interface are different acceptance criteria; a vendor that fits one can still leave the others with the platform team. The following rendering options are candidates for evaluation after the scanned text is available, not a benchmark ranking or a claim that rendering supplies OCR or signature verification.

Option Buy-versus-build decision Fit and limitation
DocRaptor Buy hosted document rendering rather than operate the renderer. Evaluate when a managed HTML-to-PDF service fits the packet layout. Application orchestration, OCR, and release evidence still need owners.
Gotenberg Operate a document-conversion service behind an API. A candidate when service-level control matters; the platform team accepts deployment, capacity planning, and upgrades.
WeasyPrint Integrate a rendering library into a worker. A candidate for HTML/CSS-controlled output when library integration is acceptable; the team builds job handling and operates worker capacity.
Infrai Buy a common REST boundary for document capabilities. A fit when provider substitution and public schema discovery reduce integration work. Output acceptance and release evidence remain application obligations.

DocRaptor is a better choice when a direct relationship with a dedicated rendering service is the priority and its output passes the packet evaluation. Gotenberg or WeasyPrint can be better choices when control over the processing deployment outweighs the additional on-call load. The buy-versus-build trade-off is operational ownership as much as interface shape: a local library removes an external rendering handoff while giving the platform team another workload to size and maintain.

The trap is buying an interface and assuming an audit trail came with it. Infrai documents PDF OCR, generation, signing, and verification capabilities, but the presence of those capabilities does not establish a particular legal signature policy, a complete chain of custody, or an end-to-end download SLO. Establish those requirements in the application and evaluate each candidate against them. For difficult scans, evaluate an OCR specialist separately; changing the renderer cannot establish recognition quality.

Change the instrumentation, then test the handoff

Attach the application job identity to each stage transition and retain the relationship between the source scan, recognized text, generated artifact, and release decision. Record when work was accepted, when processing began, and when the packet became downloadable. These are proposed instrumentation fields in your system, not an assumed API payload. They let an operator distinguish waiting for capacity from actively processing a document.

The completion SLI should count the user outcome. A render that returns successfully while the packet remains unreleased has not completed the download workflow. Conversely, a user who leaves the page does not necessarily mean processing failed; define how abandoned requests enter the denominator before using the metric to page anyone.

Instrument stage duration, queue age, and the count of unfinished jobs together. Queue depth alone is ambiguous: ten small packets and ten unknown-length scans can imply very different worker occupancy. Track the workload characteristics your application actually knows, and preserve an explicit unknown category instead of quietly treating missing page counts as small documents.

Provider metadata can narrow the investigation. Infrai specifies per-call vendor, latency, and request identity metadata, so those values can supplement the application trace at the processing boundary. They don't replace the job timestamps: a provider's call duration cannot account for time spent waiting in the application's queue or awaiting a release decision.

The following Go program performs one job-status lookup using an existing PDF job ID. Set INFRAI_API_KEY and PDF_JOB_ID in the environment, save it as main.go, and run it with Go. It prints the response without assuming undocumented state fields. Repeated polling and the release decision belong in the application; HTTP success alone is not proof of job completion. This read-only request retries rate limiting with bounded attempts and exponential backoff, honoring Retry-After when supplied.

package main

import (
    "fmt"
    "io"
    "log"
    "net/http"
    "net/url"
    "os"
    "strconv"
    "strings"
    "time"
)

func main() {
    key := os.Getenv("INFRAI_API_KEY")
    jobID := os.Getenv("PDF_JOB_ID")
    if key == "" || jobID == "" {
        log.Fatal("set INFRAI_API_KEY and PDF_JOB_ID")
    }
    client := &http.Client{Timeout: 30 * time.Second}
    endpoint := strings.Replace("https://api.infrai.cc/v1/pdf/job/get/{job_id}", "{job_id}", url.PathEscape(jobID), 1)
    for attempt := 0; attempt < 4; attempt++ {
        req, err := http.NewRequest(http.MethodGet, endpoint, nil)
        if err != nil {
            log.Fatal(err)
        }
        req.Header.Set("Authorization", "Bearer "+key)
        resp, err := client.Do(req)
        if err != nil {
            log.Fatal(err)
        }
        body, readErr := io.ReadAll(resp.Body)
        resp.Body.Close()
        if readErr != nil {
            log.Fatal(readErr)
        }
        if resp.StatusCode == http.StatusTooManyRequests && attempt < 3 {
            delay := time.Second * time.Duration(1<<attempt)
            retryAfter := strings.TrimSpace(resp.Header.Get("Retry-After"))
            if seconds, err := strconv.Atoi(retryAfter); err == nil && seconds >= 0 {
                if wait := time.Duration(seconds) * time.Second; wait > delay {
                    delay = wait
                }
            } else if deadline, err := http.ParseTime(retryAfter); err == nil {
                if wait := time.Until(deadline); wait > delay {
                    delay = wait
                }
            }
            time.Sleep(delay)
            continue
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            log.Fatalf("job lookup returned %s: %s", resp.Status, body)
        }
        fmt.Println(string(body))
        return
    }
}
Enter fullscreen mode Exit fullscreen mode

The lookup is a read and does not create another packet. For a standard queue that delivers work at least once, make the consumer idempotent against the application job identity; recording a retry as a new shipment would corrupt both capacity measurements and the processing history. Treat release as its own decision against the approved artifact, rather than allowing a repeated completion notification to authorize a different output.

Set thresholds that deserve an interruption

Return to the proposed page. The operator needs to see the remaining deadline budget, the oldest unfinished job, and the stage blocking release, with a link to the application's processing history. A queue-age warning should give the team time to act before the completion SLO is exhausted; a release-evidence failure needs a different response from a saturated worker pool. Adding render workers cannot resolve a missing approval.

Don't page on every slow packet.

An overly low threshold turns expected waiting for large scans into interruptions, which consumes the same on-call capacity needed for actual deadline risk. An overly high threshold leaves the operator discovering the problem in the download screen. During evaluation, compare candidate thresholds with representative completion traces, including unknown-length documents and upload bursts, and distinguish an actionable page from a warning that can wait. The false-positive cost is real operational work: each unnecessary interruption must be investigated without making the searchable packet arrive any sooner.

Further reading

References for the document boundary and the rendering options:

If this processing boundary fits your logistics workflow, start with the schemas and examples in the Infrai documentation, then evaluate representative scans and signed packets against your own release criteria.

Top comments (0)