DEV Community

UlricDonovan1564
UlricDonovan1564

Posted on

Large App Backup Files: How to Resume Multipart Uploads in Object Storage

Short answer: split each backup into fixed parts, persist the upload ID and confirmed part ETags in a tenant-scoped checkpoint, reconcile that checkpoint with the object store after every restart, and complete only from the reconciled ordered list. Abort on explicit cancellation or failed validation, not on a routine timeout.

That rule matters more than the client library. A large app backup can outlive a process, a deployment, or a queue lease. If progress exists only in memory, a retry becomes a second upload instead of a continuation. In a property-management system, a second mistake is worse: a valid upload written under the wrong tenant prefix can turn an availability problem into an isolation incident.

I've been paged by missed jobs and duplicate deliveries. The useful reflex is the same here — make ownership, identity, and the recovery transition durable before moving bytes.

What state makes a multipart backup resumable?

Treat a multipart upload as a small state machine, not as one oversized request. The durable record needs a tenant ID, backup ID, destination key, source fingerprint, upload ID, chosen part size, status, and the part number-to-ETag mapping returned by storage. Keep the ordered completion input as derived state. The database row is your control plane; object storage holds the data plane.

The destination key must come from trusted tenant context rather than a tenant value supplied in the job payload. For example, resolve tenantID from the authenticated scheduler identity, then construct tenants/<tenantID>/backups/<backupID>.tar. Use a separate bucket or account where regulation or blast-radius requirements demand stronger isolation. A shared bucket with tenant prefixes can be suitable only when authorization is enforced at the storage credential boundary and tested for cross-prefix denial; a prefix by itself isn't an access-control mechanism.

Here is the deliberately small contract used by the worker. It mirrors the multipart operations without binding the application to a commercial SDK.

package backup

import (
    "context"
    "io"
)

type CompletedPart struct {
    Number int
    ETag   string
}

type MultipartStore interface {
    Create(ctx context.Context, bucket, key string, metadata map[string]string) (uploadID string, err error)
    UploadPart(ctx context.Context, bucket, key, uploadID string, number int, body io.Reader, size int64) (etag string, err error)
    ListParts(ctx context.Context, bucket, key, uploadID string) ([]CompletedPart, error)
    Complete(ctx context.Context, bucket, key, uploadID string, parts []CompletedPart) error
    Abort(ctx context.Context, bucket, key, uploadID string) error
}

type Checkpoint struct {
    TenantID   string
    BackupID   string
    Bucket     string
    Key        string
    SourceHash string
    UploadID   string
    PartSize   int64
    Parts      map[int]string
    Status     string
}

type CheckpointStore interface {
    Load(ctx context.Context, tenantID, backupID string) (Checkpoint, error)
    Save(ctx context.Context, cp Checkpoint) error
}
Enter fullscreen mode Exit fullscreen mode

Make (tenant_id, backup_id) unique in the checkpoint database. Also bind the source hash, destination key, and part size when the upload is created. If any of those values changes on retry, stop and require a new backup ID. Don't splice parts from two versions of a file just because their offsets happen to line up.

How should a large app resume multipart backup file uploads?

On every attempt, load the checkpoint and ask storage which parts it has accepted. Rebuild local part state from the remote response, because the worker may have uploaded a part and died before saving its ETag. Then seek to each missing offset, upload that exact range, and save the returned ETag before proceeding. A Node.js coordinator can enqueue this work just as well as any other runtime; the recovery contract belongs in durable data, while this Go worker provides the concrete implementation.

Consider a concrete restart. A 10 GiB tenant export split into 64 MiB ranges has 160 numbered parts. The worker sends part 73, storage accepts it, and the process exits before the checkpoint transaction commits. The database still says 72 parts, while the remote upload has 73. On restart, blindly trusting the database resends part 73; blindly trusting an old in-memory queue can start a second multipart session. The recovery path instead loads the original upload ID, lists its accepted parts, replaces the local part map with that remote truth, persists the reconciled map, and begins at part 74. If the source fingerprint no longer matches, it does none of those things: it marks the attempt for controlled abort and creates a new backup identity only after policy permits it. This is also why the queue message should carry identifiers, not the multipart progress itself. Delivery can happen twice. The state transition remains singular.

package backup

import (
    "context"
    "errors"
    "fmt"
    "io"
    "sort"
)

