DEV Community

sawyerflynn1578
sawyerflynn1578

Posted on

Multipart Beats Streaming for Large Private Document Storage and Logistics ZIP Uploads

Short answer: use a single streamed request for a short-lived export that is cheap to regenerate, but use multipart upload for a 100 MB PDF or a 1 GB ZIP when retrying from byte zero would violate the export window or blur the audit trail. Keep either result private, bind every object to a tenant and a retention deadline, and make deletion a recorded state transition rather than an occasional cleanup job.

For a logistics system that stores product images and builds tenant-scoped exports, the largest storage bill is not necessarily the newly uploaded document. It is often the accumulated byte-days of old images, completed exports, abandoned parts, and replacement generations. Before choosing an upload mechanism, calculate retained bytes as object size x retained generations x retention time; a 1 GB export kept for one 30-day billing month is 1 GB-month, while seven retained generations consume seven times that storage. Multipart transfer changes the cost of failure. Retention policy changes the steady-state term.

That distinction matters more than an attractive per-request number.

The bill starts with retained generations, not upload requests

Suppose an export contains private product images, PDF shipping documents, and a ZIP index for one tenant. The useful artifact may be 1 GB, yet a loose lifecycle can leave the previous artifact, the replacement artifact, temporary assembly data, and unfinished multipart state alive at once. I model those categories separately because they have different deletion triggers and different evidence: completed exports expire from a declared business policy, source images may follow a longer product-record policy, and unfinished parts should disappear after a bounded assembly window. I'm not sure which category dominates a particular system until its inventory reports bytes by tenant, object state, and expiration date; a global bucket-size graph cannot answer that question.

The smallest change with the largest predictable effect is to stop retaining superseded exports by accident. Store an explicit retain_until value beside the export record, keep the object key opaque, and let one idempotent deletion worker advance active -> deletion_due -> deleted. The worker should record the policy version, tenant, object identifier, expected version, attempt identifier, and provider acknowledgement. If legal hold or another compliance control applies, it must be a separate state that blocks deletion visibly; silently extending every object's lifetime is easier to implement, but it makes the cost model and the deletion promise false.

This is an exactly-once outcome built on at-least-once work. The deletion command may run twice. The audit transition may not.

Stored state Retention decision Evidence worth keeping
Product image Product-record policy Tenant, content digest, policy version
Completed tenant export Short delivery window Generation ID, expiry, download authorization
Replaced export Delete after replacement is committed Old and new generation IDs
Unfinished parts Abort after assembly window Upload ID, initiated time, abort result
Audit record Compliance schedule Immutable transition and actor identity

The deliberate loss is old export generations. If a customer asks for an expired ZIP after deletion, the system regenerates it from retained source records; if those records are also past their lawful retention period, the correct answer is that recovery is unavailable. Longer retention reduces regeneration risk, but increases both exposure and byte-days. There is no free setting here.

Deletion is final.

How should Node.js handle multipart upload for large private PDF and ZIP objects?

Keep the Node.js request handler out of the data path. It should authenticate the tenant, validate the intended media type and declared size, create an upload record with an idempotency key, and return narrowly scoped transfer instructions. The browser or trusted export worker then moves bytes directly to private object storage. A completion request supplies the ordered part results; the control plane verifies that the upload record still belongs to the same tenant, has not expired, and has not already committed another generation.

The same state machine works across Amazon S3, Cloudflare R2, Google Cloud Storage, and Azure Blob Storage, although their multipart or resumable primitives and lifecycle controls are not interchangeable. Treat those products as conformance targets, not as drop-in synonyms: verify minimum and maximum part rules, checksum behavior, abort semantics, conditional writes, private-access defaults, lifecycle timing, and evidence available after deletion against the current documentation for the service and region under consideration. A provider name in a configuration file is not a portability test.

Consider a deterministic recovery test for a 1 GB tenant export, divided by the test harness into ten 100 MB payloads. After six payloads have received verified part results, terminate the transfer process, restart it with the same tenant and idempotency key, and ask the control plane for the ledger state. A correct implementation identifies the same upload, retains the six verified results, transfers only the remaining four payloads, and commits one current generation. Now repeat completion twice, once from each of two workers. Both callers must observe the same committed generation even though they raced. Finally, expire the export, run deletion twice, and check that the tenant can no longer obtain transfer authorization while the audit ledger shows one policy transition and the repeated command's outcome. This single scenario exposes four costs that a happy-path benchmark hides: resent bytes, abandoned-part byte-days, duplicate generations, and manual reconciliation. The numbers are a test fixture rather than a recommended provider part size; each adapter must enforce its provider's documented constraints.

Retries happen.

For the transfer itself, single-request streaming remains the least complex option. It has one object operation, one digest, and no orphan-part state. Choose it when the client has a stable connection, the object is modest, and restarting the full transfer fits the service objective. Multipart earns its machinery when failures are common enough or objects are large enough that resending the entire PDF or ZIP is materially worse than retrying one part. The threshold is operational, not ceremonial — 100 MB and 1 GB are useful test points, not universal laws.

Don't let a multipart library decide tenancy. Every initiate, sign, complete, abort, inspect, and delete action must load the upload record through a tenant-scoped key. The storage key should be derived on the server from that record rather than accepted from a client. Completion also needs compare-and-set behavior so two retries cannot publish two current exports. If the first request committed generation 42, the second request must return generation 42's result rather than create generation 43.

A small upload ledger makes retries boring

The interface below separates a provider adapter from the domain ledger. It intentionally contains no vendor route, SDK type, or public bucket name. A Node.js control plane can implement the same contract; Go makes the transaction boundaries unusually visible here, which is why the example uses it.

