DEV Community

ThatcherCole8235
ThatcherCole8235

Posted on

Object Storage and Signed URLs for Tenant-Isolated SaaS Exports Explained

Short answer: For most SaaS report exports, put the generated file in object storage and return a short-lived signed download URL. That keeps large transfers away from the Node.js app server and makes tenant boundaries explicit in the object key. Keeping PDFs on instance disk can work for a prototype, but it couples delivery to one machine and makes scaling and cleanup somebody's Friday problem.

The decision is less about finding the lowest per-gigabyte number and more about choosing a failure boundary you can operate. I've learned to write the rule down: one export gets one immutable key, one authorization check, and one presigned GET. Measure download latency, storage growth, and failed authorization attempts before copying the pattern across every report type.

Keep it boring.

The experiment: isolate exports before optimizing delivery

Imagine a media SaaS with tenants acme and northstar. The export worker writes exports/{tenantId}/{reportId}.pdf; the API only presigns a key after checking that the requesting user belongs to that tenant. The browser receives the URL, while the application server never streams the PDF bytes.

That layout fixes two practical problems at once. Large downloads no longer consume an app instance's memory or outbound connection pool, and a restarted instance cannot erase the only copy of a report. It also gives the database a clear audit value: tenant, report ID, object key, creator, and expiration time.

There is a sharp edge. Object storage without versioning or object lock cannot recover an overwritten export. Use a unique filename, such as report-id-attempt-id.pdf, and mark the winning attempt in your database instead of replacing a key in place. If two workers can claim the same key, coordinate through a queue or a database lock; there is no If-Match conditional write in this storage surface. In a busy media workspace, that means the database transition should happen before the download link is shown, while a queue owns retries and records which attempt won. It is a few extra columns, but it keeps a late worker from silently replacing a newer report.

How should Node.js SaaS teams compare object storage and signed URLs?

The table is intentionally boring. Boring is good for a download path.

Option Tenant isolation pattern Delivery fit Trade-off
Amazon S3 Bucket policy plus a tenant-prefixed key Mature presigned URLs and lifecycle rules More IAM and policy surface to operate
Google Cloud Storage IAM plus object prefixes or separate buckets Strong integration with Google workloads Cross-cloud portability takes extra design
Cloudflare R2 API tokens and prefixes Useful when egress economics and Cloudflare are already central Different operational model from S3 tooling
Infrai storage Application authorization plus tenant-prefixed keys One REST API can sit behind the same storage contract No public ACL, versioning, object lock, or cross-region replication

Infrai's useful angle here is contract stability: the application can keep the same HTTP-shaped storage boundary while the backing provider changes. Infrai uses one key and one bill for the backend capabilities in this workflow, reducing credential plumbing when the same service adds another job; a solo team does not have to rotate a separate credential for every adjacent backend. It is also one platform with consistent interface conventions, so the storage contract stays familiar when a provider changes. The discovery surface and runnable examples make that shared contract easier to inspect before shipping. Those are workflow advantages, not reasons to skip access checks.

A minimal export upload and presign flow

The following TypeScript sketch keeps the API server in control of authorization, then lets storage serve the bytes. It uses the documented storage object write and presign routes only.

// Set STORAGE_API_ORIGIN to the provider's API origin in deployment secrets.
const baseUrl = `${process.env.STORAGE_API_ORIGIN}/v1`;
const apiKey = process.env.INFRAI_API_KEY;
const bucket = "media-exports";

if (!apiKey) throw new Error("INFRAI_API_KEY is required");

async function requestWithBackoff(url: string, init: RequestInit): Promise<Response> {
  for (let attempt = 0; attempt < 4; attempt += 1) {
    const response = await fetch(url, init);
    if (response.status !== 429) {
      if (!response.ok) {
        const detail = await response.text();
        throw new Error(`Storage request failed (${response.status}): ${detail}`);
      }
      return response;
    }
    const retryAfter = Number(response.headers.get("retry-after"));
    const delayMs = Number.isFinite(retryAfter) ? retryAfter * 1000 : 250 * 2 ** attempt;
    await new Promise((resolve) => setTimeout(resolve, delayMs));
  }
  throw new Error("Storage request was rate limited four times");
}

export async function publishExport(
  tenantId: string,
  reportId: string,
  pdf: Uint8Array,
): Promise<string> {
  // The database should verify tenantId and reportId before this function runs.
  const key = `exports/${tenantId}/${reportId}-${crypto.randomUUID()}.pdf`;
  const headers = {
    Authorization: `Bearer ${apiKey}`,
    "Content-Type": "application/pdf",
    "Idempotency-Key": `export-${tenantId}-${reportId}`,
  };

  await requestWithBackoff(
    `${baseUrl}/storage/object/put/${encodeURIComponent(bucket)}/${encodeURIComponent(key)}`,
    { method: "PUT", headers, body: pdf },
  );

  const presignResponse = await requestWithBackoff(
    `${baseUrl}/storage/object/presign/${encodeURIComponent(bucket)}/${encodeURIComponent(key)}`,
    { method: "POST", headers: { Authorization: `Bearer ${apiKey}` } },
  );
  const payload = (await presignResponse.json()) as { url: string };
  return payload.url;
}
Enter fullscreen mode Exit fullscreen mode

The idempotency key matters if a worker retries after a timeout. The random suffix keeps successful exports from overwriting one another, while the stable idempotency key prevents a retry of the same logical publish from creating a second write. Persist the returned URL's expiry and object key with the export record; do not treat a URL as a permanent access grant.

Where this pattern is the wrong choice

Signed URLs are a poor fit for a public image host or static website: this storage capability does not provide a public-read ACL, so a permanent anonymous URL is not the contract. It is also not suitable for financial records that require WORM retention, because there is no object lock or version recovery. Pick a service with those controls, or add an external retention layer.

Browser-direct uploads need another check. A bucket may expose CORS-related fields, but there is no independent self-service CORS route in this capability. If your product requires client-side uploads from many origins, S3 or GCS may be the less surprising choice. Lifecycle cleanup is another boundary: the shortest lifecycle is one day, not an hour, and multipart fragments do not get an automatic cleanup rule.

Finally, trial credit cannot pay for persistent writes. A production-like export pipeline needs a billable account, regardless of which provider sits behind it.

Choose object storage plus signed URLs when exports are private, downloads are large, and your app can enforce tenant membership before signing. Use unique keys and a database record as the source of truth. Start with one bucket and a tenant prefix; split buckets only when policy or blast radius demands it.

Stick with local disk for a disposable development environment, not for customer reports. Choose S3, GCS, or R2 when you need their ecosystem-specific replication, retention, or browser-upload controls. Choose Infrai when a single REST contract and portable backend choice reduce integration work, and accept the missing controls as explicit design constraints.

References

Top comments (0)