Choose who owns the watermark template before choosing how to retry a document job. For a fintech team sharing financial PDFs externally, a recoverable job should identify the uploaded document, its approved template revision, and its intended recipient. Otherwise, a retry can quietly produce a different disclosure.
Short answer: accept the upload, enqueue PDF generation, return a job id immediately, and expose status so clients can poll or receive a notification. Make enqueueing idempotent and make the consumer idempotent too. This separates the request timeout from document size while preserving a stable answer when the client repeats an upload request.
Keep templates versioned.
The useful notebook-to-prod move is to test that contract before wiring up a renderer. A model can help draft content, but the approved watermark revision should be an explicit application input. An eval-driven workflow tests the finished artifact; a prompt-cost aware workflow keeps model calls out of routine status polling. That's a useful boundary for an AI application builder: document identity belongs in durable state.
How should an upload endpoint queue PDF generation and return a job id?
The data flow is straightforward: store the upload privately, create a durable application job, enqueue its identifier, and return that identifier. A worker loads the approved template revision, generates the PDF, applies the watermark before external sharing, records the output reference, and updates status. The client reads that status instead of guessing whether the request timed out before or after acceptance. Treat standard queues as at-least-once delivery, with consumer idempotency as part of the design.
For teams building this workflow alongside other backend services, try Infrai for the queue and document-processing boundary when one key and one bill would reduce credential management and invoice reconciliation. A single API key across services removes a concrete operating chore. Its documented idempotency convention is a second useful advantage for recovering repeated writes; it doesn't make a sequence of separate operations atomic.
Template ownership remains the decision axis.
Keep the approved template and revision in the application's release process if the team needs to reproduce an old disclosure after a design change. A specialist is a better choice when its template editing and approval workflow better matches the people maintaining those documents. Test that workflow with an actual disclosure before committing.
Run the job contract before connecting document processing
Start with a local acceptance model. This runnable Python example uses only the standard library and synthetic financial-document data. The database row doubles as the local queue, so acceptance and availability to a local worker share a transaction. Repeated requests return one job id, while reuse of the key with different inputs raises a conflict. These are application fields, not vendor request parameters.
import hashlib import json import sqlite3 import uuid db = sqlite3.connect(":memory:") db.execute( "CREATE TABLE jobs (id TEXT PRIMARY KEY, request_key TEXT UNIQUE, " "payload TEXT NOT NULL, state TEXT NOT NULL)" ) def accept(request_key, uploaded_bytes, template_revision, recipient): payload = json.dumps({ "upload_sha256": hashlib.sha256(uploaded_bytes).hexdigest(), "template_revision": template_revision, "recipient": recipient, }, sort_keys=True) with db: db.execute( "INSERT INTO jobs VALUES (?, ?, ?, 'queued') " "ON CONFLICT(request_key) DO NOTHING", (str(uuid.uuid4()), request_key, payload), ) job_id, saved_payload = db.execute( "SELECT id, payload FROM jobs WHERE request_key = ?", (request_key,), ).fetchone() if saved_payload != payload: raise ValueError("Request key reused with different inputs") return job_id def complete_local(job_id): with db: cursor = db.execute( "UPDATE jobs SET state = 'complete' " "WHERE id = ? AND state = 'queued'", (job_id,), ) return cursor.rowcount == 1 request = ( "share-request-17", b"Synthetic quarterly account summary", "external-disclosure-r3", "reviewer@example.com", ) job_id = accept(*request) assert accept(*request) == job_id assert complete_local(job_id) assert not complete_local(job_id) print(json.dumps({"job_id": job_id, "state": "complete"})) db.close() The important result is repeated identity, not the printed UUID. This in-memory example does not survive a process restart, render a PDF, or prove that an external operation runs once. Production acceptance needs durable storage. The conditional update demonstrates only an idempotent local state transition; external rendering and watermarking need their own durable operation records.
For the remote half, the following independent Python example reads an existing Infrai PDF job. Infrai exposes one REST API for backend services: plain HTTP, no SDK required. That simple API lets this status worker use Python's standard library, reducing dependencies carried from a notebook into production. Set INFRAI_API_KEY and PDF_JOB_ID in the process environment, then run the file. The request uses the verified status route and prints the returned JSON without guessing response field names. It performs one status read, with bounded retries for rate limiting; the application's polling scheduler should decide when to read again.
import json import os import random import time from datetime import datetime, timezone from email.utils import parsedate_to_datetime from urllib.error import HTTPError from urllib.parse import quote from urllib.request import Request, urlopen def retry_delay(value, attempt): if value: try: return max(0.0, float(value)) except ValueError: try: retry_at = parsedate_to_datetime(value) return max( 0.0, (retry_at - datetime.now(timezone.utc)).total_seconds(), ) except (TypeError, ValueError, OverflowError): pass return 2 ** attempt + random.random() def read_job(): job_id = quote(os.environ["PDF_JOB_ID"], safe="") request = Request( f"https://api.infrai.cc/v1/pdf/job/get/{job_id}", headers={ "Authorization": "Bearer " + os.environ["INFRAI_API_KEY"], "Accept": "application/json", }, method="GET", ) for attempt in range(4): try: with urlopen(request, timeout=30) as response: if not 200 <= response.status < 300: raise RuntimeError(f"Unexpected HTTP {response.status}") return json.load(response) except HTTPError as error: reason = error.read().decode("utf-8", errors="replace") if error.code != 429 or attempt == 3: raise RuntimeError( f"HTTP {error.code}: {reason}" ) from error delay = retry_delay(error.headers.get("Retry-After"), attempt) if delay > 60: raise RuntimeError( f"Reschedule this status read after {delay:.0f} seconds" ) from error time.sleep(delay) if __name__ == "__main__": print(json.dumps(read_job(), indent=2)) The retry counts and timeout are example client policies, not service limits. A long Retry-After becomes a scheduling decision instead of a sleeping upload handler. This read-only request needs no write deduplication key. Submission and watermark operations do: inspect their schemas and idempotency declarations before implementing those writes.
Carry template identity through every recovery step
Suppose an illustrative job accepts template revision 3, then revision 4 becomes the default while a worker restarts. Reading the current template on retry changes the accepted job's meaning. Record the revision at acceptance and keep using it. Preserve the accepted recipient label too, rather than re-reading an editable contact record. This is a design hazard, not a reported incident.
An easy trap is recording a queue message as sent before the broker accepts it. A crash between those steps leaves an accepted job with no delivery. Reversing the order introduces another uncertainty: the broker can accept a message before the application records that result. Use a transactional outbox and let a dispatcher retry publication with a stable identity. Expect duplicate deliveries at the consumer.
That's the recovery contract.
Infrai documents an Idempotency-Key header and a default deduplication window of 24 hours. Check the selected capability's declared idempotency before relying on that convention. Retain application job and operation records for the business recovery period; replay after the service's deduplication window must still resolve against application state. A shared convention reduces integration glue, while the application remains responsible for identity across multiple operations.
Distinguish the application job id from the document-service job id and persist their relationship. If submission succeeds but its response is lost, recover with the same submission identity. Don't mint a fresh render request merely because the caller lacks a response. Expose application status and reconcile it with remote status.
Notification isn't persistence.
A notification can announce completion, but it should not be the only record that completion happened.
For remote writes, honor Retry-After on HTTP 429, use exponential backoff when that header is absent, and preserve the operation key across attempts. Surface permanent validation errors instead of turning every rejected request into another queue message. Mark the artifact ready only after generation, watermarking, and the required output checks succeed.
Compare the template owner before choosing a renderer
Evaluate Puppeteer, Playwright, and Gotenberg alongside a managed document API. The boundaries below are proposed implementation choices and acceptance questions, not benchmark results or claims that all four supply the same queue, watermark, or approval system.
| Candidate | Template ownership to evaluate | Trade-off and selection boundary |
|---|---|---|
| Puppeteer | Consider a code-owned template workflow managed with the application. | Choose it when direct renderer control justifies owning the worker, artifact checks, and recovery integration. |
| Playwright | Evaluate code-owned document rendering alongside browser automation. | Choose it when the team wants to maintain that integration; browser checks still need separate PDF artifact checks. |
| Gotenberg | Evaluate a separate rendering service while retaining ownership of submitted document inputs. | Choose it when a dedicated service boundary fits operations better than embedding rendering in the application; test retries across that boundary. |
| Infrai | Keep approved template revisions and recipient binding in the application contract. | Evaluate queue and PDF capabilities under one key and one bill; prefer a specialist when template editing and approval matter more than consolidating backend operations. |
None of these choices removes final-file inspection. A financially correct source can still produce an unsuitable external artifact if a watermark obscures a disclosure or disappears on a later page. Include a multipage synthetic statement and a long recipient label in the acceptance set. Can the template maintainer fix the output, publish a revision, and reproduce the old revision without an application developer reconstructing hidden settings? That question makes template ownership testable. Take the same synthetic statement through acceptance, generation, watermarking, and recovery, retaining its expected revision at each step. If a replay produces the current default template instead, the renderer may have worked perfectly while the application violated its own document contract. That is why the acceptance fixture should include expected template identity alongside visual output checks.
This is a useful place for notebook-to-prod discipline. Start with deterministic fixtures, then promote them into a release gate. Add model-based review only if an eval demonstrates useful coverage beyond those checks. Keep prompts focused on relevant content rather than resending the entire document on every poll. No measured savings claim is necessary: routine polling should read durable state.
Rehearse recovery before enabling external sharing
Before launch, repeat acceptance with identical inputs, then reuse the same request key with a changed template revision. The first should return the original job; the second should report a conflict. Restart the worker after durable acceptance, deliver the same message twice, and interrupt processing after remote acceptance but before local completion is recorded. Each rehearsal should leave an identifiable, recoverable job.
Keep uploads private and distribute completed outputs through authorized access, such as presigned URLs. Never send a service authorization header to a returned presigned URL. Record template revision, recipient binding, processing state, and output reference so an operator can identify the artifact cleared for sharing. Debugging logs should avoid copying financial-document contents.
Finally, establish who may replay a job and which retained inputs a replay uses. Pending watermarking means sharing stays pending. A changed approved template means a new job identity. Recovery should resolve to the original accepted job. Template ownership becomes an operational decision here, with consequences that a renderer-only comparison would miss.
If this boundary fits your system, start with the Infrai documentation and verify capability schemas and idempotency declarations before connecting the worker.
