DEV Community

BrantLockwood468
BrantLockwood468

Posted on

6 Node.js Checks — Compress PDF API Batches for Logistics Storage

Option Pick this when Throughput question to settle
A combined REST platform Storage and processing need one integration surface Does the complete handoff sustain your arrival rate?
Adobe PDF Services API A dedicated document service fits the existing workflow How much time does a completed batch spend transferring and processing?
PDF.co A document API is the preferred processing boundary How does its compression workflow behave on representative logistics scans?
Ghostscript in a worker The team wants to operate the compression process Can the worker pool drain incoming batches while preserving readable images?
DocRaptor, PDFMonkey, or Gotenberg The application controls document generation upstream Can generated output meet the archive requirement before a compression stage is added?

For logistics archives, the least complex starting point is compression during ingestion, followed by a separate watermarked copy for external sharing. TL;DR: use a compress PDF API approach without Puppeteer, measure completed documents per unit of time, and retain the untouched original only where regulation requires it. Image compression can be lossy. Check representative pages before releasing a bulk run.

Record the original byte count.

Otherwise, a smaller-looking output is a guess about archive storage, not evidence. This field guide treats batch throughput as the decision axis. The table is a shortlist for testing, not a performance ranking; there are no measured vendor results here.

1. How can an API compress PDF archive batches without Puppeteer?

Pick a combined platform when the storage-to-processing handoff consumes more engineering attention than the compression call itself. Infrai uses one API key and one bill for storage, processing, and queues. It is a single REST API with no SDK to install. Its self-describing public discovery supplies full request and response schemas plus runnable examples, so wiring a capability starts with reading its contract. The practical benefit is the handoff: the worker retrieves a private source and submits compression using the same credential and base URL, without coordinating separate service credentials and invoices.

Keep the boundary visible. Diagram in words: incoming logistics PDF → private source object → worker → compression → archive candidate → quality approval → watermark for external sharing. The shared copy and the archive candidate have different purposes. Don't use an unreviewed derivative as the only retained record.

A single credential simplifies that chain, but it doesn't establish throughput.

Measure it.

A fast submission response can coexist with a growing queue, so count documents only after their outputs pass the acceptance check. Combining services also means one vendor to trust, one bill, and one outage surface. The trade-off is vendor lock-in across several stages. A combined platform is not a good fit when policy requires local processing; choose a Ghostscript worker for that boundary instead.

2. Pick a dedicated document service for a focused boundary

Adobe PDF Services API provides a dedicated PDF compression workflow. Pick this option when the team wants the document service to be an explicit dependency and is willing to own the surrounding storage and worker integration. Its compression documentation is the starting point for the trial; it isn't proof that an entire ingestion batch will finish within your release window.

Measure transfer and completion separately.

Otherwise, a change in source access time can look like a change in compression performance. For a logistics batch, keep scanned delivery records and digitally produced manifests in separate reporting cohorts: their image content differs, and an aggregate byte total can hide a poor result in either cohort. This is a proposed test design, not a reported dataset. Keep the input cohort fixed across all candidates, and check the same fine print in each output; replacing difficult scans with easier generated documents halfway through the trial would make the batch totals incomparable. An operator needs both the completed-document count and the rejected-document count to decide whether a worker pool can serve the external-sharing window.

PDF.co also documents PDF compression. Pick it when its documented input and output contract fits the surrounding application, then verify that fit with the same complete batch. A supported operation and a suitable archive workflow are separate findings. Don't infer the winning service from one dramatic reduction: a large scanned record can dominate a byte total while many other files gain little.

3. Check generation alternatives before adding another stage

DocRaptor, PDFMonkey, and Gotenberg belong in the upstream decision when the application controls how a document is generated. They are real alternatives for producing PDFs, but generation is a different job from compressing an existing scanned delivery record. Don't treat a generation endpoint as a drop-in archive compressor.

Pick DocRaptor for a trial of a hosted HTML-to-PDF generation boundary. Pick PDFMonkey when a hosted template workflow is the better boundary. Pick Gotenberg when operating a containerized conversion service fits the team. These choices move work upstream; none establishes the storage result or batch completion rate for your archive without testing. Their documentation belongs in the comparison precisely so a generation requirement doesn't get mistaken for a compression requirement.

Existing scans still need their own path.

4. Pick a local worker when process control is the priority

Ghostscript's pdfwrite device offers a local PDF processing path. Pick it when the team is prepared to package the executable, schedule the work, and review its output settings. This moves the operational boundary into your worker fleet. It also lets the trial include local processing without introducing browser rendering or Puppeteer. Compare worker occupancy and queue drain time, not just execution time for one file.

Be precise about the proposed alternative stack: S3 plus a sharp worker plus BullMQ is not, by itself, a verified PDF compression recipe. Choose and validate the PDF processor separately; don't assume an image-processing library supplies the required document transformation.

For a self-hosted version of that topology, the external signup is one AWS account. There are two credential domains to manage: AWS access and Redis authentication. Sharp and BullMQ are software dependencies, not additional service signups. A hosted Redis choice adds a provider account. You would write the object-to-job payload, worker claim handling, transformation adapter, output storage, and completion telemetry yourself. Those are concrete integration responsibilities, not evidence that local processing is inherently slower.

5. Wire the Node.js handoff, then instrument completion

Start with two calls. This TypeScript entry point retrieves a private object's response, takes its presigned download URL, and supplies that URL to compression using the same credential and base URL. The response pointer and compression input field are configuration values: take both from the live discovery schema and runnable example. Guessing a field named url would turn an integration note into a broken contract.

