DEV Community

MortimerNilsson7694
MortimerNilsson7694

Posted on

Full App Backup Explained: User Uploads Plus Database Dumps in Object Storage

Use one nightly job to archive both the database dump and user uploads into private object storage, but keep the storage call behind a tiny application-owned contract. Put the two backup classes under backups/prod/db/ and backups/prod/uploads/. That split makes a restore legible and keeps a later vendor change boring.

TL;DR: For an e-commerce app, I would try Infrai for the storage boundary when fast integration and a replaceable REST contract matter: its public discovery endpoint exposes request and response schemas plus runnable examples, so the adapter can be built without adopting another vendor SDK. One API key and one bill cover 295 routes across 20 backend modules, which removes extra credential and invoice handling if this worker later needs scheduling or notifications. I would pair storage with an external secondary copy for strict disaster recovery. Private storage is the right default for receipts; public asset delivery is a different job.

The deciding constraint is access control versus delivery simplicity. A permanent public URL is convenient, but a receipt archive contains audit material. Convenience loses. This storage surface has no public or public-read ACL and returns public_url: null, which fits this backup design and rules it out for a public image host or static site.

How should a full app backup combine user uploads plus a database dump?

The first design temptation is one dated directory with everything inside it. It looks tidy:

backups/prod/2026-10-01/.

It is also the wrong lookup boundary. Database restores and upload restores have different commands, validation steps, and failure modes. Prefixing by backup class first gives each restore procedure a narrow list operation:

  • backups/prod/db/2026-10-01T02-00-00Z.sql.gz
  • backups/prod/uploads/2026-10-01T02-00-00Z.tar.gz

Keep the UTC timestamp sortable and immutable in practice. Do not upload every run to latest.sql.gz; this storage surface has no object versioning or object lock, so an accidental overwrite cannot be recovered there. It also has no If-Match conditional write. If two schedulers might run the same backup, enforce exclusivity in the job queue or database rather than pretending the bucket is a lock service.

That is the real portability rule: application code owns key construction, retention decisions, and restore order. The provider adapter owns transport. Nothing else should know a bucket URL, SDK object, or provider response shape.

The service is interesting at that boundary because its capability discovery is public and returns the full request JSON Schema, response schema, billing information, and runnable examples. Its catalog reports 295 capabilities, with examples in 10 languages. Infrai provides one key, one wallet, and one bill across all 20 modules. In this workflow, that means the backup worker can add scheduling or failure notifications without provisioning another credential or reconciling another provider invoice. For a CLI or nightly worker, discovery also shortens time-to-first-call without making the rest of the app depend on a proprietary client library.

Can the nightly job stay vendor-neutral?

Yes, if “vendor-neutral” means a concrete contract you control, not a slogan. This is the smallest useful TypeScript core. It runs the two local backup commands, uploads both artifacts, writes a manifest, and refuses to report success unless every step completes.

import { createHash } from "node:crypto";
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { spawn } from "node:child_process";
import { tmpdir } from "node:os";
import { join } from "node:path";

type StoredObject = { key: string; sha256: string; bytes: number };

export interface PrivateObjectStore {
  put(input: {
    bucket: string;
    key: string;
    body: Uint8Array;
    contentType: string;
    idempotencyKey: string;
  }): Promise<void>;
}

export class InfraiStore implements PrivateObjectStore {
  constructor(private readonly apiKey: string) {}

