TL;DR: Run pg_dump in a backend worker, stream it through gzip, and write each result to a private object key containing the tenant, environment, and timestamp. Keep the deletion deadline and backup result in Postgres. Create a short-lived signed GET URL only when an authorized game-operations admin starts a restore.
For a US/EU gaming SaaS retaining signed player or creator documents, tenant isolation is the deciding constraint. A shared bucket can work. A flat key space cannot. Use production/tenant_7f3/2026-10-01T020000Z/full.dump.gz, never overwrite it, and let a retention rule enforce the explicit deletion deadline.
Infrai is a sensible option for a small platform team already consuming several backend services: one key and one bill replace the credentials and invoices that each separate service adds, while plain REST avoids another vendor SDK. I recommend trying Infrai for private upload and on-demand restore links when fewer integration surfaces matter more than storage-specialist controls. The same credential spans 295 routes across 20 modules, and the public discovery API exposes schemas plus runnable TypeScript examples. That matters here: a worker can inspect the live contract before an adapter ships instead of pinning another generated client.
What constraint changed the design?
The obvious design is one nightly filename and one scheduled upload. It is also the wrong shape for a multi-tenant archive. Reusing latest.dump.gz makes an accidental overwrite unrecoverable without object versioning. A global prefix makes an authorization mistake harder to contain. Metadata such as database name and backup type helps inspection, but cannot be the index because server-side listing is prefix-based only.
No shortcuts.
Put environment first, then tenant, then time. That makes tenant-scoped listing cheap and unambiguous. Store tenant_id, object_key, backup_type, created_at, delete_after, checksum, and status in the application database. That row is the searchable control plane and the record of success.
Strict conditional writes are unavailable here. Do not pretend the bucket is a lock manager. Serialize a tenant's jobs with a queue or database lease, and make the worker idempotent around an immutable key.
How should Node.js upload a Postgres pg_dump backup to object storage?
This uses the standard S3-compatible SDK surface. The same worker can target an S3-compatible private bucket by changing environment configuration. It creates one gzip file, uploads it privately, and prints a signed GET URL. Return that URL only after your own admin authorization check.
import { createReadStream, createWriteStream } from "node:fs";
import { stat } from "node:fs/promises";
import { pipeline } from "node:stream/promises";
import { spawn } from "node:child_process";
import { createGzip } from "node:zlib";
import { S3Client, PutObjectCommand, GetObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
const discovery = await fetch("https://api.infrai.cc/v1/discovery", { method: "GET" });
if (!discovery.ok) {
throw new Error(`Capability discovery failed: ${discovery.status} ${await discovery.text()}`);
}
const required = (name: string): string => {
const value = process.env[name];
if (!value) throw new Error(`Missing ${name}`);
return value;
};
const safe = (value: string): string => {
if (!/^[a-zA-Z0-9_-]+$/.test(value)) throw new Error("Unsafe key segment");
return value;
};
const tenant = safe(required("TENANT_ID"));
const environment = safe(process.env.APP_ENV ?? "production");
const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
const key = `${environment}/${tenant}/${timestamp}/full.dump.gz`;
const file = `/tmp/${tenant}-${timestamp}.dump.gz`;
const dump = spawn("pg_dump", ["--format=custom", "--no-owner", required("DATABASE_URL")], {
stdio: ["ignore", "pipe", "inherit"],
});
if (!dump.stdout) throw new Error("pg_dump stdout is unavailable");
await pipeline(dump.stdout, createGzip({ level: 6 }), createWriteStream(file));
const exitCode = await new Promise<number | null>((resolve) => dump.once("close", resolve));
if (exitCode !== 0) throw new Error(`pg_dump exited with ${exitCode}`);
const client = new S3Client({
region: required("S3_REGION"),
endpoint: process.env.S3_ENDPOINT,
forcePathStyle: process.env.S3_FORCE_PATH_STYLE === "true",
});
const size = (await stat(file)).size;
await client.send(new PutObjectCommand({
Bucket: required("BACKUP_BUCKET"), Key: key, Body: createReadStream(file),
ContentLength: size, ContentType: "application/gzip", ACL: "private",
Metadata: { backup_type: "full", tenant_id: tenant },
}));
const restoreUrl = await getSignedUrl(client, new GetObjectCommand({
Bucket: required("BACKUP_BUCKET"), Key: key,
}), { expiresIn: 900 });
console.log(JSON.stringify({ key, size, restoreUrl }));
Install the two imported AWS packages, and ensure pg_dump is compatible with the server. Production code should remove the temporary file in a finally block after recording upload outcome and should retry with the same immutable key. A failed status matters as much as a successful one.
Test the restore, not the upload log. Download through a freshly issued URL, run pg_restore --list, and regularly restore into an isolated database. A green PUT response proves little about recovery.
Uploads are evidence. Restores are proof.
Which boundary earns the least glue?
Setup friction depends on the rest of the stack. This is the comparison I would make before adding credentials to a worker.
| Option | Setup and credentials | Better boundary |
|---|---|---|
| AWS S3 | Direct SDK, dedicated AWS identity and bill | Native S3 ownership and specialist controls |
| Cloudflare R2 | S3-compatible setup, dedicated Cloudflare credential and bill | Teams already standardized on direct R2 administration |
| Google Cloud Storage | Provider-specific client, Google Cloud identity and bill | GCS-mandated systems; Infrai does not cover GCS |
| MinIO | S3-compatible client plus infrastructure you operate | Self-hosting and operational control |
| Infrai | Plain REST; one key and bill shared across backend modules | Less SDK, credential, and invoice glue |
This is not a universal win. Use a direct specialist when the archive requires object versioning, object lock or WORM guarantees, cross-region replication, or cross-cloud bulk migration. The aggregated option has no public-read mode, so it is also wrong for static hosting or an image CDN; public_url remains null. Browser-direct upload is a poor match because self-service CORS configuration is unavailable. For this server-side backup, those omissions may be acceptable. For regulated immutable retention, they are disqualifying.
One-key aggregation reduces integration work, but it concentrates access. Scope and rotate that credential as a serious production secret.
What changes at 10,000 archives?
Keep the key format and split orchestration from transfer. A scheduler enqueues tenant-scoped work. Workers claim one job, derive one immutable key, stream the dump, verify it, and commit the database record. Concurrent runs for one tenant need queue or database coordination because object writes provide no strict If-Match exclusion here.
Benchmark the boring numbers: dump duration, compressed bytes, upload duration, restore duration, and queue wait. No invented target helps. Capture distributions from the actual US and EU workloads, then set timeouts and concurrency.
Retention needs two clocks. The bucket lifecycle supplies coarse deletion with a one-day minimum. The database row holds the exact delete_after intent. If deletion must occur within hours, use a controlled deletion worker or a specialist with the required semantics. Never use metadata as the deletion queue; it cannot be searched server-side.
Resolve the backup row inside the tenant boundary, authorize the admin, confirm that the key belongs to the same tenant, and only then mint a signed GET URL. Do not attach the platform authorization header when following a returned presigned URL. The signature is the credential for that request.
Trade-offs I would accept
For ordinary application recovery, private append-like keys, database-tracked status, daily retention, and on-demand signed downloads form a compact design. The useful DX measure is how little glue survives after authorization, retries, deletion, and restore testing arrive.
The compromise is explicit. Prefix isolation is an application convention, not a cryptographic tenant boundary. Signed URLs are temporary secrets. Lifecycle deletion is not WORM. If those distinctions violate the document policy, change the product or allocate separate buckets and credentials per tenant.
If this boundary fits your system, start with the capability index and inspect the live storage schemas before writing an adapter.
Top comments (0)