package export

import (
    "context"
    "errors"
    "time"
)

type Upload struct {
    TenantID      string
    IdempotencyKey string
    ObjectKey     string
    UploadID      string
    State         string
    RetainUntil   time.Time
    Generation    int64
}

type CompletedPart struct {
    Number int
    ETag   string
}

type ObjectStore interface {
    Begin(ctx context.Context, objectKey string) (uploadID string, err error)
    Complete(ctx context.Context, objectKey, uploadID string, parts []CompletedPart) error
    Abort(ctx context.Context, objectKey, uploadID string) error
}

type Ledger interface {
    FindByIdempotencyKey(ctx context.Context, tenantID, key string) (Upload, bool, error)
    InsertPending(ctx context.Context, upload Upload) error
    CommitOnce(ctx context.Context, tenantID, key, uploadID string) (Upload, error)
}

var ErrUploadConflict = errors.New("upload state conflict")
Enter fullscreen mode Exit fullscreen mode

Initiation first checks the ledger. A repeated idempotency key returns the existing upload; it does not allocate another provider upload ID. Completion asks the provider to assemble the declared parts and then commits the domain generation exactly once. In a production design, the boundary between those two systems cannot be one database transaction, so reconciliation is mandatory: scan provider-completed but ledger-pending records, confirm their tenant-bound identity and digest, and replay the idempotent commit. The inverse case, ledger-pending uploads that never completed, becomes an abort candidate after the assembly deadline.

func Start(
    ctx context.Context,
    store ObjectStore,
    ledger Ledger,
    tenantID string,
    idempotencyKey string,
    objectKey string,
    retainUntil time.Time,
) (Upload, error) {
    if prior, ok, err := ledger.FindByIdempotencyKey(ctx, tenantID, idempotencyKey); err != nil {
        return Upload{}, err
    } else if ok {
        return prior, nil
    }

    uploadID, err := store.Begin(ctx, objectKey)
    if err != nil {
        return Upload{}, err
    }

    upload := Upload{
        TenantID: tenantID, IdempotencyKey: idempotencyKey,
        ObjectKey: objectKey, UploadID: uploadID,
        State: "pending", RetainUntil: retainUntil,
    }
    if err := ledger.InsertPending(ctx, upload); err != nil {
        _ = store.Abort(ctx, objectKey, uploadID)
        return Upload{}, err
    }
    return upload, nil
}
Enter fullscreen mode Exit fullscreen mode

There is a narrow failure interval after Begin and before InsertPending. The adapter should attach a non-secret correlation value to provider metadata so an inventory job can identify initiated uploads that have no ledger row and abort them after the same bounded window. This isn't a promise of distributed exactly-once execution. It is a design in which duplicates converge, missing transitions are discoverable, and every repair has an audit identity.

Retention changes the safer upload choice

Multipart is not suitable when the export can be rebuilt quickly, the client connection is controlled, and the team cannot operate an upload ledger plus orphan reconciliation. Stick with a streamed single request in that case; fewer states mean fewer ambiguous cleanup decisions. Conversely, a single request is a poor fit when a 1 GB tenant ZIP crosses unreliable links or a missed delivery window has business impact, because retrying from zero couples network failure directly to completion time.

The catch is that resumability creates data with a lifecycle before a final object exists. An unfinished part can contain private document bytes, so its expiration, access boundary, inventory, and abort evidence belong in the privacy model. Completed objects need an authorization check at download time rather than a guess based on an unforgeable-looking URL. Encryption and private access reduce disclosure risk, but neither answers who may delete, how a hold is represented, or which tenant owned a part during assembly.

Compliance labels also do not transfer automatically from a cloud service to an application architecture. FedRAMP is a United States government risk and authorization program; a relevant authorization can be one input to system selection, but the deployment boundary, service offering, region, controls, and agency requirements still need review. For commercial logistics data, contractual deletion terms and jurisdiction may be more relevant. Have the accountable security and legal teams define the evidence and retention schedule. A blog post cannot do that.

Test recovery, deletion, and tenant isolation together

The useful test matrix crosses size, failure point, and lifecycle state. Exercise at least a 100 MB PDF and a 1 GB ZIP; interrupt transfers before any part, between parts, during completion, after provider completion but before ledger commit, and during deletion. Then retry every command with the same idempotency key. The assertions are domain assertions: exactly one current generation, no cross-tenant lookup, stable completion output, bounded unfinished data, and one auditable deletion outcome.

Ship metrics that reconcile rather than merely count traffic. Pending uploads should be grouped by age and tenant; completed objects should be grouped by retention state; deletion_due records should have a bounded lag; and storage inventory should reconcile with ledger generations. Alert on divergence, not on an arbitrary number of uploads. Deployment needs the same discipline: add new ledger states with backward-compatible readers, deploy reconciliation before writers can create those states, and rehearse rollback while both versions exist.

Cost testing follows from the model. Measure bytes resent during injected interruption, byte-days by state, regeneration work after expiry, and operations per successful export. Provider request and egress pricing can influence the final selection, but it should be applied to observed workload categories rather than used as the opening argument. Your mileage may vary because connection quality, export frequency, retention policy, and regeneration cost move different terms.

The decision rule is compact: stream when restart cost is bounded and regeneration is ordinary; use multipart when preserving verified progress materially protects the delivery objective. In both cases, choose the storage implementation only after it passes tenant-isolation, lifecycle, conditional-commit, reconciliation, and deletion-evidence tests. The upload method handles transport failure. The ledger makes its consequences accountable.

References

Further reading

Top comments (0)