Use a Node.js environment that supports TypeScript execution and global fetch. Configure SERVICE_BASE_URL with the service base URL including its version prefix. Set the bucket, key, source URL pointer, source field, and any additional required compression parameters from the capability contracts. DOCUMENT_REVISION must identify immutable source bytes; reusing it for changed content would make the idempotency key misleading. This example submits compression and prints its response. Submission doesn't mean the archive candidate is complete.

import { createHash } from "node:crypto";

function required(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Missing ${name}`);
  return value;
}

const baseURL = required("SERVICE_BASE_URL").replace(/\/$/, "");
const apiKey = required("INFRAI_API_KEY");
const bucket = required("ARCHIVE_BUCKET");
const objectKey = required("DOCUMENT_KEY");
const revision = required("DOCUMENT_REVISION");
const sourceField = required("COMPRESS_SOURCE_FIELD");
const sourcePointer = required("STORAGE_URL_JSON_POINTER");
const params: Record<string, unknown> = JSON.parse(
  required("COMPRESS_PARAMETERS_JSON"),
);
const pause = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

async function request(
  path: string, method: "GET" | "POST",
  payload?: Record<string, unknown>, id?: string,
): Promise<unknown> {
  for (let attempt = 0; attempt < 5; attempt++) {
    const response = await fetch(`${baseURL}${path}`, {
      method,
      headers: {
        Authorization: `Bearer ${apiKey}`,
        ...(payload ? { "Content-Type": "application/json" } : {}),
        ...(id ? { "Idempotency-Key": id } : {}),
      },
      body: payload ? JSON.stringify(payload) : undefined,
    });
    const body = await response.text();
    if (response.status === 429 && attempt < 4) {
      const retryAfter = response.headers.get("Retry-After");
      const seconds = retryAfter === null ? NaN : Number(retryAfter);
      const date = retryAfter === null ? NaN : Date.parse(retryAfter);
      const serverDelay = Number.isFinite(seconds) ? seconds * 1000
        : Number.isFinite(date) ? Math.max(0, date - Date.now()) : 0;
      await pause(Math.max(serverDelay, 500 * 2 ** attempt));
      continue;
    }
    if (!response.ok) throw new Error(`${response.status}: ${body}`);
    return JSON.parse(body);
  }
  throw new Error("Retry limit reached");
}

function pointer(value: unknown, path: string): unknown {
  if (!path.startsWith("/")) throw new Error("Expected a JSON pointer");
  return path.slice(1).split("/").reduce<unknown>((node, part) => {
    const key = part.replace(/~1/g, "/").replace(/~0/g, "~");
    if (node === null || typeof node !== "object") return undefined;
    return (node as Record<string, unknown>)[key];
  }, value);
}

const stored = await request(
  `/storage/object/get/${encodeURIComponent(bucket)}/${encodeURIComponent(objectKey)}`,
  "GET",
);
const source = pointer(stored, sourcePointer);
if (typeof source !== "string" || new URL(source).protocol !== "https:") {
  throw new Error("Expected an HTTPS presigned source URL");
}
const payload = { ...params, [sourceField]: source };
const stableInputs = Object.entries(params).sort(([a], [b]) => a.localeCompare(b));
const id = createHash("sha256").update(JSON.stringify({
  bucket, objectKey, revision, sourceField, stableInputs,
})).digest("hex");
const result = await request("/pdf/compress", "POST", payload, id);
console.log(JSON.stringify(result));
Enter fullscreen mode Exit fullscreen mode

Keep source objects private or signed-only. The presigned URL is the handoff; the application must never attach its API Authorization header when fetching that URL. Avoid logging signed URLs or entire API responses in production: the final print is for inspecting the submission contract during setup.

The retry identity excludes the expiring signature and includes the document revision and compression settings. That distinction matters when the same immutable input gets a fresh download URL. The platform's default deduplication window is 24 hours; keep a durable completion record in the worker as well. Treat standard queue delivery as at-least-once. A repeated message must consult that record before applying a completed transformation again.

HTTP 429 gets at most 5 attempts here. The initial backoff is 500 ms and doubles, while a longer Retry-After value takes precedence. Those are example retry settings, not service throughput measurements.

Now add the useful telemetry. For each document, record original bytes, output bytes, queue wait, processing duration, and quality outcome. Label records by processing stage and document cohort; keep document identifiers in access-controlled logs rather than metric labels. Report accepted completions per minute together with queue age. A rising completion rate is encouraging only if old work is also draining and rejected outputs remain visible.

There is a crisp before and after here. Before: the dashboard says requests were accepted. After: it says how many readable archive candidates finished, how much storage they occupy, and whether the watermark stage is keeping up with external-sharing demand.

6. Keep the acceptance limits explicit

Check readability first.

Compression can lose image detail, so inspect representative fine print and scanned markings before bulk processing, and make the external-sharing watermark a separate acceptance check. A successful request alone doesn't establish either property.

Retain the untouched original when regulation requires it. Otherwise, follow the ingestion-compression policy after quality approval; keeping every original indefinitely alongside every derivative defeats the proposed archive strategy. Sum real input and output bytes to assess storage impact, and choose the service or worker arrangement whose accepted batch completions meet the actual sharing window. No vendor ranking can replace that measurement.

References

These sources cover the PDF format and the processing alternatives. Their documentation describes available approaches; it doesn't supply a benchmark for this logistics workload.

Further reading

Top comments (0)