func Resume(ctx context.Context, objects MultipartStore, states CheckpointStore, cp Checkpoint, src io.ReaderAt, fileSize int64) error {
    if cp.PartSize <= 0 || cp.UploadID == "" {
        return errors.New("checkpoint is not initialized")
    }

    remote, err := objects.ListParts(ctx, cp.Bucket, cp.Key, cp.UploadID)
    if err != nil {
        return fmt.Errorf("list accepted parts: %w", err)
    }
    cp.Parts = make(map[int]string, len(remote))
    for _, part := range remote {
        cp.Parts[part.Number] = part.ETag
    }
    if err := states.Save(ctx, cp); err != nil {
        return fmt.Errorf("save reconciled checkpoint: %w", err)
    }

    partCount := int((fileSize + cp.PartSize - 1) / cp.PartSize)
    for number := 1; number <= partCount; number++ {
        if _, ok := cp.Parts[number]; ok {
            continue
        }
        offset := int64(number-1) * cp.PartSize
        size := min64(cp.PartSize, fileSize-offset)
        body := io.NewSectionReader(src, offset, size)
        etag, err := objects.UploadPart(ctx, cp.Bucket, cp.Key, cp.UploadID, number, body, size)
        if err != nil {
            return fmt.Errorf("upload part %d: %w", number, err)
        }
        cp.Parts[number] = etag
        if err := states.Save(ctx, cp); err != nil {
            return fmt.Errorf("save part %d: %w", number, err)
        }
    }

    parts := orderedParts(cp.Parts)
    cp.Status = "completing"
    if err := states.Save(ctx, cp); err != nil {
        return fmt.Errorf("save completing state: %w", err)
    }
    if err := objects.Complete(ctx, cp.Bucket, cp.Key, cp.UploadID, parts); err != nil {
        return fmt.Errorf("complete upload: %w", err)
    }
    cp.Status = "complete"
    return states.Save(ctx, cp)
}

func orderedParts(parts map[int]string) []CompletedPart {
    out := make([]CompletedPart, 0, len(parts))
    for number, etag := range parts {
        out = append(out, CompletedPart{Number: number, ETag: etag})
    }
    sort.Slice(out, func(i, j int) bool { return out[i].Number < out[j].Number })
    return out
}

func min64(a, b int64) int64 {
    if a < b {
        return a
    }
    return b
}
Enter fullscreen mode Exit fullscreen mode

There is one awkward boundary: the final completion call and the database update aren't one transaction. If the worker loses its response after completion, I'm not sure a generic S3-compatible service will report that ambiguity in one portable way; the provider's documented behavior resolves it. Design the verifier to inspect the final object and its application metadata before retrying completion. Never assume that an absent upload session means an absent object.

Keep retries bounded and jittered at the job layer. A transient read or network error leaves the checkpoint resumable, so aborting there throws away confirmed work. By contrast, explicit user cancellation, a source-hash mismatch, expired retention, or a tenant-policy rejection should move the record to aborting and invoke Abort. Persist aborted only after that call succeeds. This distinction prevents a routine deploy from converting every interrupted 40 GiB export into abandoned parts, while still giving operators a deterministic cleanup path.

Make completion a manifest decision

The completed object should not be the only evidence that an export is ready. Write an application manifest containing the tenant ID, backup ID, object key, source hash, byte length, creation time, and format version, then publish the export in your database only after verification. Consumers should discover the backup through that committed manifest rather than by listing an object prefix.

Small detail, big effect.

For product images, store immutable image keys and reference them from the export manifest. Don't rebuild image keys from mutable property names during export. The backup then captures a stable tenant view: records point to exact objects, and deleting or renaming a property doesn't silently change a backup already in progress.

Completion input must contain every accepted part exactly once, sorted by part number. Before calling Complete, compare the expected byte ranges with the reconciled part set. ETags are protocol tokens used to identify accepted parts; don't quietly treat them as a portable whole-file checksum. Keep your own source fingerprint and verify the final byte length plus any checksum facility explicitly documented by the chosen service.

Verify isolation, recovery, and cleanup

A happy-path upload proves very little. The release test should interrupt the worker after a remote part succeeds but before the checkpoint save, then restart it and confirm that reconciliation avoids sending that part again. Interrupt it again after the status changes to completing. Verify the final object before declaring success.

The isolation suite deserves equal weight. Give tenant A and tenant B similarly named backup IDs, attempt reads and multipart operations across both credential scopes, and require denial before production. Log tenant ID, backup ID, upload ID, part number, attempt, bytes, and state transition as structured fields, but never log object credentials or signed URLs. Useful counters include active multipart uploads, resume attempts, uploaded bytes, completion latency, abort latency, and checkpoints stuck in completing or aborting.

Use a sweeper for stale sessions, with a retention window longer than the maximum legitimate export. The sweeper should claim the checkpoint, recheck its status and age, request abort, and record the result. Alert on age and state, not on one failed part attempt. That's the postmortem lesson: pages should describe an endangered outcome, not ordinary retry noise.

For rollback, stop scheduling new export jobs first. Let running workers finish or preserve their checkpoints; don't mass-abort them. Roll back the worker binary while keeping the checkpoint schema backward-readable, then resume the same upload IDs. A schema deployment that cannot read the previous checkpoint format is not suitable for this workflow, so use versioned records and test one-version rollback before release.

When should you choose a different design?

Multipart upload is not suitable when backups are small enough for a single bounded request, because the checkpoint and cleanup machinery add operational surface without meaningful recovery value. A filesystem snapshot or database-native backup is a better choice when the requirement is crash-consistent restoration of the whole data store rather than a tenant-scoped application export. Stick with an offline transfer or managed migration workflow when the data set is too large for the application's normal network and scheduling envelope.

The catch is that tenant-prefix isolation also stops being enough when policy requires separate encryption administration, deletion boundaries, audit ownership, or credentials per tenant. Move those tenants to separate buckets or accounts, and keep the same checkpoint state machine above. The protocol can stay stable even when the isolation boundary changes.

Choose the design by testing restore behavior, not by comparing upload throughput alone. A backup that completed quickly but cannot prove tenant scope, source identity, and resumable state is just an object with a reassuring filename.

References

Top comments (0)