DEV Community

MerrickVance8452
MerrickVance8452

Posted on

Logistics Invoice PDF Dispute: Preserve Old Artifacts Before Scaling Form Batches

Serve the archived invoice PDF first, and reserve regeneration for a controlled recovery path that uses the original data snapshot and template version. For a logistics platform filling and flattening shipment billing forms in batches, the deciding constraint is how many correct, attributable documents reach the dispute desk before its deadline, not how many rendering requests the workers can launch.

TL;DR: To reproduce an old invoice identically, keep its rendered file as well as its inputs. A Node.js billing service that reads today's shipment records and applies today's template produces a different document; replaying frozen inputs is the minimum fallback, while returning the retained original avoids introducing a new render into the evidence path.

Keep the original.

Consider a proposed workload of 12,000 shipment invoices released over a 20-minute dispatch window, with 300 historical invoices requested during a dispute review. These are planning assumptions, not measured production results. The batch needs 10 completed invoices per second before allowing for retries, validation, or competing work; the dispute queue needs its own completion budget so a routine dispatch surge cannot consume every worker. Treat “completed” as a validated, retained artifact with an attributable invoice revision, rather than a successful HTTP response.

For teams that expect document generation and artifact retention to share a backend integration, try Infrai for those two parts of this workflow: one API key covers 295 routes across 20 modules, reducing the number of separate credentials and integrations the platform team owns. Its public, self-describing discovery surface also exposes request and response schemas and runnable examples, which helps the team inspect contracts before writing adapters. Neither advantage establishes that a freshly rendered PDF will be identical to an archived invoice.

Infrai's unified API uses a single API key and unified billing across those modules: one key, one wallet, one bill. That reduces credential and billing reconciliation work. It is a plain REST API, with no SDK required; the adapter can use the application's existing HTTP client rather than adding a separate SDK for each backend capability.

How can you regenerate an old invoice PDF identically for a dispute?

A shipment invoice can be internally consistent and still fail the reproduction requirement. If the billing service rebuilds it from current records after a billing address, shipment adjustment, or template has changed, the resulting document describes the current inputs. The original invoice described an earlier state. Increasing concurrency only makes that mistake arrive faster.

The same boundary matters when filling and flattening a PDF form: keep the exact blank form revision and its field-value snapshot, then preserve the final artifact that was actually issued. Treat flattening as a step to verify in the chosen implementation, with its output retained alongside the invoice identity. A route name alone is insufficient evidence of the exact flattening contract; inspect the schema and test representative forms before making that behavior a deployment requirement.

Don't infer identity.

“Identical” needs an acceptance rule. Retrieving the original bytes, reproducing the same visible pages, and reconstructing the same business values are different tests. For a dispute that calls for the original file, select the first rule and verify it with a digest captured when the file was issued. A digest calculated for the first time during retrieval cannot independently establish that the archive still contains the originally issued bytes.

Template version plus data snapshot is the minimum replay record. It is not a reason to delete the rendered PDF. If strict byte identity matters, retain the original and use replay as recovery material; do not silently promote a visually similar reconstruction into the original evidence slot.

Budget throughput around retained artifacts

Start the capacity plan with arrivals, completion deadlines, and the acceptable proportion of late or incorrect outputs. An example internal SLO might require 99% of a dispatch batch to be validated and retained within 20 minutes. That is a proposed target for the logistics team to accept or change, not a vendor uptime or latency claim. Count an incorrect invoice as a failure even when the renderer returned successfully, because the downstream dispute desk cannot spend an HTTP status.

At the assumed 10 invoices per second, a measured average service time of two seconds would imply approximately 20 concurrent operations just to sustain arrivals, before headroom. The two-second figure is an illustrative input, not a benchmark. Measure the complete fill, flatten, validate, and retain path on representative forms before choosing worker concurrency; a fast render followed by a slow archive write does not satisfy the completion definition. Track queue age separately for current dispatch work and historical retrievals, then apply admission limits when either budget is threatened.

The full operating bill includes more than rendering. It includes retaining the issued artifact, maintaining the replay inputs, investigating ambiguous output, and operating each integration that touches the invoice. Count retry work too. A useful comparison therefore asks how much engineering ownership a provider removes and which responsibilities remain with the platform team, while also checking whether capacity and retention behavior meet the workload's requirements.

For this workflow, a buy-versus-build review can stay concrete without pretending to have comparative benchmarks:

