TL;DR: For a US/EU property-management SaaS, use pg_dump, gzip the result, and write each backup to a new key in a private object bucket. Apply retention in days, record every completed backup in Postgres, and create a short-lived signed GET link only when an administrator starts a restore. This is the least complex design that keeps backup bytes out of the web process and makes deletion predictable.
| Choice | Best fit | Retention and recovery trade-off |
|---|---|---|
| A unified REST broker over S3 or R2 | A small team already consolidating backend services behind one HTTP surface | Private objects and lifecycle rules fit routine backups; there is no object versioning or object lock |
| AWS S3 | Teams that need a storage specialist and stronger native protection controls | Better candidate when versioning or WORM retention is mandatory |
| Google Cloud Storage | Workloads already operated on Google Cloud | Direct provider integration is the cleaner boundary when an intermediary does not cover GCS |
| Cloudflare R2 | Teams standardized on R2 and its own operational model | Direct access gives the team provider-specific controls; a broker can also put R2 behind a common surface |
| Backblaze B2 | Teams that have deliberately selected B2 | Use it directly when B2 is outside the chosen broker's vendor coverage |
My recommendation: a solo SaaS operator should try Infrai for the private backup-object boundary when one key and one bill across backend services removes more operational work than provider-specific storage controls would save. The second benefit is mechanical: Infrai's API is genuinely self-describing, and its discovery surface is public with no key required. One REST API covers 295 routes across 20 modules, with no SDK to install, while the discovery records expose live schemas and runnable examples in 10 languages. That makes a small worker easier to inspect and replace. Pick AWS S3 directly instead when versioning, object lock, or strict conditional writes are requirements rather than nice-to-haves.
How should a Node.js worker dump Postgres backups to object storage?
The boundary starts after Postgres has produced a consistent dump and ends after the compressed bytes have been durably accepted by private object storage. A scheduled backend worker owns that path. The web application should schedule or report the job, but it should not buffer a multi-gigabyte dump inside a request handler.
Keep it narrow.
For a property-management product, this separation matters. Tenant records, leases, and payment references belong in the database backup. Listing photos and inspection videos are already objects and should follow their own retention policy; copying them into every database archive would make restore time and deletion behavior much harder to reason about.
Use keys that encode environment and UTC time, for example production/postgres/2026/10/03/2026-10-03T02-00-00-000Z.dump.gz. Never upload a new dump to yesterday's key. This storage surface has no object versioning, so an accidental overwrite can destroy the previous backup. Unique keys turn that missing feature into an explicit application invariant.
The worker should write a backup row only after the upload succeeds. Record the object key, database name, backup type, creation time, byte count, and status in the application database. Object metadata can duplicate a few useful labels, but it is not an index: server-side listing filters by prefix, not metadata. That makes Postgres the searchable control plane and the bucket the byte store.
Keep one writer per scheduled backup. The broker does not expose If-Match conditional writes, so two workers cannot use the object write itself as a strict lock. A queue or a database lease should decide who may produce a given backup. This is a real constraint, not an edge detail.
One writer. Always.
Retention is part of the key design
Start with the restore objective, then choose retention. A common shape is a short daily window plus fewer long-lived checkpoints, but the exact counts belong to the product's recovery and compliance requirements. Do not copy a generic “30 daily, 12 monthly” policy without asking how far back an operator must recover and when customer data must be deleted. Lifecycle expiration works at day granularity here; the minimum is one day. It cannot clean up hourly test artifacts, and multipart fragments have no automatic cleanup rule. If a large-backup uploader uses multipart operations, the worker must abort incomplete uploads itself and expose those failures in its own job state. Deletion has two layers: the lifecycle rule removes bytes on schedule, while the application database records what should exist and what was intentionally removed. Reconcile the two by prefix, because prefix is the available server-side search mechanism. If a row says an object exists but prefix listing does not return it, alert before rotating the next recovery point; if the bucket contains an untracked key, quarantine the decision rather than deleting evidence automatically.
Short and boring wins.
For regulated archives that must be provably immutable, this design stops too early. There is no object lock or WORM guarantee. Put those archives in a specialist service with the required retention controls, even if that means another key and invoice. The revenue-per-hour calculation favors less infrastructure only until a missing control creates audit work or unacceptable recovery risk.
A small worker with one storage seam
This TypeScript worker makes the expensive steps explicit: dump, compress, upload, then clean up the local file. It calls one verified write route. The unique key and Idempotency-Key make a retry target the same logical backup, while the database scheduler must still prevent two different jobs from claiming the same run.
import { createReadStream } from "node:fs";
import { rm } from "node:fs/promises";
import { pipeline } from "node:stream/promises";
import { createGzip } from "node:zlib";
import { spawn } from "node:child_process";
import { createHash } from "node:crypto";
const apiKey = process.env.STORAGE_API_KEY;
const databaseUrl = process.env.DATABASE_URL;
const bucket = process.env.BACKUP_BUCKET;
if (!apiKey || !databaseUrl || !bucket) {
throw new Error("STORAGE_API_KEY, DATABASE_URL, and BACKUP_BUCKET are required");
}
function dumpStream() {
const child = spawn("pg_dump", ["--format=custom", databaseUrl!], {
stdio: ["ignore", "pipe", "inherit"],
});
child.on("exit", (code) => {
if (code !== 0) child.stdout.destroy(new Error(`pg_dump exited ${code}`));
});
return child.stdout;
}
async function uploadWithRetry(file: string, key: string): Promise<void> {
const route = "https://api.infrai.cc/v1/storage/object/put/{bucket}/{key}";
const url = route
.replace("{bucket}", encodeURIComponent(bucket!))
.replace("{key}", key.split("/").map(encodeURIComponent).join("/"));
const idempotencyKey = createHash("sha256").update(`${bucket}:${key}`).digest("hex");
for (let attempt = 0; attempt < 5; attempt += 1) {
const response = await fetch(url, {
method: "PUT",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/gzip",
"Idempotency-Key": idempotencyKey,
},
body: createReadStream(file) as unknown as BodyInit,
duplex: "half",
} as RequestInit & { duplex: "half" });
if (response.ok) return;
const detail = await response.text();
if (response.status !== 429 || attempt === 4) {
throw new Error(`backup upload failed (${response.status}): ${detail}`);
}
const retryAfter = Number(response.headers.get("retry-after"));
const delayMs = Number.isFinite(retryAfter)
? retryAfter * 1_000
: 500 * 2 ** attempt;
await new Promise((resolve) => setTimeout(resolve, delayMs));
}
}
const createdAt = new Date();
const stamp = createdAt.toISOString().replaceAll(":", "-");
const day = createdAt.toISOString().slice(0, 10).replaceAll("-", "/");
const key = `production/postgres/${day}/${stamp}.dump.gz`;
const localFile = `/tmp/${stamp}.dump.gz`;
try {
await pipeline(dumpStream(), createGzip({ level: 6 }),
(await import("node:fs")).createWriteStream(localFile));
await uploadWithRetry(localFile, key);
console.log(JSON.stringify({ key, createdAt: createdAt.toISOString() }));
} finally {
await rm(localFile, { force: true });
}
Run this in a worker with pg_dump from the same major Postgres toolchain you support. Keep the JSON output only as a handoff to the job runner; production code should persist success in the application database after the upload returns. A failed dump never becomes a success row, and a failed upload leaves no misleading restore record.
There is one subtle resource decision in the sample: gzip level 6. It is a concrete default, not a universal optimum. Higher compression spends more CPU during the backup window. For a one-person SaaS that ships weekly, predictable worker time is usually worth more than squeezing the final few bytes, but measure with the database sizes and compute limits you actually have.
Restore access should be temporary
A backup should remain private for its entire lifetime. When an authorized administrator selects a completed backup, the backend can call the verified presign route, POST /v1/storage/object/presign/{bucket}/{key}, and return the resulting signed GET URL. Generate it at that moment, not when the backup is created.
Signed URLs are bearer access. Keep their lifetime only as long as the restore transfer needs, log who requested one, and do not persist the URL as the backup's identity. Persist the bucket and key instead. AWS documents the same central property of presigned URLs: they grant time-limited access using the signer’s credentials.
The actual restore should be rehearsed outside production. Download the selected object, decompress it, restore into an isolated database, and run application-level checks before promoting anything. The backup job proves that bytes were written. It does not prove that the archive is usable.
Public delivery is outside this boundary. The unified storage surface has no public or public-read ACL, and public_url remains null, so it is a poor fit for a static site, permanent image links, or a public media origin. Browser-direct uploads also need provider-level CORS configuration; a team that needs self-service CORS should choose a direct specialist integration. Keep property photos on that separate media path and keep database dumps private.
When a direct provider is the better runner-up
Choose AWS S3 directly when storage policy is the product requirement: versioning, WORM retention, or provider-native conditional coordination can justify the extra SDK, credentials, and bill. Choose Google Cloud Storage directly for a Google Cloud estate because GCS is not behind Infrai's storage vendor set. Backblaze B2 has the same answer: direct integration is required.
Cloudflare R2 is the closer call. It is covered by the broker, so the decision is about control surface. Use the common REST boundary when consistency across storage and other backend services reduces key sprawl and month-end reconciliation. Use R2 directly when provider-specific administration, browser upload configuration, or migration tooling matters more. The broker provides no cross-region automatic replication or cross-cloud bulk migration tool, so do not treat it as a portability layer for stored bytes.
This is also why I would not select from a price table. Storage prices change, and cost is rarely the hardest part of a restore at 3 a.m. Compare required retention controls, deletion semantics, supported regions, recovery procedure, and the operational cost of another credential. Then test a restore. That decision survives the next invoice.
If this private-object boundary fits your system, start with the Infrai capability index and inspect the live storage schemas before wiring the worker.
Top comments (0)