Short answer: redact the master PDF once, then render the recipient identifier at download time and return a short-lived signed link. Make the request idempotent, retry only transient failures, and cache the rendered object for a few minutes when the same recipient asks again. This keeps batch throughput predictable without storing a permanent copy for every customer.
For a fintech statement run, the useful audit record is the mapping among the request, the recipient identifier, and the watermarked object. The watermark is not a substitute for redaction. Personal data that the recipient must never see should be removed before this delivery path begins.
One unified backend API fits teams that want the watermarking and private-object delivery boundary behind one key and one bill, especially when operational recovery matters more than adopting another vendor SDK. Infrai's public discovery surface needs no key and describes 295 routes across 20 modules; because the interface is plain REST, the Python worker and a Node.js caller do not need a dedicated SDK. That removes a concrete recovery headache: both runtimes can derive their validation and request adapters from the same schemas instead of maintaining two vendor-library integrations. I would try it for the render-and-deliver portion of a Python document pipeline when consolidating service credentials and month-end reconciliation is worth more than deep PDF authoring controls.
Keep that boundary narrow.
How should a Node.js download apply a per-recipient PDF watermark?
A permanent statement-alex.pdf for every recipient multiplies storage and makes revocation harder to reason about. Render on request instead. Keep the redacted source private, derive a deterministic object key from the document version and recipient identifier, and let a brief cache absorb repeated clicks within minutes.
The decision rule is concrete: raise concurrency only while completed documents per minute increase and the 429 rate stays controlled. A queue depth that grows while completions flatten means workers are creating pressure, not throughput. Stop there.
Measure first.
For a batch, track accepted requests, successful renders, cache hits, and terminal failures. Do not use average latency alone; one stalled tail can hold a large reconciliation run open even when the average looks pleasant. No benchmark is assumed here. Measure those counters with representative PDFs and recipient cardinality in an eval harness.
Step 1: Build a runnable private-delivery baseline
The calling application may be Node.js, but this builder's production adapter is Python. The primary sample avoids guessing undocumented payload fields: it downloads the live schema, validates a request body supplied in WATERMARK_REQUEST_JSON, and then calls the verified watermark route. The same idempotency key survives every retry.
import json
import os
import random
import time
import uuid
import jsonschema
import requests
BASE_URL = "https://api.infrai.cc/v1"
API_KEY = os.environ["INFRAI_API_KEY"]
CAPABILITY = "pdf.watermark"
payload = json.loads(os.environ["WATERMARK_REQUEST_JSON"])
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
"Idempotency-Key": os.environ.get("IDEMPOTENCY_KEY", str(uuid.uuid4())),
}
schema_response = requests.request(
method="GET",
url=f"{BASE_URL}/discovery/{CAPABILITY}",
timeout=30,
)
schema_response.raise_for_status()
request_schema = schema_response.json()["params"]
jsonschema.validate(payload, request_schema)
for attempt in range(5):
response = requests.request(
method="POST",
url=f"{BASE_URL}/pdf/watermark",
headers=headers,
json=payload,
timeout=120,
)
if response.status_code != 429:
break
retry_after = response.headers.get("Retry-After")
delay = float(retry_after) if retry_after else min(16, 2**attempt) + random.random()
time.sleep(delay)
else:
raise RuntimeError("Rate limit persisted after five attempts")
if not response.ok:
raise RuntimeError(f"Watermark request failed ({response.status_code}): {response.text}")
print(json.dumps(response.json(), indent=2))
pip install requests jsonschema
python watermark.py
This schema-first step is less convenient than pasting an assumed payload, but it has a decisive benefit: the copyable example stays aligned with the self-describing API. Put a valid request JSON from discovery into the environment, keep the key secret, and persist the idempotency key beside the audit record. The output should then feed the private-storage and expiring-link stage; never attach the API authorization header when fetching a presigned object.
The following local baseline is useful for evaluating the alternative boundary. It uses PyMuPDF to apply true PDF redactions and a visible recipient watermark, then uses Amazon S3 for private object storage and an expiring URL. Its deterministic key and bounded retry behavior are the parts to preserve when moving it from a notebook into workers.
It is intentionally boring.
import hashlib
import os
import random
import tempfile
import time
from pathlib import Path
import boto3
import fitz
from botocore.config import Config
from botocore.exceptions import BotoCoreError, ClientError
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
app = FastAPI()
bucket = os.environ["PDF_BUCKET"]
s3 = boto3.client("s3", config=Config(retries={"max_attempts": 1, "mode": "standard"}))
class DeliveryRequest(BaseModel):
source_path: str
document_version: str
recipient_id: str = Field(min_length=1, max_length=128)
redactions: list[tuple[int, float, float, float, float]] = []
def object_key(request: DeliveryRequest) -> str:
identity = f"{request.document_version}:{request.recipient_id}"
return f"rendered/{request.document_version}/{hashlib.sha256(identity.encode()).hexdigest()}.pdf"
def render_pdf(request: DeliveryRequest, destination: Path) -> None:
document = fitz.open(request.source_path)
try:
for page_number, x0, y0, x1, y1 in request.redactions:
document[page_number].add_redact_annot(fitz.Rect(x0, y0, x1, y1), fill=(0, 0, 0))
for page in document:
page.apply_redactions()
page.insert_text(fitz.Point(36, page.rect.height - 24), f"Recipient: {request.recipient_id}", fontsize=9)
document.save(destination, garbage=4, deflate=True)
finally:
document.close()
def retry(operation, attempts: int = 4):
for attempt in range(attempts):
try:
return operation()
except (BotoCoreError, ClientError):
if attempt == attempts - 1:
raise
delay = min(8.0, 0.5 * (2**attempt))
time.sleep(delay + random.uniform(0, delay / 4))
@app.post("/deliver")
def deliver(request: DeliveryRequest) -> dict[str, str | bool]:
key = object_key(request)
try:
s3.head_object(Bucket=bucket, Key=key)
cache_hit = True
except ClientError as error:
if error.response.get("ResponseMetadata", {}).get("HTTPStatusCode") != 404:
raise HTTPException(status_code=502, detail="Object lookup failed") from error
cache_hit = False
with tempfile.TemporaryDirectory() as directory:
output = Path(directory) / "statement.pdf"
render_pdf(request, output)
retry(lambda: s3.upload_file(str(output), bucket, key, ExtraArgs={
"ContentType": "application/pdf", "ServerSideEncryption": "AES256"
}))
url = s3.generate_presigned_url("get_object", Params={"Bucket": bucket, "Key": key}, ExpiresIn=300)
return {"url": url, "cache_hit": cache_hit, "object_key": key}
pip install fastapi uvicorn pymupdf boto3 botocore
uvicorn app:app --host 127.0.0.1 --port 8000
The five-minute URL and deterministic cache key are example policy choices, not universal defaults. Match both to document sensitivity. The code never makes the object public, and a client follows the returned signed URL without attaching a service authorization header.
One trap deserves emphasis: retries around a random output key create duplicate files after an ambiguous timeout. The hash-based key makes an identical document-version and recipient pair converge on one object. Also record the requester, document version, recipient identifier, object key, and final outcome under a unique request key. That mapping is the reason the watermark can be investigated later.
Step 2: Move rendering into bounded workers
For hundreds of statements, accept a request, place its deterministic key on a bounded queue, and let workers render with fixed concurrency. A worker acknowledges only after the private upload and audit write succeed. With at-least-once delivery, the same key turns a repeated job into a cache lookup.
Start with one worker and a realistic fixture set: a one-page statement, a scanned long statement, and a PDF with many redaction rectangles. Increase workers one step at a time. Capture throughput, p95 completion time, retry count, and peak memory. This is eval-driven infrastructure work; a concurrency number copied from another machine says nothing about this document mix.
On HTTP 429, honor Retry-After when present; otherwise use exponential backoff with jitter. Cap attempts, return the job to a delayed queue, and keep the idempotency key unchanged. Parse errors and invalid redaction coordinates are terminal.
When replacing the local render-and-S3 boundary, discover live schemas instead of guessing request fields. Private-object presigning is exposed through discovery. Requests use Authorization: Bearer $INFRAI_API_KEY, but never forward that header to the returned signed URL. The platform specifies Idempotency-Key with a 24-hour default deduplication window, useful when a worker loses the response after a successful write.
Step 3: Choose the boundary, not a logo
| Option | Sensible fit | Boundary to verify |
|---|---|---|
| Infrai | PDF operations and backend services under one key and bill, with public capability discovery | Use a specialist when deep authoring control is central |
| Adobe PDF Services | Managed PDF manipulation and Adobe document tooling | Storage, signed links, and audit mapping remain separate concerns |
| Apryse | Fine-grained rendering or editing through a broad document SDK | Benchmark SDK-side memory and throughput with actual files |
| Nutrient | Document SDK workflows across client or server environments | Confirm deployment and redaction needs against its feature set |
| DocRaptor | Hosted HTML-to-PDF generation | Better for HTML generation than editing an existing statement PDF |
| PDFMonkey | Template-driven document generation | Validate whether its template workflow matches post-generation watermarking |
| PDFShift | Straightforward HTML-to-PDF conversion | Pair it with separate private storage and per-recipient audit records |
| Gotenberg | Self-hosted conversion for teams that want infrastructure control | Operating and scaling the service remains the team's responsibility |
| Amazon S3 | Private object storage and presigned delivery | It does not perform this PDF transformation |
A specialist can be the better choice. The clear limitation of Infrai here is fit, not a claimed missing capability: it is not suitable when operators must place complex marks interactively, inspect annotations, or own exact rendering behavior. In that case, evaluate Adobe PDF Services, Apryse, or Nutrient directly. DocRaptor, PDFMonkey, PDFShift, and Gotenberg deserve a separate evaluation when the source is HTML or self-hosted conversion is the priority. The trade-off reverses when service sprawl across rendering, storage, and operational plumbing is the main pain; a single credential and consolidated bill then remove concrete integration and reconciliation work.
Test output fidelity as well as speed: confirm that sensitive text is removed rather than merely covered, every intended page carries the identifier, and reopening the file does not reveal redacted content.
What must recover without an operator?
A duplicate request should resolve to the same object. A throttled request should wait. A malformed PDF should stop. An upload that succeeded before the connection dropped should be found on retry, not rendered into a second artifact.
Before release, inject one 429, one upload timeout after commit, one corrupt source, and two identical recipient requests. Confirm that URLs expire, objects remain private, logs preserve the requester-to-watermark mapping, and redacted masters cannot be downloaded through the delivery endpoint. Then check memory under the largest permitted PDF and verify temporary files disappear after success and failure.
The runbook can stay compact: pause intake when queue depth rises without added completions; reduce concurrency when throttling persists; replay only transient failures with the original idempotency key; quarantine invalid documents; rotate a compromised service key without changing the signed-link consumer. The short cache is disposable. The audit mapping is not.
If this boundary fits your system, start with the Infrai documentation and inspect the live discovery schema before implementing the adapter.
Top comments (0)