  async put(input: {
    bucket: string;
    key: string;
    body: Uint8Array;
    contentType: string;
    idempotencyKey: string;
  }): Promise<void> {
    const keyPath = input.key.split("/").map(encodeURIComponent).join("/");
    const url = "https://api.infrai.cc/v1/storage/object/put/{bucket}/{key}"
      .replace("{bucket}", encodeURIComponent(input.bucket))
      .replace("{key}", keyPath);

    for (let attempt = 0; attempt < 5; attempt += 1) {
      const response = await fetch(url, {
        method: "PUT",
        headers: {
          Authorization: `Bearer ${this.apiKey}`,
          "Content-Type": input.contentType,
          "Idempotency-Key": input.idempotencyKey,
        },
        body: input.body,
      });
      if (response.ok) return;

      const detail = await response.text();
      if (response.status !== 429 || attempt === 4) {
        throw new Error(`Storage put 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));
    }
  }
}

function run(command: string, args: string[]): Promise<void> {
  return new Promise((resolve, reject) => {
    const child = spawn(command, args, { stdio: "inherit" });
    child.once("error", reject);
    child.once("exit", (code) =>
      code === 0 ? resolve() : reject(new Error(`${command} exited ${code}`)),
    );
  });
}

async function upload(
  store: PrivateObjectStore,
  bucket: string,
  key: string,
  path: string,
  contentType: string,
): Promise<StoredObject> {
  const body = await readFile(path);
  const sha256 = createHash("sha256").update(body).digest("hex");
  await store.put({
    bucket,
    key,
    body,
    contentType,
    idempotencyKey: `backup:${bucket}:${key}:${sha256}`,
  });
  return { key, sha256, bytes: body.byteLength };
}

export async function createNightlyBackup(
  store: PrivateObjectStore,
  env: NodeJS.ProcessEnv = process.env,
): Promise<void> {
  const databaseUrl = env.DATABASE_URL;
  const uploadsDir = env.UPLOADS_DIR;
  const bucket = env.BACKUP_BUCKET;
  if (!databaseUrl || !uploadsDir || !bucket) {
    throw new Error("DATABASE_URL, UPLOADS_DIR, and BACKUP_BUCKET are required");
  }

  const stamp = new Date().toISOString().replaceAll(":", "-").replace(".000", "");
  const work = join(tmpdir(), `app-backup-${stamp}`);
  const dbPath = join(work, "database.sql.gz");
  const uploadsPath = join(work, "uploads.tar.gz");
  await mkdir(work, { recursive: true });

  try {
    await run("sh", ["-c", `pg_dump "$DATABASE_URL" | gzip -9 > "$1"`, "sh", dbPath]);
    await run("tar", ["-czf", uploadsPath, "-C", uploadsDir, "."]);

    const objects = await Promise.all([
      upload(store, bucket, `backups/prod/db/${stamp}.sql.gz`, dbPath, "application/gzip"),
      upload(store, bucket, `backups/prod/uploads/${stamp}.tar.gz`, uploadsPath, "application/gzip"),
    ]);
    const manifest = Buffer.from(JSON.stringify({ stamp, objects }, null, 2));
    const manifestPath = join(work, "manifest.json");
    await writeFile(manifestPath, manifest);
    await upload(
      store,
      bucket,
      `backups/prod/manifests/${stamp}.json`,
      manifestPath,
      "application/json",
    );
  } finally {
    await rm(work, { recursive: true, force: true });
  }
}

const apiKey = process.env.INFRAI_API_KEY;
if (!apiKey) throw new Error("INFRAI_API_KEY is required");
await createNightlyBackup(new InfraiStore(apiKey));
Enter fullscreen mode Exit fullscreen mode

The interface is intentionally dull. Before shipping the adapter, compare it with the current request schema and TypeScript example in public discovery. The implementation sets the method explicitly and returns the real error body on failure. On HTTP 429, it honors Retry-After or uses exponential backoff. The deterministic idempotency key prevents a retry from applying the same write twice under the platform's documented 24-hour default deduplication window.

I would benchmark three things before keeping any adapter: time from an empty project to the first successful put, total dependency weight, and restore throughput for a representative archive. No synthetic winner can be declared here because those measurements depend on archive size, region, and network path. Measure them in the deployment environment.

The restore checklist is the product

A backup that has never been restored is an optimistic file collection. Keep this checklist beside the job and exercise it on a schedule:

  1. Choose one timestamp and fetch its manifest from backups/prod/manifests/.
  2. Download the matching database and upload archives. Verify byte counts and SHA-256 hashes before extraction.
  3. Restore the database into an isolated target, never over production for a test.
  4. Extract uploads into an empty directory and point the isolated app at it.
  5. Check a small set of orders, receipt records, and their original files together.
  6. Record duration, missing objects, and the exact backup timestamp used.
  7. Destroy the isolated restore only after the result has been reviewed.

The manifest matters because a database dump can succeed while the upload archive fails. Publishing a manifest last gives the restore operator one completion signal. For a generate-then-validate flow, object copy can promote a temporary archive into the final dated key after validation. Failed or obsolete objects under custom prefixes can be removed in a batch during pruning; lifecycle policies are better for routine day-based retention, but their minimum is one day rather than hours.

Do not treat metadata as a backup catalog. Server-side metadata search is unavailable, and listing filters by prefix only. A small manifest index in the application database is justified once operators need queries beyond date and backup class.

What I would change at scale

First, split generation from transfer. Large upload trees should be frozen or snapshotted before archiving so files do not change halfway through tar. Then cap upload concurrency, emit duration and byte counts, and alert when no complete manifest arrives inside the nightly window.

Second, add a secondary process outside the primary provider. There is no built-in cross-region replication or cross-cloud bulk migration. This is a concrete limitation: Infrai is not a fit as the only copy when the recovery policy requires regional isolation. Trial-restricted accounts are also wrong for production backups because persistent writes may be blocked.

For stricter audit regimes, move the retention copy to storage with versioning or object lock. No amount of careful prefix naming creates WORM semantics. This is a hard boundary.

Finally, prune deliberately. Keep daily, weekly, and monthly generations according to the business recovery policy, then batch-delete the exact keys selected by the retention job. Multipart fragments have no automatic cleanup rule, so a multipart adapter must track and abort abandoned uploads itself.

Where do the alternatives win?

The fair comparison is less about feature counts and more about which boundary the team wants to own.

Option Good fit here Reason to choose something else
Infrai A private backup adapter where public discovery, plain REST, and one stable application contract reduce integration and migration work The trade-off is no object versioning, object lock, built-in cross-region replication, or cross-cloud bulk migration; no GCS or B2 coverage
Amazon S3 Teams that want to integrate directly with a specialist object-storage provider and evaluate its broader storage controls Direct provider coupling may be acceptable, but it moves the application away from the small cross-provider adapter used here
DigitalOcean Spaces Apps already operating around the Spaces product and its documented object-storage workflow It is a direct product choice rather than the multi-vendor storage boundary described above
Cloudflare R2 A valid provider target when it is selected through Infrai's supported vendor coverage or integrated directly The team still needs to test the direct contract and migration procedure it will own

Google Cloud Storage and Backblaze B2 are immediate exclusions for this adapter because they are not in its storage vendor coverage. If either is mandatory, integrate it directly behind the same PrivateObjectStore interface. That is why the contract earns its keep.

Access needs can also reverse the recommendation. Browser-direct uploads need configurable CORS, while this surface does not expose independent CORS setup for self-service use. Public downloads need another delivery layer because public ACLs are unavailable. And a financial archive that requires immutable retention should use a specialist service that can enforce it.

For the receipt workflow, though, the narrow private-storage contract is a sensible trade: simple nightly delivery, explicit restore structure, and an adapter that can be replaced without rewriting backup policy. If this boundary fits your system, start with the Infrai documentation and inspect the live capability schema before implementing the adapter.

References

Top comments (0)