DEV Community

SeraphinaLyn7139
SeraphinaLyn7139

Posted on

Express Poll Status for Node.js Background PDF Merge Workers with Signing Integrity

The operational constraint is irreversible signing: once a contract bundle is signed, fixing page order, a missing exhibit, or ambiguous provenance means producing a new artifact and a new audit event. The defensible choice is to merge asynchronously from an immutable input manifest, verify the exact output before exposing it for signature, and make status polling report durable state rather than worker activity.

TL;DR: let Express accept and validate a manifest, persist a job plus its ordered inputs, and return 202 Accepted with a status URL. A worker claims the job idempotently, reads each PDF from immutable storage, assembles the bundle in manifest order, writes to a temporary object, verifies it, then atomically publishes the final object and its digest. Only the published digest may cross the signing boundary.

A concrete production case is a developer-tools service receiving a master services agreement, a data-processing addendum, and several exhibits, then producing one server-side contract bundle with an audit trail. I treat the manifest as evidence, not transient queue payload. That is the invariant. A queue can deliver twice; a process can die; a client can poll late. None of those events may change which bytes are eligible for signature.

What actually failed if the job says complete?

A green worker log proves little. The dangerous failure is split-brain completion: the database says succeeded while the final object is absent, truncated, or derived from inputs that changed after submission. Another is semantic success with the wrong page sequence. PDF assembly preserves application-supplied order; the format cannot infer that Exhibit B belongs after Exhibit A.

Logs lie by omission.

Model only queued, running, succeeded, and failed. Persist timestamps, attempt count, manifest digest, output digest, and a stable error code. A transition to succeeded belongs beside the already-published object's key, byte length, and digest. Object storage and a relational database do not share a transaction, so publish the immutable object first, then commit success; a retry should detect and verify that object instead of blindly rewriting it.

Short failures need names. Input missing. Password protected. Parse rejected. Output verification failed. Naming them gives operators an error budget they can partition instead of one useless count called "PDF errors."

The initial HTTP response should be 202 Accepted, which means processing has not completed and may eventually fail. Include a monitor URL. Poll responses should carry Retry-After; clients should add jitter and a ceiling. A completed response may contain a short-lived download URL, but the audit record retains the immutable object identity and digest, not that expiring URL.

Build the evidence before assembling bytes

The submission transaction freezes an ordered manifest. Each entry needs an application-owned document identifier, immutable object version or content digest, declared media type, byte length, and ordinal. Reject duplicate ordinals, unsupported encryption, missing objects, and exceeded limits before queue admission. MIME labels are untrusted input; parse the file as PDF under resource limits.

{
  "job_id": "01JCONTRACTBUNDLE7K9M3Q2X",
  "documents": [
    {"document_id": "msa", "ordinal": 1, "sha256": "<64 lowercase hex characters>", "bytes": 428103},
    {"document_id": "dpa", "ordinal": 2, "sha256": "<64 lowercase hex characters>", "bytes": 193882},
    {"document_id": "exhibit-a", "ordinal": 3, "sha256": "<64 lowercase hex characters>", "bytes": 88214}
  ]
}
Enter fullscreen mode Exit fullscreen mode

The idempotency key should bind tenant, operation, and canonical manifest digest. Reusing a client key with a different manifest is a conflict, not permission to return an unrelated result.

Bytes decide.

ISO 32000-2 defines PDF, but syntax conformance does not promise identical rendering everywhere, nor does copying pages preserve forms, annotations, embedded files, bookmarks, or signatures as a legal workflow may expect. Define the bundle profile. If the contract depends on interactive fields, tagged structure, existing digital signatures, or archival conformance, plain page assembly is the wrong operation until fidelity tests prove otherwise.

How should a Node.js background job merge PDFs while clients poll?

The Node.js service can own Express admission and polling while an isolated worker performs memory- and CPU-sensitive document work. This Go sketch shows the commit protocol, independent of a queue or PDF library. Publish must provide create-if-absent semantics or an equivalent generation precondition.

package bundle

import (
    "bytes"
    "context"
    "crypto/sha256"
    "encoding/hex"
    "fmt"
    "io"
)

type Store interface {
    OpenVersion(context.Context, string) (io.ReadCloser, error)
    Publish(context.Context, string, io.Reader, int64, string) error
    Verify(context.Context, string, int64, string) error
}

type Jobs interface {
    MarkSucceeded(context.Context, string, string, int64, string) error
}

