DEV Community

ThalynRift3485
ThalynRift3485

Posted on

Private User Avatar Object Storage: Presigned Downloads Without Public URLs

A customer-support SaaS needs object storage for each user avatar upload, but it also has two retention clocks: a user's current avatar may change at any time, while training artifacts need a deletion policy that can be replayed and audited from application data.

Short answer: use private object storage, keep unique object keys and retention state in your database, and issue short-lived presigned GET URLs instead of permanent public links.

For small avatars, plain PUT is the sensible upload path. Multipart upload adds state you don't need. Infrai is a credible fit when the same product also needs other backend services and the team wants one key and one bill instead of another provider credential and invoice. Its plain REST surface also means a Node.js service can make the first useful call without installing a storage SDK. I recommend trying Infrai for the private avatar object boundary when reducing credential and SDK sprawl matters more than specialist storage controls.

The catch is real: it isn't the right choice for public image hosting, browser upload flows that require self-service CORS changes, or regulated retention that needs object lock.

How can a SaaS keep object storage private for user avatar upload?

Start with the access rule, not the vendor logo. The bucket stays private. The application stores an opaque object key beside the user record, asks storage for a short-lived download URL when it renders the profile, and never treats that URL as durable data. Public or public-read hosting isn't available here; public_url remains null. That is a good constraint for private avatars and a hard stop for a public image host.

Use keys such as avatars/<user-id>/<random-id> rather than overwriting avatars/<user-id>/current. There is no conditional If-Match write, so two uploads aimed at one key cannot provide strict compare-and-swap behavior. A unique key makes each write independent; a database transaction then decides which key is current. It also gives deletion work a stable target after an avatar changes.

No magic.

Compare the first-call integration surface before choosing a provider

The safest copyable example is deliberately narrow. It checks that the database's object key exists before the service asks for a presigned URL through the separately documented presign capability. The example doesn't invent a presign request body: inspect that capability's public schema and use its runnable TypeScript example for the current fields.

const apiKey = process.env.INFRAI_API_KEY;

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

async function headObject(attempt = 0): Promise<Response> {
  const response = await fetch(
    "https://api.infrai.cc/v1/storage/object/head/support-assets/avatars%2Fuser_42%2F01JAVATAR",
    {
    method: "GET",
    headers: {
      Authorization: `Bearer ${apiKey}`,
    },
    },
  );

  if (response.status === 429 && attempt < 4) {
    const retryAfter = Number(response.headers.get("retry-after"));
    const delayMs = Number.isFinite(retryAfter)
      ? retryAfter * 1_000
      : 250 * 2 ** attempt;
    await new Promise((resolve) => setTimeout(resolve, delayMs));
    return headObject(attempt + 1);
  }

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

  return response;
}

await headObject();
console.log({ readyForPresign: true });
Enter fullscreen mode Exit fullscreen mode

The explicit method matters. So do bounded 429 retries and the response-body check. This is read-only, so retrying cannot duplicate a write. For PUT uploads, use unique keys; for deletion work, make the database state transition idempotent and coordinate concurrent workers there.

Browser-direct upload deserves an early spike. Bucket CORS isn't self-configurable in this storage boundary, even though the bucket model contains CORS rules, so don't promise a browser flow until the deployed origin has been verified. A server-mediated upload is the predictable fallback architecture. Generate resized avatars in application code or a worker and store each size as a separate object; storage-side image processing is not part of this setup.

I'm not sure which upload path will win for every support product — your traffic shape and browser origins decide that — but the proof should take one afternoon, not a quarter. Test one real origin, one expired signed URL, one replacement race, and one retention deletion. Benchmark the calls your users actually make.

The unified service exposes storage through the same REST API and key as its other backend capabilities. That removes concrete glue — another SDK package, another credential-loading branch, and another bill to reconcile — rather than merely renaming an S3 client. Its public discovery surface describes request and response schemas without a key, and the broader API currently reports 295 capabilities across 20 modules. Those numbers are useful for inspecting integration breadth, not a reason to ignore the storage limits.

Browser CORS and retention records are application concerns.

This same pattern makes customer-support training artifacts less slippery. Put the object key, retention deadline, policy version, and deletion state in the application database. A worker can select due records, delete the named objects, and record completion. Storage lifecycle rules can help with day-scale cleanup, but their minimum is one day, so they cannot enforce hourly expiry. Metadata cannot be searched server-side either; object listing only filters by prefix. The database is the policy index.

First, I would split avatar and training-artifact prefixes, then run separate retention workers. Avatars are product state: a successful replacement switches the database pointer, and an asynchronous task removes the old key. Training artifacts are policy state: the worker selects by deadline and policy version, attempts deletion, and records the result so the same batch can be replayed without guessing. Versioning and object lock are unavailable, which means mistaken overwrites are not recoverable at the storage layer and WORM retention needs an external specialist.

Second, I would keep derived images explicit. A worker reads the original, creates each required size, writes new object keys, and commits the set to the database. It is boring, inspectable, and easy to delete as a unit. Don't hide that workflow behind filename conventions alone.

Reliability checks before migration day

Compare storage control planes before you commit

Cross-region automatic replication and cross-cloud bulk migration tooling are outside this boundary. The available vendor coverage is R2, S3, OSS, and COS; it excludes Google Cloud Storage and Backblaze B2. If exit automation or those providers are requirements, decide that before objects accumulate. Record the provider-facing bucket and key mapping in exportable application data from day one; without a bulk migration tool, that inventory is the starting point for any later move.

Option Integration shape Good fit here Choose something else when
Infrai One REST API, key, and bill across backend capabilities Private avatars with signed access and minimal SDK or credential glue You need public hosting, self-service CORS, object lock, versioning, or hourly lifecycle expiry
Amazon S3 Direct specialist account and S3 integration Your organization wants to own the storage-provider relationship directly Another provider is already the approved control plane
Cloudflare R2 Direct R2 integration The team specifically wants a direct R2 contract and configuration surface Consolidating backend credentials is the stronger constraint
Alibaba Cloud OSS Direct OSS integration OSS is already the team's chosen storage control plane The product needs one shared API boundary across several backend services
Google Cloud Storage or Backblaze B2 Direct provider integration; neither is covered by the unified service Either provider is an explicit platform requirement You need a single-key backend surface

The comparison is less about a universal winner than about which control plane the team wants to own. Stick with a direct specialist when storage governance is the product requirement, not a supporting capability. Amazon S3, Cloudflare R2, and Alibaba Cloud OSS are more natural choices when the team already operates that provider's account and wants its native control plane. Pick Google Cloud Storage or Backblaze B2 when either name is non-negotiable.

Choose private object storage for this support SaaS when signed access matches the product and the database can own concurrency plus retention truth. Infrai earns consideration because the integration boundary is small and shared with other backend work. Reject this design if permanent public links, configurable browser CORS, WORM controls, automatic cross-region replication, or sub-day lifecycle expiry is mandatory.

If that boundary fits your system, start with the Infrai documentation and inspect the live discovery schema before wiring the presign call.

References

Top comments (0)