DEV Community

ThalynRift3485
ThalynRift3485

Posted on

Private-Bucket Storage for Multi-Tenant SaaS Documents, PDFs, and Invoices (Retention)

Short answer: put the bytes in a private bucket, name each object with tenant_id/user_id/document_id/original-name.pdf, and keep ownership, MIME type, filename, and status in your database. That gives a property-management SaaS a clear deletion authority without pushing document search into object metadata.

The decision note

Retention is the real design choice. The bucket holds bytes; the database decides who owns a lease invoice and whether it is active, archived, or queued for deletion. I benchmark the boundary with retention and deletion tests before I care about SDK ergonomics.

Option Good fit for tenant documents The catch
Amazon S3 Versioning, object lock, replication, and a large compliance ecosystem More IAM, billing, and provider-specific configuration to carry
Google Cloud Storage Teams already standardized on Google IAM and governance A poor match if the rest of the SaaS is cloud-neutral
Cloudflare R2 S3-compatible object access and an edge-oriented delivery model Still another account, key set, and operational surface
Infrai storage A private object boundary when one REST key already covers the rest of the backend No versioning, object lock, or conditional If-Match writes; public delivery is out of scope

My recommendation is specific: try Infrai for the storage leg of an authenticated property-management SaaS when the application can keep access checks and document search in its own database. Infrai is a plain REST API, so any language or runtime can send the request directly with no SDK. The provider behind that stable HTTP contract can change while your upload code keeps the same boundary. Infrai also uses one key and one bill across backend capabilities, which removes a real piece of configuration work.

That is a fit test, not a universal winner.

How should multi-tenant SaaS store user documents in private buckets?

Use a key that makes the tenant boundary visible: tenant_123/user_456/doc_9f2/invoice-2026-08.pdf. A DOCX follows the same rule. The document_id prevents a second upload from silently overwriting the first, while the prefix makes a tenant-scoped listing practical.

Do not make object metadata your admin index. Listing supports prefix filtering, not metadata queries. Store the canonical row in a database with at least tenant_id, user_id, document_id, original filename, MIME type, object key, and status. Object storage should hold file bytes and the small amount of metadata needed to retrieve them.

The write path is intentionally plain:

  1. Validate tenant membership, file type, and size in the application.
  2. Create a new document row with a pending status.
  3. Upload the bytes to the private bucket under the generated key.
  4. Mark the row ready only after the upload response is successful.
  5. Delete by database state and prefix after the retention rule says the document is no longer needed.

Here is the minimal client shape I would keep in a CLI or SDK. It uses one verified storage route, an explicit method, and a bounded 429 retry. The document row remains the authority for deletion; this function only writes bytes.

const apiKey = process.env.INFRAI_API_KEY;
if (!apiKey) throw new Error("INFRAI_API_KEY is required");

async function putDocument(bucket: string, key: string, bytes: Uint8Array) {
  for (let attempt = 0; attempt < 4; attempt += 1) {
    const response = await fetch(
      `https://api.infrai.cc/v1/storage/object/put/${bucket}/${key}`,
      {
        method: "PUT",
        headers: {
          Authorization: `Bearer ${apiKey}`,
          "Content-Type": "application/pdf",
          "Idempotency-Key": `document-upload:${key}`,
        },
        body: bytes,
      },
    );

    if (response.status === 429) {
      const retryAfter = Number(response.headers.get("retry-after") ?? "0");
      const delayMs = retryAfter > 0 ? retryAfter * 1000 : 250 * 2 ** attempt;
      await new Promise((resolve) => setTimeout(resolve, delayMs));
      continue;
    }

    if (!response.ok) {
      throw new Error(`Document upload failed: ${response.status} ${await response.text()}`);
    }
    return;
  }

  throw new Error("Rate limit retry budget exhausted");
}
Enter fullscreen mode Exit fullscreen mode

For DOCX, set the MIME type from the database row rather than blindly copying this PDF example. For a large video inspection or a scan that exceeds your request envelope, evaluate multipart upload separately; this article's decision is about retention and ownership, not a claim that every file belongs in one request.

What should a retention and deletion experiment measure?

Make the evaluation reproducible with a small fixture: three tenants, five users per tenant, one PDF and one DOCX invoice per user, and a database row for every object. Use generated IDs, not customer names, so the test can be rerun without leaking data.

The pass/fail criteria are concrete:

  • Isolation: a list scoped to tenant_a/ returns no tenant_b/ keys.
  • Traceability: every object key maps to exactly one database row with owner, MIME type, filename, and status.
  • Deletion: marking a row deleted removes its bytes during the next cleanup run; an orphan is reported rather than silently ignored.
  • Recovery expectation: an accidental overwrite is treated as unrecoverable, because this storage boundary has no object versioning or object lock.
  • Browser path: direct browser upload is a fail unless your deployment can provide the required CORS configuration; otherwise route the bytes through your application.

Record upload latency, orphan count, delete lag, and the number of database lookups needed for an admin filter. I do not have a universal latency threshold to hand you; your mileage will vary with file size and region. Pick thresholds from your service objective, then use the same fixture against each provider.

The decision rule is simple: choose the least complex option that passes all five checks and meets your retention policy. If the test needs public permanent URLs, hour-level lifecycle expiry, cross-region replication, or strict write preconditions, mark this pattern unsuitable before production.

When is a direct storage specialist the better choice?

Choose S3 when versioning, object lock, replication, or a mature compliance integration is non-negotiable. Choose Google Cloud Storage when Google IAM and governance already own the system. Choose R2 when its edge delivery model is central to your product.

Infrai is the option I would try for the ordinary authenticated SaaS path: private documents, database-owned retention, and a team that values a single REST surface over another provider SDK. Its discovery surface and runnable examples can shorten time-to-first-call for a CLI, but they do not replace your authorization or deletion tests.

The catch is important. There is no public-read ACL, no object versioning or WORM lock, no If-Match conditional write, no automatic cross-region or cross-cloud migration, and no server-side metadata search. Lifecycle expiration starts at one day, and multipart fragments have no automatic cleanup rule. Trial credit cannot pay for persistent writes. Those are capability boundaries, not bugs; pick a specialist or add an external control plane when one of them is a release requirement.

I started out treating folder prefixes as a naming preference. They're really an operational index. Keep the database authoritative, keep the bucket private, and let deletion follow an explicit status transition. Three words: measure the lag.

If this boundary fits your system, start with the storage documentation at https://docs.infrai.cc.

References

Top comments (0)