func PublishVerified(ctx context.Context, jobID, manifest string, src io.Reader, size int64, store Store, jobs Jobs) error {
    digest := sha256.New()
    data, err := io.ReadAll(io.TeeReader(src, digest))
    if err != nil { return fmt.Errorf("read assembly: %w", err) }
    if int64(len(data)) != size { return fmt.Errorf("assembly size changed") }

    sum := hex.EncodeToString(digest.Sum(nil))
    key := "bundles/" + jobID + "/" + manifest + ".pdf"
    if err := store.Publish(ctx, key, bytes.NewReader(data), size, sum); err != nil {
        return fmt.Errorf("publish output: %w", err)
    }
    if err := store.Verify(ctx, key, size, sum); err != nil {
        return fmt.Errorf("verify output: %w", err)
    }
    return jobs.MarkSucceeded(ctx, jobID, key, size, sum)
}
Enter fullscreen mode Exit fullscreen mode

Production should spool large outputs to bounded temporary storage rather than use the sketch's io.ReadAll. It must also recompute every input digest while reading, validate the completed PDF with an independent parser, count pages, cap disk use, and record a structured audit event. Cancellation leaves the job retryable and temporary data disposable. Never sign a temporary path.

This advice does not apply unchanged when inputs contain digital signatures that must remain independently verifiable, when a regulator requires an archival profile, or when fidelity includes dynamic forms and scripts. Preservation or a container approach may fit, subject to legal and interoperability review. Page assembly is not neutral to document semantics.

That limitation matters.

Capacity is a concurrency decision

I would reject a capacity proposal expressed only as jobs per second. The useful unit is peak bytes and pages in flight, split across download, parse, assembly, validation, and upload. Buffering sources plus output makes memory grow with bundle size; disk-backed streaming moves the constraint to local storage and I/O. Hard admission limits protect both paths.

Little's Law provides a planning check: average concurrency is arrival rate multiplied by average processing time. Then size for a declared percentile and overload policy. As an illustrative input, not a benchmark, 2 jobs per second with 8 seconds of mean service time implies 16 jobs in service on average. A platform safe at only 12 will accumulate queue depth at that load.

Set separate SLOs for valid-job admission and completion latency from durable acceptance to verified publication. Track queue age apart from worker duration. Rising oldest-job age is a clearer saturation signal than CPU alone. Dashboards should separate retries, permanent validation failures, output verification failures, bytes, pages, and temporary-disk high-water marks.

Backpressure is correctness. When queue age or storage headroom crosses a defined threshold, stop admitting work with a retryable response instead of accepting an unbounded promise. Per-tenant concurrency prevents one oversized batch from consuming the completion SLO.

Buy, build, or separate the concerns?

The choice turns on fidelity evidence, render cost, on-call ownership, and exit cost.

Every option carries a trade-off: local control creates local pager duty, while outsourcing execution reduces direct maintenance but expands the external data and contract boundary. Neither removes the need to qualify output against the same corpus.

Approach Fidelity control Operational load Lock-in surface
In-process library Direct fixtures and version pinning Parser incidents and upgrades stay with the team Library API and output behavior
Isolated self-hosted worker Same test control with resource isolation Sandboxing, patching, scaling, and storage Internal job contract and engine
Managed document service Requires retained corpus evidence Less worker maintenance; integration incidents remain Request semantics, limits, and data handling
Hybrid validation pipeline Independent checks catch engine-specific defects Two components and more failure states Multiple replaceable interfaces

Do not select from a synthetic ten-page benchmark. Build a sanitized corpus covering rotated pages, mixed page boxes, large images, fonts, forms, annotations, bookmarks, encrypted inputs, malformed files, and the largest allowed bundle. Compare rendered pages and structural expectations, and run the fixtures on every assembler or parser upgrade. Fidelity is an acceptance criterion; render cost is its budget.

Isolation, least-privilege object access, encrypted transport and storage, malware policy, and short retention are baseline controls. Audit events need an append-oriented destination, controlled access, clock discipline, and retention aligned to the legal workflow. A digest demonstrates byte identity; it does not prove who approved the contract or that its content was legally valid.

Release checklist for a signable bundle

  • Freeze ordered, versioned inputs under one canonical manifest digest.
  • Validate parser acceptance, encryption policy, count, pages, and bytes before admission.
  • Test worker death after publication but before the database commit.
  • Verify output length, digest, parseability, and expected page count.
  • Return durable status with stable errors, Retry-After, poll authorization, and no stack traces.
  • Bind the signature request to the recorded output digest.
  • Exercise duplicate delivery, stale polling, storage throttling, cancellation, and full temporary disks.
  • Define admission and completion SLOs; alert on oldest queue age and capacity headroom.
  • Re-run the fidelity corpus after every assembler or parser upgrade.

The release criterion is simple: the same accepted manifest must resolve to one verified byte sequence, and durable records must explain every transition from acceptance to signing. Background execution absorbs expensive work. The integrity protocol makes the contract bundle fit to sign.

Sources

Top comments (0)