DEV Community

NyxenL29
NyxenL29

Posted on

Hosted PDF API vs Local Libraries: How to Handle Medical Intake Latency Under Load

Short answer: choose a hosted PDF API when referral intake needs burst capacity, consistent rendering, and an auditable boundary that your team cannot operate reliably; keep a local library when data residency, offline operation, or predictable low latency outweighs that operational relief. The deciding constraint is the signature and audit trail around each referral, not the convenience of producing a file.

A referral packet is part of a clinical workflow. A delayed or unsigned document can stall triage, while a silently different rendering can make an approval hard to defend later. I treat PDF generation as a queue with an SLO, not as a formatting helper.

Measure twice.

What should a hosted PDF API solve at production scale?

Start by writing the failure budget. Measure intake-to-document latency at p50, p95, and p99, split by payload size and concurrent jobs. A service that is fast at ten requests but queues for six seconds at 500 concurrent referrals has failed the real test. Run the same test with a cold worker pool, a warmed pool, and a deliberately throttled dependency, because a single happy-path number hides the queue that coordinators actually experience. Set a deadline, enqueue work when the deadline cannot be met, and make the job idempotent so a retry cannot create two signed packets.

For medical referral intake, the durable record should include the source payload hash, template version, signer identity, timestamp, and the resulting PDF hash. Store those fields beside the object, then append an immutable event when the document is released to an outside practice. The PDF is an output; the audit trail is the control.

Hosted capacity is useful during an insurer-driven spike, but the network hop becomes part of your latency distribution. You also inherit a provider's quotas, regional routing, and retention semantics. Your contract should state timeout behavior and deletion guarantees in terms your compliance team can test.

How do latency, signatures, and audit trails change the design?

Use a two-stage path. The intake request validates and records intent, then a worker renders and signs the packet. A status endpoint lets the caller distinguish queued, complete, and rejected work without guessing from a timeout. Keep the original referral immutable; corrections create a new version linked to the prior hash.

Here is the shape of a small Go worker. The interfaces are deliberately generic so the same tests can exercise a local renderer or a hosted adapter.

type Renderer interface {
    Render(ctx context.Context, input []byte, template string) ([]byte, error)
}

type Signer interface {
    Sign(ctx context.Context, pdf []byte, keyID string) ([]byte, error)
}

func BuildPacket(ctx context.Context, r Renderer, s Signer, referral []byte) ([]byte, error) {
    pdf, err := r.Render(ctx, referral, "referral-v3")
    if err != nil {
        return nil, fmt.Errorf("render referral: %w", err)
    }
    return s.Sign(ctx, pdf, "clinical-signing-key")
}
Enter fullscreen mode Exit fullscreen mode

The worker records a correlation id before calling either interface. On timeout, it marks the attempt unknown and lets a reconciler query the job record; it does not blindly submit again. I once assumed a five-second client timeout protected the SLO. It did not: a retry storm multiplied the queue, and p99 became the only metric that told the truth.

When is a local PDF library the safer choice?

Local rendering wins when referrals must remain inside a private network, when an offline clinic must continue operating, or when a measured workload fits comfortably on capacity you already patch and monitor. It removes a network dependency and makes version pinning explicit. The cost is yours: font files, image handling, sandboxing, CVE response, and deterministic output across operating-system upgrades.

A hosted API is a poor fit when its region or retention policy cannot satisfy your data-processing agreement, when your signing key may not leave your trust boundary, or when a hard real-time workflow cannot tolerate remote queueing. Stick with a local library in those cases, even if the hosted path looks easier to launch.

The trade-off is operational, not ideological:

Concern Hosted API Local library
Burst capacity Provider absorbs peaks; quotas must be tested You provision headroom and autoscaling
Latency Network and remote queue add variance Mostly CPU and I/O; your load tests are decisive
Audit evidence Request and response metadata need contractual retention You own logs, hashes, and access controls
Signing boundary Depends on key-management integration Keys can stay in your environment
Maintenance Less renderer patching, more dependency governance Full patching and compatibility burden

How do you verify and roll back PDF generation safely?

Load-test with production-shaped referral packets: scanned pages, long notes, uncommon Unicode, and concurrent signer calls. Record queue age, render duration, signature duration, retry count, and output hash mismatches. Test cancellation and duplicate delivery, then sample PDFs by hash rather than by filename.

Canary a template version against a small clinic cohort. A rollback means stopping new jobs for that version, draining or quarantining in-flight work, and restoring the previous template without rewriting already released records. Keep both versions available long enough to explain an audit. Your mileage may vary because font and scan distributions differ; I'm not sure any synthetic benchmark can predict a rural clinic's 99th percentile until its real packets are in the test set.

The practical decision rule is simple: choose remote capacity when your team can prove the provider's latency, residency, signing, and deletion behavior under your SLO; build locally when those controls are non-negotiable or when operating the renderer is cheaper than accepting that external dependency. Either way, make hashes, versions, and release events first-class data.

References

Top comments (0)