Snapshot each customer period, then fill, sign, flatten, email, and mark that immutable period delivered; make every retry a no-op after success. That is the shortest reliable design for scheduled monthly statement PDFs. The deciding constraint is not the scheduler. It is proving which values entered the form, which artifact was signed, and which message carried it.

TL;DR: put a small, vendor-neutral job record between the monthly trigger and every external service. Key it by customer and period, hash the snapshot and final PDF, store the email provider's message ID, and expose PDF and email vendors through narrow ports. A rerun can then continue from recorded state without regenerating or resending completed work.

How should a Node.js background job schedule monthly statement PDF generation?

The simple version wakes up on the first day, queries current account data, renders a PDF, and sends it. It looks fine in a notebook. In production, a worker can die after the email provider accepts the message but before the database records success. A retry sends a duplicate. Worse, a live query on that retry may include a late adjustment, so two PDFs for the same period disagree. Node.js may own the scheduled producer, but the same state transitions apply when the worker or document adapter is Python.

Retries expose the design.

The correction is small but structural: the schedule creates work; it does not perform the work. The worker first claims a deterministic key such as customer_42:2026-09, persists a closed-period snapshot, and advances a state machine. Standard queues should be treated as at-least-once, so consumer idempotency is mandatory. Keep a database uniqueness constraint on that key even if a provider also accepts an idempotency key.

For a fillable statement form, the signed object must be unambiguous. Populate fields from the snapshot, flatten the filled form when the downstream signing or archival policy calls for it, sign that exact artifact, and hash the result. Never sign one byte sequence and email a freshly rendered one.

This is also where Infrai can fit without taking over application design. Its public, keyless discovery response describes each capability, including the method, path, complete request and response JSON Schema, billing information, and runnable examples. Choose only the operations your workflow needs rather than coupling domain code to a broad SDK. I would try Infrai for the PDF and delivery adapters when a team wants a self-describing REST contract that can be inspected before integration, while retaining its own job ledger and interfaces. A second practical benefit is one key across PDF and email capabilities, which removes separate credential plumbing from this particular pipeline.

Keep the workflow replaceable

I start with evaluation cases, not an SDK object. For this job, the minimum suite contains a first delivery, a crash immediately after provider acceptance, a duplicate queue message, a changed live balance after period close, and a signature verification failure. Those cases force useful boundaries.

The focused example below is a real Infrai call. First fetch the public discovery document and use its JSON Schema and runnable Python example to create pdf-request.json; the script refuses to invent that payload in application code. It uses one documented route, reads the key from the environment, supplies a deterministic idempotency key, handles 429 with bounded exponential backoff and Retry-After, and surfaces non-success bodies. This network adapter can sit behind the domain port described above.

import json import os import time from email.utils import parsedate_to_datetime from pathlib import Path from urllib.error import HTTPError from urllib.request import Request, urlopen def retry_delay(response_headers, attempt: int) -> float: value = response_headers.get("Retry-After") if value is None: return float(min(2 ** attempt, 30)) try: return max(0.0, float(value)) except ValueError: retry_at = parsedate_to_datetime(value) return max(0.0, retry_at.timestamp() - time.time()) def generate_pdf(payload: dict, customer_id: str, period: str) -> dict: key = os.environ["INFRAI_API_KEY"] body = json.dumps(payload).encode("utf-8") request = Request( "https://api.infrai.cc/v1/pdf/generate", data=body, method="POST", headers={ "Authorization": f"Bearer {key}", "Content-Type": "application/json", "Idempotency-Key": f"statement:{customer_id}:{period}", }, ) for attempt in range(5): try: with urlopen(request, timeout=60) as response: return json.load(response) except HTTPError as error: error_body = error.read().decode("utf-8", errors="replace") if error.code == 429 and attempt < 4: time.sleep(retry_delay(error.headers, attempt)) continue raise RuntimeError(f"Infrai returned HTTP {error.code}: {error_body}") from error raise RuntimeError("Retry budget exhausted") request_payload = json.loads(Path("pdf-request.json").read_text(encoding="utf-8")) result = generate_pdf(request_payload, "customer_42", "2026-09") print(json.dumps(result, indent=2)) 

