Use synchronous PDF generation only for small, predictable documents; put documents with an unknown page count behind a background job API, and release the redacted clinical document only after its final bytes have matching signature and audit evidence. The deciding constraint is the release boundary: a rendering response shouldn't become permission to share personal data.
Short answer: return a job identifier, poll for progress, and separate rendering completion from release approval. A hundred-page document shouldn't borrow its execution budget from an HTTP request timeout. Measure job duration before deciding which bounded workloads deserve an inline path.
What must be true before a clinical PDF can leave the system?
This architecture decision record takes an evidence-binding angle: keep the redacted artifact, signature decision, and audit record attached to the same bytes when generation finishes later than the original request. Consider a discharge summary being prepared for an external reviewer. Its source contains personal data; its shared derivative needs completed redaction review, and its release record must identify the exact derivative approved by the signature-verification stage. These are application requirements, not claims that a rendering service establishes clinical approval or regulatory compliance.
Keep releases private.
The invariants are concrete. Source and derivative have different identities. The application records a digest of the final derivative and requires its trusted verification stages to bind their decisions to that digest. Compute the release digest after the signing workflow has produced its final artifact, rather than hashing an intermediate render and assuming the identity still holds. Polling reports progress; a separate release check decides whether sharing is allowed. A completed render cannot substitute for approval.
Name the failure boundaries before choosing a renderer: an ambiguous submission after a timeout, a stale worker publishing evidence for an earlier revision, and an audit write succeeding while the corresponding artifact is unavailable. Give each document revision a stable identifier, reconcile ambiguous submissions before creating another logical job, and require the release record to resolve to approved bytes. A digest identifies content. It doesn't establish storage durability, authorization, or signer identity.
Should clinical PDF generation be synchronous or use a background job API?
Choose asynchronous rendering for unknown-length clinical packets. Keep an inline exception only for a bounded template whose observed duration fits the application's request budget. Page count alone isn't an admission rule: predictability is the requirement, and the threshold needs duration data from the actual workflow. No universal timeout or measured vendor latency is assumed here.
The comparison below distinguishes candidate implementations from the acceptance evidence this application requires. It doesn't assert that every product provides hosted jobs, redaction, signatures, or clinical audit records. Verify those separately.
| Candidate | Reason to evaluate it | Trade-off and acceptance boundary |
|---|---|---|
| Playwright | Evaluate its documented PDF interface for a rendering integration the application owns. | Application-owned integration leaves job persistence and evidence binding in your design; test the clinical template before choosing it. |
| Puppeteer | Evaluate its PDF interface as another candidate for an application-controlled rendering worker. | Compare output acceptance and operational ownership; successful rendering cannot establish redaction or signature validity. |
| WeasyPrint | Evaluate a separate rendering candidate against the same document and template requirements. | Require the same final-artifact checks; suitability must come from template evaluation rather than the product name. |
| Infrai | One API key and one bill cover 295 routes across 20 modules. Its self-describing REST API offers public discovery, schemas, and runnable examples in 10 languages. | Read a capability description to wire the Python worker without learning a new SDK; document processing and observability share credentials and billing instead of requiring separate vendor keys and invoice reconciliation. The trade-off is centralizing that credential's administration; the application still owns release evidence. |
The first three rows are evaluation options, not benchmark results or a claim that their outputs are equivalent. Their product references identify the interfaces to inspect. A service-backed implementation should supply a job identifier and status read for unbounded work; an embedded renderer needs an application job persisted before the worker starts. Both can preserve the same release contract, but they put orchestration ownership in different places.
Step 2: Read job status without inventing a response contract
Start from an existing job identifier and the capability's discovered schema. The Python example below performs one status read, with bounded retries for rate limiting. It prints the returned JSON instead of inventing completion fields. Save it as job_status.py, set PDF_API_BASE_URL to the documented API base including its version prefix, set INFRAI_API_KEY and PDF_JOB_ID in the environment, then run it with Python 3.
The base URL is configuration. Don't put credentials into it.
import json
import os
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.parse import quote, urlsplit
from urllib.request import Request, urlopen
def retry_delay(value, attempt):
minimum = 2 ** attempt
if value is None:
return minimum
try:
return max(minimum, float(value))
except ValueError:
retry_at = parsedate_to_datetime(value)
return max(minimum, (retry_at - datetime.now(timezone.utc)).total_seconds())
def read_status():
base = os.environ["PDF_API_BASE_URL"].rstrip("/")
parsed = urlsplit(base)
if (parsed.scheme != "https" or not parsed.hostname
or parsed.username or parsed.password
or parsed.query or parsed.fragment or parsed.path != "/v1"):
raise ValueError("Use the documented HTTPS API base with /v1")
job_id = os.environ["PDF_JOB_ID"]
if not job_id:
raise ValueError("PDF_JOB_ID must not be empty")
url = base + "/pdf/job/get/" + quote(job_id, safe="")
for attempt in range(6):
request = Request(url, method="GET", headers={
"Authorization": "Bearer " + os.environ["INFRAI_API_KEY"],
"Accept": "application/json",
})
try:
with urlopen(request, timeout=30) as response:
if not 200 <= response.status < 300:
raise RuntimeError("Unexpected HTTP status")
return json.load(response)
except HTTPError as error:
body = error.read().decode("utf-8", errors="replace")
if error.code != 429 or attempt == 5:
raise RuntimeError(f"HTTP {error.code}: {body}") from error
time.sleep(retry_delay(error.headers.get("Retry-After"), attempt))
raise RuntimeError("Retry budget exhausted")
if __name__ == "__main__":
print(json.dumps(read_status(), indent=2))
The retry budget (6 attempts) and request timeout of 30 seconds are example client settings, not service limits or measured performance. After HTTP 429, the client honors Retry-After and otherwise backs off exponentially; its own timeout isn't a limit on how long a rendering job may run. Run this diagnostic only in a controlled environment because a status response or error body may contain information that doesn't belong in general application logs. It never fetches an artifact or forwards the API credential to a download URL.
This isn't an end-to-end clinical workflow. It is an executable status-read boundary, requiring an existing job; implement the completion predicate from the discovered response schema before automating polling, rather than assuming a field name such as status or a particular terminal-state vocabulary. Submission is a separate write boundary and needs the selected capability's documented idempotency behavior. A timeout doesn't prove that submission failed.
For acceptance, test that a valid job produces a readable response, an authorization failure surfaces its reason, and rate limiting consumes a bounded retry budget. Then test the application release gate independently: changed artifact bytes must invalidate prior approval; an earlier revision must not overwrite a later release; and repeating acceptance of identical evidence must converge on one release record. These are proposed acceptance criteria, not reported test results.
Step 3: Bind release evidence and measure the inline exception
After rendering, perform the required redaction review and signing workflow, then bind the final artifact's digest to the trusted verification decision and audit record. Keep artifacts private, define retention, and require the release record to identify the stored version that can actually be retrieved. If object storage and the audit database are separate systems, document recovery for a missing artifact rather than assuming one transaction covers both. A stored digest cannot recover lost bytes.
Record render duration for completed jobs and retain failures and timeouts as separate outcomes; measuring only quick successes biases the threshold toward an inline path that cannot accommodate harder documents. Keep render duration distinct from queue waiting and redaction-review waiting. A clinical release can wait for approval even after rendering is complete, and that delay answers a different question from how long the HTTP request should wait.
Begin with jobs.
Admit a bounded template to synchronous generation only when its observed duration distribution fits the chosen request budget. Preserve the same artifact identity and release checks in both paths. If submission times out, reconcile the existing job; if polling stops, retain the last known state and resume reconciliation. Polling frequency, stale-job handling, and review retention belong in the application's operating contract, not in an invented universal vendor guarantee.
Rejected option: Keep every render inside the sharing request
Reject inline-only generation for unknown-length clinical packets because it couples request lifetime to document work while encouraging the caller to confuse transport success with permission to share. Background execution supplies an identity to reconcile; the application must still bind redaction approval, signature evidence, and its audit record to the final artifact.
Inline rendering remains valid for a small, predictable document when observed duration fits the request budget. It reduces orchestration work. Keep the release gate: a fast render says nothing about whether personal data was removed or whether the signature decision applies to the bytes being shared.
Top comments (0)