A page saying "archive growth rate exceeded" is already late. The least complex defensible design is to compact only unsigned logistics bundles, retain signed originals byte-for-byte, and report savings as measured input and output bytes at the ingest boundary. Do not rewrite a signed PDF merely to reclaim storage. Its bytes are part of the evidence you are preserving, so route it to immutable storage and record why compression was skipped.
TL;DR: separate eligibility from compression, calculate input_bytes - output_bytes rather than trusting a processor's claim, and publish both byte counts plus a bounded ratio. Keep the original until the compacted object has passed structural validation and an atomic promotion step. This answers the practical ingest question without making the archive depend on a particular JavaScript package, PDF engine, or storage provider; a Node.js worker can use the same process boundary and metric contract as the Go example below.
The alert the on-call sees should name the affected archive class, observed byte-ingest rate, forecast window, and trace or job identifier. A percentage alone is weak evidence. A 60% saving on a tiny packing slip matters less to capacity than a 3% change across a sustained stream of image-heavy bills of lading, while a negative saving is an actionable outcome rather than a math error.
Count bytes.
Why did the capacity alert fire before the compression alarm?
Usually, the storage forecast and document pipeline are measuring different things. The forecast sees committed object bytes. The worker may count logical payload bytes before retries, may omit skipped signed bundles, or may report the processor's temporary output before validation. Those definitions drift quietly until the archive page fires.
Work backward from that page. For every terminal ingest outcome, the audit event needs a stable document identifier, input bytes, committed bytes, disposition (compressed, retained_original, or rejected), a reason code, and the processor policy version. Keep the content hash in the evidence record, but do not put document identifiers or hashes into metric labels; that creates unbounded cardinality and turns an operational signal into an expensive index.
The earlier signal is not "compression failed once." It is the byte-weighted effectiveness of eligible traffic over a capacity-planning window, accompanied by the eligible and skipped byte rates. Alert when the forecast threatens the archive's capacity objective, then use those pipeline signals to explain the burn. This ordering respects the SLO: the user-visible promise concerns durable, retrievable evidence, not an attractive compression ratio.
One subtle trap deserves a short paragraph. A merged freight bundle may contain a signed delivery record beside unsigned scans. Treating the outer bundle as uniformly rewriteable erases the distinction. Split only when the governing workflow permits it and the audit trail records the parent-child relationship; otherwise retain the entire original.
Signature boundaries define the data path
PDF is standardized by ISO 32000-2, and digital signatures cover specified byte ranges in the file. Rewriting objects, cross-reference data, metadata, or images can therefore invalidate a signature even when every rendered page looks identical. Visual comparison is not signature validation.
Run a standards-aware preflight before any transformation. If a signature is present, preserve the received bytes and validate the signature under the organization's trust policy. If the document is unsigned, apply a pinned policy, write to a temporary object, parse the result, enforce page-count and required-metadata invariants, and only then promote it. Encryption, malformed structure, unsupported filters, or a processor timeout should have explicit dispositions; none should silently produce a smaller but unusable archive object.
For merge and split jobs, the audit record should connect each output to every input using stable identifiers and hashes. A newly created merged PDF is a new artifact, not the same signed artifact in a more convenient envelope. If the business process requires a signature over the merged result, signing belongs after the merge and validation stages.
The size report is deliberately plain:
| Field | Meaning | Operational use |
|---|---|---|
input_bytes | Bytes accepted at the boundary | Ingest demand and audit reconciliation |
committed_bytes | Bytes in the promoted archive object | Capacity forecast |
saved_bytes | input_bytes - committed_bytes | Absolute storage effect |
saving_ratio | saved_bytes / input_bytes, when input is nonzero | Cohort comparison, not billing |
disposition | Compressed, retained, or rejected | Explains denominator changes |
Never clamp a negative saved_bytes value to zero. It tells you the selected policy expanded the file, which should normally cause the original to be retained and the candidate discarded. Keep the observation so policy regressions remain visible.
How should Node.js compress a PDF on ingest and report its size?
The following Go function is intentionally smaller than a PDF engine. It measures files around a processor supplied by the deployment, rejects zero-byte output, keeps the original when compaction does not help, and promotes with a rename on the same filesystem. The caller must perform signature preflight before invoking it and must supply a processor that validates its output before returning. Those two contracts are where a production Node.js worker should draw the same boundary.
package ingest import ( "context" "errors" "os" ) type Processor interface { Compact(ctx context.Context, inputPath, outputPath string) error } type SizeReport struct { InputBytes int64 `json:"input_bytes"` CommittedBytes int64 `json:"committed_bytes"` SavedBytes int64 `json:"saved_bytes"` SavingRatio float64 `json:"saving_ratio"` Disposition string `json:"disposition"` } func CompactUnsigned(ctx context.Context, p Processor, inputPath, finalPath string) (SizeReport, error) { in, err := os.Stat(inputPath) if err != nil { return SizeReport{}, err } if in.Size() == 0 { return SizeReport{}, errors.New("empty input") } tmp, err := os.CreateTemp("", "pdf-candidate-*.pdf") if err != nil { return SizeReport{}, err } tmpPath := tmp.Name() if err := tmp.Close(); err != nil { return SizeReport{}, err } defer os.Remove(tmpPath) if err := p.Compact(ctx, inputPath, tmpPath); err != nil { return SizeReport{}, err } out, err := os.Stat(tmpPath) if err != nil { return SizeReport{}, err } if out.Size() == 0 { return SizeReport{}, errors.New("processor produced empty output") } committed := in.Size() disposition := "retained_original" if out.Size() < in.Size() { if err := os.Rename(tmpPath, finalPath); err != nil { return SizeReport{}, err } committed = out.Size() disposition = "compressed" } saved := in.Size() - committed return SizeReport{ InputBytes: in.Size(), CommittedBytes: committed, SavedBytes: saved, SavingRatio: float64(saved) / float64(in.Size()), Disposition: disposition, }, nil } This is a measurement example, not a complete archive transaction. Its first limitation is deliberate: it does not parse PDF signatures, merge documents, validate page rendering, or implement an object-store transaction. os.Rename is atomic only when source and destination are on the same filesystem, and object stores need their own conditional-promotion sequence. The code also leaves original retention to the caller because deletion policy must follow the audit and recovery requirements, not a helper function's convenience. A deployment that cannot guarantee same-filesystem staging should choose a storage-native conditional write instead; a workflow that cannot reliably classify signatures should retain the original rather than run this transformation. Those are hard boundaries, not missing polish.
Emit the report only after promotion succeeds. Record the same values in a durable job event for reconciliation, then aggregate metrics by bounded dimensions such as document class, disposition, and policy version. Histograms can show input and output size distributions; counters can accumulate bytes and outcomes. A trace links preflight, processing, validation, and commit, but the durable audit event remains the source for answering what happened to a particular bundle. This creates some duplication between telemetry and the audit store, yet collapsing them into one system is the worse trade-off: metrics are optimized for aggregation and bounded labels, while an evidence record must retain per-document lineage and survive changes to dashboards.
Measure after commit.
Buy or build around the risky boundary
The decision is less about which engine can make a sample file smallest and more about who owns signature detection, validation, upgrades, and incident response.
| Approach | Signature and audit control | On-call load | Lock-in | Sensible boundary |
|---|---|---|---|---|
| Managed document service | Contract and evidence depend on exposed controls | Lower processor maintenance; integration failures remain yours | API and policy semantics can bind the archive | Keep eligibility, hashes, and commit audit in your system |
| Self-hosted PDF engine | Full policy and version control | You own security updates, capacity, and malformed-file behavior | File and process boundary is portable | Wrap the engine behind a narrow processor interface |
| Custom PDF rewriting | Maximum theoretical control | Highest testing and specification burden | Low vendor lock-in, high code ownership | Reserve for requirements existing engines cannot satisfy |
Build the evidence path; buy or adopt the transformation engine only after testing its boundary. The evaluation corpus should represent the actual logistics mix: born-digital invoices, scanned delivery documents, mixed page sizes, rotated images, encrypted files, malformed inputs, signed artifacts, and bundles produced by merge and split operations. Do not invent a universal saving target. Establish distributions from that corpus, because image-heavy and already-optimized PDFs have fundamentally different headroom.
Roll out a new policy version in shadow mode first: generate and validate a candidate, report the hypothetical byte result, then discard it. A small canary follows. Capacity planning needs arrival bytes per interval, eligibility rate, observed committed-to-input ratio, retention duration, replication factor, and expected peak multiplier; compression ratio alone cannot forecast the archive.
The threshold can create more incidents than it prevents
A threshold that pages on every low-saving interval will punish the on-call for shifts in document mix. A run of already-optimized carrier invoices can be healthy while producing almost no reduction. Conversely, a good average ratio can conceal signed-document growth that bypasses transformation and still consumes capacity.
Tie the page to forecasted exhaustion or an error-budget policy, and make compression effectiveness a diagnostic alert only when volume is large enough and the change persists across an operationally meaningful window. Use separate views for eligible bytes, skipped signed bytes, candidate expansion, validation failures, and committed bytes. This makes the first page actionable: the responder can distinguish demand growth from policy drift without opening customer documents.
False positives have a direct cost. They train responders to mute the one signal that should warn before the archive misses its durability or availability objective. The final rule is conservative: preserve evidence first, report bytes at commit, and optimize only inside the unsigned boundary.
Further reading
- ISO 32000-2, Portable Document Format: https://www.iso.org/standard/75839.html
- ETSI EN 319 142-1, PAdES digital signatures: https://www.etsi.org/deliver/etsi_en/319100_319199/31914201/01.01.01_60/en_31914201v010101p.pdf
- Go
os.Renamedocumentation: https://pkg.go.dev/os#Rename - Prometheus metric and label guidance: https://prometheus.io/docs/practices/naming/
- OpenTelemetry traces specification: https://opentelemetry.io/docs/specs/otel/trace/