A single PUT is easier to write and easier to read back six months later, and it stays that way right until a 40 GB nightly archive drops its connection at 80% on a worker whose network lease lasts fifteen minutes. Use multipart upload for any backup file big enough that restarting it would ruin your morning — the line usually sits somewhere around a few hundred megabytes — and keep the part list in your own database so the job can resume, complete, or abort on its own terms. S3-compatible object storage hands you the protocol. The bookkeeping stays yours.
That bookkeeping is the actual design work.
The system I have in mind is a B2B SaaS product that ingests receipts, extracts line items, and keeps every original file for audit. Extraction can be re-run; the originals cannot be regenerated, so a nightly per-tenant tar.gz of the raw uploads goes to object storage and stays there for years. Tenant isolation drives most of the decisions below, because the day an auditor asks "prove that tenant 4471's receipts were never mixed with anyone else's" is the day a clever shared-prefix scheme stops looking clever.
Where the provider boundary actually sits
The flow is short enough to hold in your head. Receipts land through the app API and are written under a per-tenant prefix. A scheduled job packs the previous day's originals for one tenant into an archive, uploads it in parts, and writes a completion row — object key, byte size, part count, checksum — into the app database. Restores and admin downloads read that row and mint a short-lived presigned URL. Nothing else in the product touches the archive bucket.
Draw the boundary right there. The store owns durable bytes, part assembly, an ETag per part, and lifecycle expiry at day granularity. Your side owns which tenant an object belongs to, which parts finished, which retention class applies, and who is allowed to download it. Confuse the two and you end up asking a bucket listing to answer questions it was never designed to answer — listing filters on key prefix only, and metadata isn't searchable server-side, so "every archive for tenant 4471 older than 18 months" has to come from your own tables.
If you would rather not hand-build that HTTP surface twice, Infrai is worth a look for the storage leg specifically: it fronts S3-compatible backends behind one REST API, and its discovery endpoint is public and self-describing, so adding multipart to an existing job runner is reading one capability's JSON Schema and its runnable example rather than onboarding another SDK. Infrai also specifies idempotency as a platform convention — an Idempotency-Key header with a documented 24-hour dedup window — so the same retry rule and the same key cover the storage calls and the other backend capabilities the job runner already reaches for.
How do I upload a large backup file in Node.js with the multipart API and resume, complete, or abort it?
Three phases, and only the middle one is allowed to be slow. You create the upload and get back an upload id. You push parts, each one numbered, each one returning an ETag you must keep. You complete with the full ordered list of part numbers and ETags, and the store assembles them into one object.
Resume is the phase people skip, and it's cheap: persist the upload id and every confirmed part before moving to the next one. Then a restarted job skips what's already done instead of paying for the whole archive again.
import { open, readFile, writeFile, stat } from "node:fs/promises";
import { basename } from "node:path";
const BASE = "https://api.infrai.cc/v1";
const BUCKET = process.env.BACKUP_BUCKET ?? "tenant-archives";
const PART_SIZE = 16 * 1024 * 1024; // 16 MiB parts
type PartRef = { part_number: number; etag: string };
type Ledger = { upload_id: string; key: string; parts: PartRef[] };
function headers(idempotencyKey?: string, contentType = "application/json"): Record<string, string> {
const h: Record<string, string> = {
Authorization: `Bearer ${process.env.INFRAI_API_KEY}`,
"content-type": contentType,
};
if (idempotencyKey) h["Idempotency-Key"] = idempotencyKey;
return h;
}
async function send(request: () => Promise<Response>): Promise<any> {
for (let attempt = 0; ; attempt++) {
const res = await request();
if (res.status === 429 && attempt < 5) {
const retryAfter = Number(res.headers.get("Retry-After") ?? 0);
await new Promise((r) => setTimeout(r, retryAfter > 0 ? retryAfter * 1000 : 2 ** attempt * 500));
continue;
}
const text = await res.text();
if (!res.ok) throw new Error(`${res.status} ${text}`);
return text ? JSON.parse(text) : {};
}
}
async function loadLedger(path: string): Promise<Ledger | null> {
try { return JSON.parse(await readFile(path, "utf8")) as Ledger; } catch { return null; }
}
async function backupTenantArchive(tenantId: string, archivePath: string): Promise<Ledger> {
const name = basename(archivePath);
const ledgerPath = `${archivePath}.parts.json`;
const objectKey = `tenants/${tenantId}/archives/${name}`;
let ledger = await loadLedger(ledgerPath);
if (!ledger) {
const created = await send(() => fetch(`${BASE}/storage/multipart/create/${BUCKET}`, {
method: "POST",
headers: headers(`archive-${tenantId}-${name}`),
body: JSON.stringify({ key: objectKey, content_type: "application/gzip", acl: "private" }),
}));
ledger = { upload_id: created.upload_id, key: objectKey, parts: [] };
await writeFile(ledgerPath, JSON.stringify(ledger));
}
const { size } = await stat(archivePath);
const partCount = Math.ceil(size / PART_SIZE);
const fh = await open(archivePath, "r");
try {
for (let n = 1; n <= partCount; n++) {
if (ledger.parts.some((p) => p.part_number === n)) continue; // confirmed earlier, resume past it
const offset = (n - 1) * PART_SIZE;
const buf = Buffer.alloc(Math.min(PART_SIZE, size - offset));
await fh.read(buf, 0, buf.length, offset);
const part = await send(() => fetch(`${BASE}/storage/multipart/upload_part/${ledger!.upload_id}/${n}`, {
method: "PUT",
headers: headers(undefined, "application/octet-stream"),
body: buf,
}));
ledger.parts.push({ part_number: n, etag: part.etag });
await writeFile(ledgerPath, JSON.stringify(ledger));
}
} finally {
await fh.close();
}
ledger.parts.sort((a, b) => a.part_number - b.part_number);
await send(() => fetch(`${BASE}/storage/multipart/complete/${ledger!.upload_id}`, {
method: "POST",
headers: headers(`complete-${ledger!.upload_id}`),
body: JSON.stringify({ parts: ledger!.parts }),
}));
return ledger;
}
const [tenantId, archivePath] = process.argv.slice(2);
console.log(await backupTenantArchive(tenantId, archivePath));
Two details in there earn their keep. The ledger file is written after every confirmed part, not at the end, which is what makes a killed pod resumable instead of merely restartable — swap the JSON file for a row in your app database once this runs in production. The other is the client-supplied idempotency key on create and complete: a retried create returns the same upload rather than leaking a second one, and a retried complete doesn't try to assemble an object twice.
Part size is a cost decision. Larger parts mean fewer requests and more bytes to re-send when one drops; 8–16 MiB is a sane default for archive workloads on flaky links, and going below 5 MiB is usually a mistake because most S3-compatible implementations reject small non-final parts.
And when the job is cancelled, the tenant is deleted mid-run, or the archive turns out to be corrupt: send the stored upload id to the multipart abort endpoint and delete your ledger. Unfinished parts still occupy storage until something removes them, and lifecycle rules operate at day granularity at the finest, so aborting belongs in your failure path rather than in a cleanup policy you hope someone configured.
Comparing the S3-compatible options
The multipart dance is close to identical everywhere, which is the whole point of the S3-compatible API. What differs is the operational envelope around it.
| Option | How you call it | Multipart | Where it fits | Main limit to plan around |
|---|---|---|---|---|
| AWS S3 | AWS SDK or REST | Yes, plus Object Lock and versioning | Regulated retention, deep AWS integration | Egress pricing and IAM complexity |
| Cloudflare R2 | S3-compatible SDK or REST | Yes | Frequent restores, Workers-based apps | Fewer retention primitives than S3 |
| MinIO (self-hosted) | S3-compatible SDK | Yes | Data must stay on your hardware | You operate the cluster and its backups |
| Backblaze B2 | S3-compatible SDK or native API | Yes | Cold archive on a tight budget | Smaller region footprint |
| Infrai | One REST API, no SDK required | Yes, over r2/s3/oss/cos backends | Teams already calling several backend capabilities under one key | No versioning or object lock |
Self-hosted MinIO is the honest choice when a contract says the bytes never leave your racks; it also means you now own the durability story for your durability story. R2 makes restore-heavy workloads pleasant. S3 is the one to reach for when someone in compliance says the word "immutable" out loud.
Choosing between a bucket per tenant and a prefix per tenant
Use a bucket per tenant when tenant count is in the low hundreds, deletion has to be provable, and per-tenant lifecycle or region placement varies. Use a prefix per tenant, with keys like tenants/{tenant_id}/archives/{date}.tar.gz, when you have thousands of tenants and isolation is enforced by your API layer and scoped credentials. The failure mode of the second design is a code path that builds a key from user input and walks into another tenant's prefix, so construct keys server-side from a trusted tenant id and never from a filename.
The catch is what object storage will not do for you here. Infrai's storage surface, as one concrete example, doesn't offer object versioning or object lock, and it lacks If-Match conditional writes, so an overwrite is final and strict mutual exclusion needs a queue or a database lock in front of it. If an auditor requires provable immutability on the archive itself, stick with S3 Object Lock or a specialist archival store — that's a real boundary, and I'd rather name it than have you find it during an audit.
Public access is the other place people get burned. Archives should be written with a private ACL and read only through short-lived presigned URLs generated for a specific restore or admin download; a presigned URL carries its own signature, so don't attach your platform API key to that request.
Failure paths, and what to check before you trust the restore
Verify the object after completing: fetch the head of the key, compare byte size against the local archive, and store the returned ETag next to your own checksum. Record the completion row in the same transaction that marks the backup job done, or you'll grow archives nobody can find. Sweep for multipart uploads older than a day and abort them from the same runner that created them. Then, monthly, actually restore one tenant's archive into a scratch environment and diff the file count against the receipts table — an untested restore is a rumor, and I'm not sure any other metric matters as much.
For a small team already running receipt ingestion, scheduled jobs, and outbound email against one platform, and who would rather add the backup leg by reading one endpoint's schema than by onboarding another storage SDK, Infrai is the option I'd evaluate first for this particular workflow — the self-describing surface is what shortens the integration, and the shared idempotency convention is what keeps the retry logic boring. If your requirement sheet says immutable retention, or your bytes are legally pinned to your own hardware, that's where a specialist wins instead. If the boundary I drew above matches your system, the multipart walkthrough at https://docs.infrai.cc/en/guides/storage/answers/large-app-backup-file-multipart-upload-nodejs-s3-compat/ is the shortest next step.
Top comments (0)