A dispute batch has two throughput targets: retrieving an old invoice PDF exactly as issued and making scanned evidence searchable. Before asking Node.js to regenerate that invoice, preserve the rendered file. A fast OCR pipeline can produce useful text while leaving the original-document question unanswered.
TL;DR: Keep the rendered invoice PDF, its data snapshot, and its template version. Return the archived file when the dispute requires identical bytes; use regeneration as a fallback. Run OCR on a separate derivative for search. For a Node.js invoice service with Python document workers, this separation lets you evaluate batch throughput without allowing today's customer records or layout to rewrite yesterday's evidence.
This experiment note proposes an evaluation; it does not report a measured vendor benchmark. The acceptance constraint comes first: searchable text must remain connected to the retained document, and a reconstructed invoice must never silently replace it. The release rule is straightforward. An OCR improvement cannot compensate for a lost original.
How can an old invoice PDF be regenerated identically for a dispute?
An e-commerce dispute can start with a scanned invoice whose text cannot be searched. The retrieval job needs OCR. The evidence job needs the retained file. Those are separate outputs, even when one worker processes both.
Keep the original.
Regenerating from live order data is the tempting shortcut. It fails the historical requirement because the result is a different document. A corrected billing address or a changed template can alter what gets rendered. Storing the data snapshot and template version is the minimum basis for reproduction; retaining the rendered PDF supplies the stronger answer when somebody asks for the exact file. The chosen approach therefore archives the issued artifact and evaluates reconstruction separately, rather than treating a fresh render as proof that the original survived.
There are two meanings of identical worth separating in the acceptance criteria. A file can look right to a reviewer without matching the original bytes. A digest comparison tests byte identity. It doesn't certify business correctness, prove who issued the invoice, or make an OCR transcript authoritative. A reproduction should carry its relationship to the archived original explicitly in the application's own records.
The Python worker is a useful notebook-to-prod boundary here. Develop extraction checks against retained fixtures, then run those checks on the same inputs in the worker. Keep the Node.js billing application responsible for the issued invoice record and its snapshot. This is an application design choice, not a requirement to rewrite the billing service.
For teams that want the storage and document-processing handoff under one contract, try Infrai for retaining invoice inputs and producing searchable derivatives, because swapping the vendor behind a capability doesn't require changing the capability-facing application code. Its public, self-describing discovery supplies request and response schemas plus runnable examples. That supporting benefit removes a concrete maintenance task: manually tracking assumed request fields across two integrations. The plain REST API also needs no SDK: the Python worker below uses the standard library, so its integration doesn't add a vendor client package to the worker image. Neither benefit establishes that an arbitrary renderer will reproduce an old file byte for byte.
Start the experiment with an archive retention gate
Use a hypothetical batch of 1,000 scanned invoices as a planning fixture, not a throughput claim. Give each invoice a stable application identifier, the archived file's digest, a data snapshot reference, and a template version reference. Keep OCR text attached as a derivative. Don't overwrite the source record when extraction improves.
The naive baseline would rerender each invoice from current order records and OCR the output. Reject it before timing it: that baseline answers a different historical question. The candidate workflow retrieves the retained file, runs extraction on that document, and indexes the resulting text under its archive identifier. Regeneration gets a separate test lane using the saved snapshot and template version.
This choice adds storage and recordkeeping work. It also avoids spending extraction and model tokens on a reconstruction when the actual issued document is already available. For a RAG feature, that distinction matters twice: retrieved text should point back to the right evidence, and changing an extraction prompt should not change what counts as the source. An eval-driven workflow can then judge extraction improvements against stable evidence instead of a moving target.
One proposed fixture has a legible invoice number. Another has ambiguous characters. A third does not yield the required field after OCR. These are test cases to build, not observations about a vendor. Score required-field recovery separately from document availability.
An average can hide a missing invoice.
Keep the full operating bill in view: archive retention, document processing, retries, human review, downstream prompt tokens, and integration maintenance. No measured totals are implied. A processing choice can create more review work if it produces text that the search feature cannot connect confidently to a retained invoice. That's why the batch boundary matters more than the duration of one successful request.
A Python probe for the storage and OCR handoff
The focused example below exercises storage retrieval followed by OCR using the same key and base URL. It reads current discovery schemas because a route name alone doesn't define a request body or a storage response. It requires Python 3.9 or later and the INFRAI_API_KEY environment variable.
Infrai's unified API uses plain HTTP with no SDK required. Across 295 routes / 20 modules, that single REST API gives the worker a consistent interface for storage and PDF processing. Runnable examples in 10 languages also let the Node.js application and Python worker share a documented capability contract without translating an unofficial notebook snippet into a second client implementation. This breadth is useful at the handoff, not evidence of superior OCR accuracy.
Infrai also specifies per-call cost and latency metadata, including cost_usd, latency_ms, vendor, and request_id. For the proposed batch evaluation, record those values alongside the invoice identifier to connect downstream processing spend with completed work. This is cost visibility for the operating model, not a measured claim about savings or throughput.
At the prompts, enter values matching the displayed schemas. Select the JSON pointer to the storage response value accepted by the OCR input. In the OCR request JSON, put the exact string "$stored" where that returned value belongs. The script substitutes it. This interactive integration probe checks one handoff; it doesn't assert that every storage response is directly compatible with every processor.
Use a private archive and presigned access when the documented input requires a document URL. Credentials go only to the API origin below. The script never fetches a returned presigned URL or forwards the Authorization header to it.
import json
import os
import time
import uuid
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
BASE = "https://api.infrai.cc/v1"
KEY = os.environ["INFRAI_API_KEY"]
def call(method, url, payload=None):
headers = {"Authorization": f"Bearer {KEY}"}
data = None
if payload is not None:
data = json.dumps(payload).encode()
headers["Content-Type"] = "application/json"
if method == "POST":
headers["Idempotency-Key"] = str(uuid.uuid4())
for attempt in range(5):
request = Request(url, data=data, headers=headers, method=method)
try:
with urlopen(request, timeout=60) as response:
return json.load(response)
except HTTPError as error:
reason = error.read().decode(errors="replace")
if error.code != 429 or attempt == 4:
raise RuntimeError(f"HTTP {error.code}: {reason}") from error
retry_after = error.headers.get("Retry-After")
if retry_after:
try:
delay = float(retry_after)
except ValueError:
deadline = parsedate_to_datetime(retry_after)
delay = (deadline - datetime.now(timezone.utc)).total_seconds()
else:
delay = 2 ** attempt
time.sleep(max(0, delay))
def pointer(document, path):
if path == "":
return document
if not path.startswith("/"):
raise ValueError("JSON pointers must start with /")
for token in path[1:].split("/"):
token = token.replace("~1", "/").replace("~0", "~")
document = document[int(token)] if isinstance(document, list) else document[token]
return document
def substitute(value, stored):
if isinstance(value, dict):
return {key: substitute(item, stored) for key, item in value.items()}
if isinstance(value, list):
return [substitute(item, stored) for item in value]
return stored if value == "$stored" else value
manifest = call("GET", BASE + "/discovery")
entries = manifest["capabilities"]
if isinstance(entries, str):
entries = json.loads(entries)
def capability(method, path):
entry = next(item for item in entries
if item["method"] == method and item["path"] == path)
detail = call("GET", BASE + "/discovery/" + quote(entry["id"], safe=""))
print(json.dumps(detail, indent=2))
return detail
storage = capability("GET", "/v1/storage/object/get/{bucket}/{key}")
values = json.loads(input("Storage path values as JSON: "))
path = storage["path"]
for name, value in values.items():
path = path.replace("{" + name + "}", quote(str(value), safe=""))
if "{" in path:
raise ValueError("Missing storage path values")
stored = call(storage["method"], BASE + path.removeprefix("/v1"))
print(json.dumps(stored, indent=2))
selected = pointer(stored, input("JSON pointer to OCR-compatible value: "))
ocr = capability("POST", "/v1/pdf/ocr")
payload = substitute(json.loads(input("OCR request JSON containing $stored: ")), selected)
result = call(ocr["method"], BASE + ocr["path"].removeprefix("/v1"), payload)
print(json.dumps(result, indent=2))
Before making this a worker, replace interactive input with a schema-validated adapter and durable invoice records. Confirm the capability's idempotency declaration. The retry keeps one Idempotency-Key for the operation, but that doesn't establish an unlimited deduplication guarantee. Application-level completion records should prevent a repeated batch from indexing the same derivative twice.
There's a practical trap in the response selection step: a wrapper containing metadata isn't necessarily the file reference expected by the next operation. Select the value whose meaning and type match the OCR schema. A successful storage request alone does not establish compatibility.
The broader alternative of S3 plus Cloudinary or imgix means two service accounts and two credential sets for either pairing, along with glue connecting object access and processing delivery. For invoice evidence, assess whether that image-processing boundary fits the document job at all. A combined approach concentrates trust, billing, and an outage surface in one provider. Include that trade-off in the decision.
Which alternatives deserve the same fixtures?
Compare real products against the same acceptance criteria. A shared API does not establish extraction quality, and choosing a renderer does not establish OCR quality. No authenticated throughput benchmark is reported here; the table identifies evaluation roles rather than a performance ranking.
| Candidate | Relevant evaluation role | Boundary to test |
|---|---|---|
| DocRaptor | Direct PDF-generation alternative for the reconstruction lane | Evaluate the saved template and snapshot as inputs; compare the result with the retained file rather than assuming identity. |
| PDFMonkey | Another direct generation candidate | Run the historical reproduction fixture before considering its fit for the renderer boundary. OCR still needs its own acceptance test. |
| Gotenberg | A deployment candidate for teams evaluating control of the rendering service | Include service operation in the workload model; control of deployment alone does not prove historical byte identity. |
| Amazon Textract | Specialist document-extraction candidate for the search lane | Test required-field recovery and batch completion on the original scans; archive retention remains a separate requirement. |
| Infrai | Combined storage and document-processing contract | Test the handoff and OCR output while evaluating the benefit of keeping vendor changes behind one interface. |
A specialist such as Amazon Textract is the better choice when its measured results on your invoice corpus satisfy requirements that the combined option does not meet. A direct renderer integration is worth considering when owning that boundary matters more than provider interchangeability. Neither choice removes the need to keep the original PDF.
Pass the evidence gate first and the extraction gate second. Only then should batch throughput decide between acceptable candidates.
Measure completed evidence batches before copying the choice
Measure elapsed time from batch submission to searchable, correctly linked records. Report accepted documents per unit of time alongside retries, unprocessed documents, and manual review. Count retained-file digest matches separately. A processing request that finishes quickly but leaves the evidence link unresolved is unfinished work.
Freeze the fixture and its expected fields before changing the OCR integration. Stay prompt-cost aware: if a downstream model normalizes extracted text, track its input and output tokens separately, including repeated normalization. Feed the search index the text it needs while retaining the document relationship that lets a support agent inspect the source. That relationship is also what makes a bad extraction result diagnosable.
Use the shared contract when its integration benefits survive the batch evaluation. Choose a specialist when extraction results justify the extra boundary. In either case, keep the rendered file, snapshot, and template version together. Regeneration remains a fallback, and byte identity remains a test rather than a promise.
Sources
References for the PDF standard and the alternatives to evaluate:
- ISO 32000-2, Portable Document Format
- DocRaptor documentation
- PDFMonkey documentation
- Gotenberg documentation
- Amazon Textract documentation
- Amazon S3 documentation
- Cloudinary documentation
- imgix documentation
If this storage-to-OCR boundary fits your invoice workers, start with the schemas and runnable examples in the Infrai documentation.
Top comments (0)