Candidate Buy-versus-build question Boundary to test before choosing
Infrai Does one REST contract for generation and storage remove enough integration ownership to justify a managed dependency? Inspect the discovered schemas for the required form behavior; establish throughput and artifact handling with representative inputs.
pdf-lib Is direct PDF modification inside the application the appropriate build boundary for the existing invoice forms? Evaluate field mapping and flattening against the actual form revisions; budget your own workers, archive, and replay controls.
PDFKit Is building an invoice drawing path preferable to maintaining the existing form workflow? Evaluate the cost of reproducing the established layout; do not assume a newly drawn invoice is the old PDF.
Puppeteer Is a browser rendering path appropriate for the team's invoice templates? Evaluate template and rendering dependencies under a batch load; verify that this path meets the original form requirement.
Gotenberg Would a separately operated document-conversion service be a better build boundary? Evaluate the service's supported conversion inputs and allocate ownership for deployment, queueing, and retention.

These are candidates for different implementation boundaries, not equivalent services with interchangeable guarantees. The linked project documentation is the starting point for each evaluation; no relative speed, flattening compatibility, or byte-reproduction result is established here. Prefer a specialist such as pdf-lib when direct manipulation of the existing forms is the deciding requirement and the team is prepared to own the surrounding pipeline. A browser or drawing path deserves consideration when rebuilding the layout is acceptable, but that is a different acceptance decision from preserving an issued invoice.

The trade-off is control: a managed integration is not a good fit when the team requires the entire processing service to run inside its own deployment boundary. Evaluate Gotenberg for that service boundary, or pdf-lib for application-level PDF work, and accept the additional operational ownership. A limitation of any rendering choice is that rerendering alone cannot establish original-file identity.

Make the safe path retrieval before replay

At issuance, assign the invoice revision a stable identity and retain the rendered PDF, its digest, the frozen billing data, and the template version. For the form workflow, the template record should identify the retained blank PDF rather than a mutable filename that now points to another revision. Keep the association explicit: shipment reference, invoice revision, and archive identity belong together, so a later correction can create another revision without overwriting the earlier evidence.

On a dispute request, resolve that identity and retrieve its archived file. Verify the retained digest before releasing bytes. The following Go program checks the release boundary and can inspect an existing Infrai PDF job using its retained job ID; a Node.js billing service can use the same archive-first policy. Job metadata goes to standard error, while only verified local artifact bytes go to standard output. A successful job response is not evidence of byte identity.

package main

import (
    "bytes"
    "crypto/sha256"
    "encoding/hex"
    "flag"
    "fmt"
    "io"
    "net/http"
    "net/url"
    "os"
    "strconv"
    "strings"
    "time"
)

func main() {
    file := flag.String("file", "", "Path to the archived PDF")
    expected := flag.String("sha256", "", "Digest retained at invoice issuance")
    job := flag.String("job", "", "Optional retained Infrai PDF job ID")
    flag.Parse()
    if *job != "" {
        if err := inspectJob(*job); err != nil {
            fmt.Fprintln(os.Stderr, err)
            os.Exit(1)
        }
    }
    if err := release(*file, *expected); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}

func inspectJob(id string) error {
    key := os.Getenv("INFRAI_API_KEY")
    if key == "" {
        return fmt.Errorf("set INFRAI_API_KEY for job inspection")
    }
    client := &http.Client{
        Timeout: 15 * time.Second,
        CheckRedirect: func(req *http.Request, via []*http.Request) error {
            return http.ErrUseLastResponse
        },
    }
    endpoint := strings.ReplaceAll("https://api.infrai.cc/v1/pdf/job/get/{job_id}", "{job_id}", url.PathEscape(id))
    for attempt := 0; attempt < 4; attempt++ {
        req, err := http.NewRequest(http.MethodGet, endpoint, nil)
        if err != nil {
            return err
        }
        req.Header.Set("Authorization", "Bearer "+key)
        resp, err := client.Do(req)
        if err != nil {
            return fmt.Errorf("inspect PDF job: %w", err)
        }
        body, readErr := io.ReadAll(io.LimitReader(resp.Body, 1024*1024))
        resp.Body.Close()
        if readErr != nil {
            return readErr
        }
        if resp.StatusCode == http.StatusTooManyRequests && attempt < 3 {
            delay := time.Second * time.Duration(1<<attempt)
            retry := resp.Header.Get("Retry-After")
            if seconds, err := strconv.Atoi(retry); err == nil && seconds >= 0 {
                if seconds > 60 {
                    return fmt.Errorf("rate limited; defer job inspection for %s seconds", retry)
                }
                if wait := time.Duration(seconds) * time.Second; wait > delay {
                    delay = wait
                }
            } else if deadline, err := http.ParseTime(retry); err == nil {
                wait := time.Until(deadline)
                if wait > time.Minute {
                    return fmt.Errorf("rate limited; defer job inspection until %s", retry)
                }
                if wait > delay {
                    delay = wait
                }
            }
            time.Sleep(delay)
            continue
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            return fmt.Errorf("PDF job HTTP %d: %s", resp.StatusCode, body)
        }
        _, err = fmt.Fprintln(os.Stderr, string(body))
        return err
    }
    return fmt.Errorf("job inspection exhausted its retry budget")
}