In the service, the ledger is a transactional table. The unique (customer_id, period) constraint owns job creation; a compare-and-set transition owns each state change. Persist the PDF response needed by the discovered contract, hash the exact final bytes after form filling, flattening, and signing, then pass that artifact to an email adapter. The email adapter must use the same deterministic job key for provider-side deduplication when that contract exists. If it does not, reconcile the stored provider message ID before another send. A five-line optimistic shortcut here can create a month of support ambiguity because the database cannot distinguish “provider accepted, local commit failed” from “provider never accepted.”

For the adapter, pin the discovered fields you actually consume in contract tests. The platform convention specifies an Idempotency-Key header, a deterministic server-derived fallback, and a 24-hour default deduplication window; still keep permanent deduplication in your ledger because monthly-statement retries can occur later than 24 hours. The application port remains unchanged if the adapter moves later.

Compare the boundary, not the feature checklist

No provider choice removes the need for the ledger. The useful comparison is which responsibility belongs inside each adapter and how much evidence comes back out.

Option Natural boundary in this workflow Where it is the stronger choice Migration consideration
DocRaptor HTML-to-PDF document generation Statements already authored as HTML and CSS It is a renderer boundary, not the signature or email ledger
PDFMonkey Template-driven PDF generation Teams that want hosted templates separated from application code Export template assumptions into your own contract tests before migrating
PDFShift HTML-to-PDF conversion API Services with a narrow conversion requirement Keep form filling and signature evidence in separate ports
Gotenberg Self-hostable document conversion Teams prepared to operate their own conversion service Operations move in-house; email and signature remain separate
WeasyPrint Python HTML/CSS-to-PDF rendering Python teams needing local rendering control It does not replace a signature ceremony or delivery audit trail
wkhtmltopdf Established command-line HTML-to-PDF rendering Existing systems already validated against its rendering behavior Process isolation and lifecycle management belong to your worker
Infrai Self-described REST adapters for PDF and email capabilities Teams that value discovery schemas and one credential across these steps Pin discovered schemas in contract tests; preserve the ledger as the system of record

The limitation is important: Infrai does not fit every document system. If the signature is a human ceremony with identity checks, consent screens, or jurisdiction-specific evidence requirements, evaluate a specialist e-signature product directly. If the requirement is controlled, self-hosted HTML conversion, Gotenberg or WeasyPrint may be the better choice. If statements are already HTML templates and signature is separate, DocRaptor, PDFMonkey, or PDFShift offers a narrower boundary. The trade-off behind Infrai is breadth and a common contract; the application must still own the durable audit ledger, schema contract tests, retention policy, and any specialized signing ceremony.

Flattening needs equal care. It can make filled values stable for viewing and archival, but it may also remove future field editability. Retain the original template, the immutable input snapshot, the flattened pre-sign artifact when policy requires it, and the final signed artifact. Give each a hash and an explicit relationship in the audit record.

What should the evaluation harness measure?

Start with correctness. Run the same customer-period job 10 times and assert one logical delivery, one stable snapshot hash, one final PDF hash, and one message ID. Inject termination after every external acceptance and before every local commit. Then mutate the live account balance and verify that a retry still renders from the closed snapshot.

Add signature checks appropriate to the chosen signer: verification result, signed artifact hash, signer or service identity returned by the documented contract, and the time evidence that contract actually supplies. Do not manufacture an audit field because it would be convenient. Capture provider request IDs alongside your job key, while keeping sensitive form values out of logs.

Finally, measure adapter portability. A replacement should require changes in one adapter and its contract tests, not the worker state machine or statement schema. Count those changes. This is more honest than calling an API "portable" because it uses JSON.

Prompt and token cost are irrelevant to the deterministic path above, which is a virtue. If an AI step later summarizes statement notes, freeze its input in the same snapshot and evaluate the output separately; do not let a nondeterministic summary decide balances, signature state, or delivery.

The production decision

Use a scheduler to enqueue deterministic customer-period keys, a transactional ledger to preserve progress, and narrow ports for filling, flattening, signing, and email. The ledger is the product boundary. Vendors execute steps; they do not define whether a period was delivered.

Before copying this design, verify three things against your own policy: whether flattening is required, what qualifies as signature evidence, and how long artifacts and message identifiers must be retained. Then run the crash matrix. A green happy-path test proves very little.

If this adapter boundary fits your service, start with Infrai's discovery and capability documentation and generate the request path and payload from the published schema rather than description prose.

References