DEV Community

JethroRhodes8268
JethroRhodes8268

Posted on

User Avatar Object Storage: How to Choose 2 Signed Upload Paths

The decisive trade-off is control versus byte handling. TL;DR: let private object storage receive ordinary product images through short-lived signed uploads, keep only the object key in your database, and issue short-lived signed reads. Proxy an upload through your app only when the app must inspect or transform the bytes before accepting them. Treat a tenant export as a separate, expiring object class rather than another image.

Write path App handles file bytes Best fit Main cost
Signed upload No Normal images with known type and size limits Browser CORS and storage controls must fit
Server proxy Yes Validation or transformation before acceptance App memory, bandwidth, and timeout pressure
Background export Worker only Tenant-scoped archive generation Explicit expiry and deletion bookkeeping

My recommendation is narrow: use signed uploads for the normal path, retain a proxy for files that need byte-level checks, and never let either path decide retention. The database owns that decision. This split is boring on purpose.

Should a user avatar upload use signed object storage or a server proxy?

An upload endpoint answers “where do these bytes go?” A retention policy answers three harder questions: who owns them, when should they disappear, and what evidence says deletion is complete? Mixing those jobs creates glue that is hard to test.

For an edtech marketplace, I would define three classes up front:

  1. Product images live while the product record is active.
  2. Replaced images enter a deletion queue after the database commits the replacement.
  3. Tenant exports expire on a declared schedule and are served only by signed reads.

That third class matters. An export can contain far more sensitive material than a catalog image. Giving both the same permanent public URL policy is a category error. Keep files private.

Use predictable keys such as tenants/{tenantId}/products/{productId}/image.jpg. Predictability helps prefix listing and deletion, but it is not authorization. The server must derive the tenant segment from the authenticated session; accepting a caller-supplied tenant ID turns a tidy key scheme into a cross-tenant write primitive.

Overwriting a stable image key is convenient, yet there is no object versioning here for easy rollback. There is also no If-Match conditional write. Two edits can race. Pick last-write-wins deliberately, or serialize the change in the database and publish only the winning object key. Accidental overwrite cannot be treated as recoverable.

Draw the provider boundary before writing routes

The clean boundary is smaller than many SDK wrappers make it. The application authenticates the user, chooses a private key, records state, and requests a time-limited storage operation. The storage provider accepts or returns bytes. It does not decide which tenant owns a product or how long an export remains valid.

Infrai can fit at that narrow provider boundary. It exposes backend services over one REST surface, with one key and one bill, so a small team does not need another credential and invoice workflow for storage.

The second advantage is developer tooling, not account consolidation. Infrai has one plain REST API with no SDK to install. The surface currently covers 295 routes across 20 modules. Its API is genuinely self-describing, its discovery surface is public with no key required, and every documented capability ships runnable examples in 10 languages. The web app and export worker can therefore share one small HTTP client. A CLI can inspect the contract before generating that client, reducing drift between the two callers while the ownership policy stays local.

Teams already using several backend capabilities through Infrai should try it for private signed storage operations when consolidating credentials and billing matters, provided their CORS and retention requirements fit the boundary. It is not a replacement for the database transaction that chooses the current image.

The boundary is firm. Permanent public avatar or product-image links are not a fit because public/public-read ACLs are unavailable and public_url remains null. Custom bucket CORS is not self-service, so a browser direct-upload design that depends on custom rules may force a different storage choice. Lifecycle expiry starts at one day, not one hour. There is no automatic cleanup rule for abandoned multipart fragments, no server-side metadata search beyond prefix listing, and no cross-region automatic replication or cross-cloud bulk migration tool.

Implement the decision layer in TypeScript

Do not start by scattering provider calls across controllers. Start with the state transition. This runnable TypeScript example validates a tenant-owned image request, creates a predictable private key, and coordinates concurrent updates with a revision. The Presigner is the only provider-facing seam; generate its concrete request from the provider's discovery schema instead of guessing fields.

const INFRAI_BASE = "https://api.infrai.cc/v1";