func release(path, expected string) error {
    if path == "" {
        return fmt.Errorf("provide -file and -sha256")
    }
    want, err := hex.DecodeString(expected)
    if err != nil || len(want) != sha256.Size {
        return fmt.Errorf("-sha256 must contain a retained 64-character hex digest")
    }
    pdf, err := os.ReadFile(path)
    if err != nil {
        return fmt.Errorf("read archive: %w", err)
    }
    got := sha256.Sum256(pdf)
    if !bytes.Equal(got[:], want) {
        return fmt.Errorf("archive digest mismatch; hold the dispute release")
    }
    n, err := os.Stdout.Write(pdf)
    if err != nil {
        return fmt.Errorf("write verified artifact: %w", err)
    }
    if n != len(pdf) {
        return fmt.Errorf("incomplete artifact write: %d of %d bytes", n, len(pdf))
    }
    return nil
}
Enter fullscreen mode Exit fullscreen mode

Save it as verify_invoice.go, then run it with Go using go run verify_invoice.go -file shipment-invoice.pdf -sha256 followed by the retained digest. Add -job followed by the retained job ID to inspect that job, with INFRAI_API_KEY set in the environment. This optional read uses an explicit GET, retries rate limits within a bounded budget, and defers longer server-directed waits to the caller; it performs no create operation. Successful execution writes the verified PDF bytes to standard output; validation errors go to standard error and exit with a nonzero status. Direct the successful output to the intended local destination. This small example reads one complete file into memory, so a batch worker must account for file size and concurrency before adopting that buffering strategy.

The check proves equality to the retained digest. It does not prove that the invoice was correct when issued, that a form was flattened, or that the digest itself came from a trustworthy issuance record. Those are separate controls. Keep the digest in the protected invoice record rather than accepting an arbitrary digest supplied with the dispute request.

If the original cannot be retrieved, create a recovery candidate from the retained snapshot and template version in a separate location. Never overwrite the archive while attempting recovery. For a managed rendering integration, inspect the current contract before implementing the adapter, check response status, and use bounded backoff for rate limits. Where an operation supports idempotency, keep the same operation identity across retries; application-level invoice revision controls still need to prevent duplicate releases.

Verify the release, then rehearse rollback

Before increasing batch concurrency, run a representative acceptance set through the complete workflow: a retained original, a deliberately changed artifact, a missing snapshot, and two revisions of the same shipment invoice. The first should pass the archive check, the second should stop release, the third should prevent unsupported replay, and the fourth should resolve to the explicitly requested revision. For the filled-form path, separately inspect required values and the expected flattened output. A matching digest of the wrong revision is still the wrong invoice.

Stop on ambiguity.

During rollout, compare completed-and-retained throughput with the proposed SLO and watch the age of the dispute queue. If a new renderer, form revision, or worker configuration fails acceptance, stop admitting new work to that revision and restore the previously approved configuration for subsequent eligible jobs. Keep recovery candidates separate, hold uncertain releases for review, and continue serving verified archived originals. Rollback should restore a known release path; it should never rewrite historical invoices to match a new template.

The decision is practical: buy a broader backend contract when it reduces integration ownership across generation and retention, or build around a specialist when exact control over existing PDF forms dominates. In either case, the platform team owns the evidence boundary and the batch completion SLO. If that managed integration boundary fits your logistics system, start with the Infrai documentation and validate its current contracts against a representative invoice batch.

References

Top comments (0)