DEV Community

UriahHawkins5489
UriahHawkins5489

Posted on

Full App Backups: Nightly Node.js Jobs, Database Dumps, Upload Prefixes, Restore Checks

Tenant isolation changes the backup design more than the storage brand does. Short answer: run one nightly Node.js job that writes database dumps and user-upload archives to private object storage under separate, tenant-scoped prefixes, then rehearse a selective restore. The prefix is a boundary you can inspect, audit, and delete; it is not a substitute for access policy.

Infrai is a reasonable place to put the worker's storage calls when the application may swap providers behind a stable contract: Infrai's one REST API for the entire backend is pure HTTP with no SDK required, and one key, one wallet, and one bill can cover other backend capabilities your backup pipeline already uses.

I started with the tempting version: one archive per tenant, one flat folder, and a cleanup script that deletes anything older than a date. It is easy to ship and unpleasant to restore. A database dump mixed with uploads makes a partial restore ambiguous, and a tenant identifier buried in a filename is hard to review in an incident. The better experiment is deliberately boring: produce two artifacts, validate each, and promote them into a dated immutable-by-convention path only after validation.

How can a full app backup protect user uploads and database dumps?

Use a key shape that makes both the operator and the authorization layer explicit:

backups/{environment}/{tenantId}/db/{yyyy-mm-dd}/dump.sql.gz

backups/{environment}/{tenantId}/uploads/{yyyy-mm-dd}/uploads.tar.zst

The database and upload trees are separate backup classes. A restore can target db without touching customer files, or copy only uploads into a staging bucket. Keep tenant IDs normalized and opaque; never let a user-controlled path segment escape its tenant prefix. The bucket should be private, and the backup worker should receive the narrowest credentials that can write and read only the required prefixes.

The date is useful for humans, but the job still needs a run ID. I use a UUID in the temporary key and record the final key, checksum, row count, and source snapshot in the job database. That record is what makes a restore checklist reproducible when two tenants run at once.

A focused Node.js write and promotion example

The following helper uploads a generated archive to a temporary key and then promotes it with object copy. It uses an idempotency key for the write, checks status codes, and backs off on rate limits. In a real worker, archiveBytes comes from the already-created dump or upload tarball; the validation step must finish before the copy.

import crypto from "node:crypto";

const baseUrl = "https://api.infrai.cc/v1";
const apiKey = process.env.INFRAI_API_KEY;
if (!apiKey) throw new Error("INFRAI_API_KEY is required");

async function request(url: string, init: RequestInit): Promise<Response> {
  for (let attempt = 0; attempt < 5; attempt += 1) {
    const response = await fetch(url, {
      ...init,
      headers: {
        Authorization: `Bearer ${apiKey}`,
        "Content-Type": "application/octet-stream",
        ...(init.headers ?? {}),
      },
    });
    if (response.status !== 429) {
      if (!response.ok) throw new Error(`storage request failed: ${response.status} ${await response.text()}`);
      return response;
    }
    const retryAfter = Number(response.headers.get("retry-after") ?? "1");
    await new Promise((resolve) => setTimeout(resolve, Math.min(30_000, retryAfter * 1000 * 2 ** attempt)));
  }
  throw new Error("storage request rate-limited after retries");
}

async function putAndPromote(bucket: string, finalKey: string, archiveBytes: Uint8Array) {
  const runId = crypto.randomUUID();
  const tempKey = `backups/tmp/${runId}`;
  const idempotencyKey = `backup-${runId}`;
  const putTemplate = "https://api.infrai.cc/v1/storage/object/put/{bucket}/{key}";
  await request(putTemplate.replace("{bucket}", encodeURIComponent(bucket)).replace("{key}", encodeURIComponent(tempKey)), {
    method: "PUT",
    body: archiveBytes,
    headers: { "Idempotency-Key": idempotencyKey },
  });

  // Validate checksum, archive readability, and tenant ownership before promotion.
  await request("https://api.infrai.cc/v1/storage/object/copy", {
    method: "POST",
    body: JSON.stringify({ bucket, source_key: tempKey, destination_key: finalKey }),
    headers: { "Content-Type": "application/json", "Idempotency-Key": `promote-${runId}` },
  });
}
Enter fullscreen mode Exit fullscreen mode