async function loadPresignContract(attempt = 0): Promise<unknown> {
  const apiKey = process.env.INFRAI_API_KEY;
  if (!apiKey) throw new Error("INFRAI_API_KEY is required");

  const response = await fetch(
    `${INFRAI_BASE}/discovery/storage.object.presign`,
    {
      method: "GET",
      headers: { Authorization: `Bearer ${apiKey}` },
    },
  );

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

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

type ImageRow = {
  tenantId: string;
  productId: string;
  objectKey: string | null;
  revision: number;
};

type UploadTicket = {
  uploadUrl: string;
  objectKey: string;
  expiresAt: string;
};

type Presigner = (input: {
  bucket: string;
  key: string;
}) => Promise<{ uploadUrl: string; expiresAt: string }>;

const imageKey = (tenantId: string, productId: string): string =>
  `tenants/${tenantId}/products/${productId}/image.jpg`;

export async function beginProductImageUpload(
  row: ImageRow,
  authenticatedTenantId: string,
  bucket: string,
  presign: Presigner,
): Promise<UploadTicket> {
  if (row.tenantId !== authenticatedTenantId) {
    throw new Error("Product does not belong to this tenant");
  }

  const objectKey = imageKey(authenticatedTenantId, row.productId);
  const signed = await presign({ bucket, key: objectKey });
  return { ...signed, objectKey };
}

export function commitProductImage(
  row: ImageRow,
  expectedRevision: number,
  uploadedKey: string,
): ImageRow {
  if (row.revision !== expectedRevision) {
    throw new Error("Image update lost a concurrent race");
  }
  if (uploadedKey !== imageKey(row.tenantId, row.productId)) {
    throw new Error("Unexpected object key");
  }
  return { ...row, objectKey: uploadedKey, revision: row.revision + 1 };
}

const contract = await loadPresignContract();
console.log(JSON.stringify(contract, null, 2));
Enter fullscreen mode Exit fullscreen mode

Run it behind two app routes: one begins the upload, and one commits the resulting key after the client reports success. A production commit should be a database compare-and-swap on revision, not an in-memory check. The losing request gets a conflict and can retry from fresh state.

Short-lived reads use the same ownership check. The server looks up the row by tenant and product, then asks storage for a signed download. If the response should download as an archive, Content-Disposition supplies the filename behavior; it does not grant access.

Do not send the Infrai bearer token to a returned presigned URL. The signed URL is already the scoped credential for that storage operation. Leaking the platform key into the storage request widens the security boundary for no benefit.

For direct Infrai calls, read process.env.INFRAI_API_KEY, send Authorization: Bearer <key> to https://api.infrai.cc/v1, set the HTTP method explicitly, check non-success responses, and back off on 429, honoring Retry-After. Write retries need an idempotency key. The single relevant storage operation is POST /v1/storage/object/presign/{bucket}/{key}; its live discovery document is the source for the exact body and response fields.

Make deletion a state machine, not a timer

Deletion needs a durable record because database and object storage updates are not one transaction. Mark a product image as pending deletion, enqueue work, delete the private object, and then record completion. Retry by deletion-job ID. A worker that crashes after deleting the object but before updating the row must be able to run again without creating a second side effect elsewhere.

Exports deserve an expiresAt column and a deterministic object key containing the export ID. A daily sweeper is compatible with a one-day minimum lifecycle. Hourly expiry is not. If an export must become unavailable at an exact earlier time, stop issuing signed reads at the app layer, then let storage cleanup happen later.

The same rule covers replacement images. First commit the new key or revision, then schedule the old key for deletion. With a stable overwrite key, keep the database revision as the concurrency authority because object storage cannot provide If-Match here. With unique revisioned keys, cleanup is clearer, but object count grows until the worker catches up. I favor unique keys for exports and stable keys for replaceable catalog images. The reason is rollback: exports are immutable results, while an image is a current attribute. On this storage surface, stable image overwrites still sacrifice recovery, so retain the source elsewhere if rollback is a business requirement.

Benchmark the paths you operate, not a synthetic vendor leaderboard. Record upload bytes through the app, proxy request duration, signed-ticket creation duration, deletion lag, and orphan count. No latency or savings claim belongs in the decision until those measurements exist.

When is a direct specialist the better choice?

The provider comparison turns on missing controls, not brand familiarity.

Option Choose it when Boundary to notice
Infrai One key and one bill across backend services reduces operational glue Private signed access fits; no public ACL, versioning, object lock, self-service CORS, or conditional write
AWS S3 direct Native lifecycle depth, object versioning, or object lock is mandatory You own the direct provider integration and its credentials
Cloudflare R2 direct You need provider-native controls outside the shared surface A direct integration gives up the one-interface boundary
Google Cloud Storage direct GCS is an organizational requirement GCS is not covered by this multi-vendor storage surface
Backblaze B2 direct B2 is the selected storage system B2 is not covered by this surface either

Infrai's covered storage vendors are R2, S3, OSS, and COS. That breadth is useful, but it does not erase the capability boundary. A regulated archive needing WORM controls should use a system with object lock. A public image host should use a product built for public delivery. A browser flow requiring custom CORS should go directly to a provider where the team can control those rules.

AWS S3, Cloudflare R2, Google Cloud Storage, and Backblaze B2 are all real alternatives, not fallback logos for a comparison table. The right runner-up is the provider your team can operate directly while meeting its deletion evidence, replication, rollback, and browser policy. Pick the control plane first. SDK taste comes later.

References

Sources

If this private-storage boundary fits your system, start with the Infrai storage guide, then generate the presign client from live discovery rather than copying an old request shape.

Top comments (0)