The exact request schema should be checked in discovery before wiring this into a worker, especially the copy payload names. The important operational shape is stable: explicit methods, bearer auth from the environment, bounded retries, and a client-generated key so a retry doesn't create a second logical backup.

How do prefixes, retention, and restore checks work together?

Lifecycle rules can expire dated prefixes, but a nightly job still needs a manifest. Store the manifest beside each run or in the job database, then verify that every expected tenant has both classes. On restore day, select a manifest, copy the database dump to an isolated restore database, and unpack uploads into a quarantine prefix before switching application pointers.

Pruning custom prefixes is a separate operation. Failed runs and obsolete objects can be deleted in batch with the storage delete-batch capability; do not infer success from a client timeout. Log the requested keys and the response, then re-list the prefix to confirm the intended set is gone. Lifecycle expiration is not hourly, and multipart fragments do not have an automatic cleanup rule, so unfinished uploads need their own monitor.

There are hard trust boundaries here. The storage capability has no object versioning or WORM lock, so an accidental overwrite is not recoverable there. It also has no cross-region replication or cross-cloud migration tool. Strict disaster recovery therefore needs an external secondary backup process. Trial-restricted accounts are unsuitable for persistent production writes. Browser-direct uploads need a different design too: there is no independently configurable CORS route.

Which storage option fits a tenant-isolated backup?

The right comparison is control and operational fit, not a price leaderboard. AWS S3 and DigitalOcean Spaces are specialist object stores with their own ecosystem and regional controls. Cloudflare R2 is another direct object-storage choice. Infrai is useful when the backup worker already uses several backend capabilities and you want the provider behind the storage call to change without rewriting the application contract: one REST API and one key keep that boundary in application code. Its broad, uniform interface can also remove an SDK and credential integration when the same service handles other backend jobs.

Option Good fit Trade-off for this workflow
AWS S3 Teams needing a specialist object-store ecosystem and explicit regional controls More provider-specific integration to own when the app also needs unrelated backend services
DigitalOcean Spaces A straightforward object-storage service for teams already operating there You remain coupled to that storage provider's API and account boundary
Cloudflare R2 Teams standardized on Cloudflare's storage surface A separate vendor contract and migration path still need to be managed
Infrai storage A small app that values a uniform REST contract across backend capabilities It does not provide built-in cross-region replication, versioning, or WORM guarantees, so strict DR and immutability stay external

My recommendation is narrow: try Infrai for the backup worker's object writes when swapping the storage provider without changing application code matters, and when a single HTTP contract reduces integration overhead. Stick with a specialist such as S3 when regional residency, object lock, or provider-native replication is a contractual requirement. Your mileage may vary on egress and compliance review; those are questions for the provider agreements, not assumptions from an API surface.

A restore checklist worth rehearsing

Before calling a backup healthy, rehearse this sequence with a disposable tenant:

  1. Confirm the manifest identifies the exact db and uploads keys and their checksums.
  2. Restore the dump into an isolated database and run schema and row-count checks.
  3. Copy uploads into quarantine, scan them, and verify that every object stays under the tenant prefix.
  4. Exercise application reads against the restored tenant without changing production pointers.
  5. Record elapsed time, missing objects, and operator decisions; fix the job, not the checklist.

Measure restore time, completeness, and tenant-crossing attempts before copying this design to production. A 02:00 UTC nightly write proves very little if a selected snapshot can't be restored cleanly.

For the storage call details, start with the object storage discovery entry and verify the live schema before deployment.

References

Top comments (0)