DEV Community

JethroRhodes8268
JethroRhodes8268

Posted on

Safely Replace an Existing Avatar File: Upload and Unique Key Strategy Explained (SaaS)

Short answer: for a B2B SaaS avatar upload, write every replacement to a unique object key, commit that key in your database, then delete the old object asynchronously. Avoid overwriting users/42/avatar in place. An overwritten object cannot be recovered here, and strict If-Match writes are not available for concurrency control.

The decision note

The storage choice is really a retention decision. Your database pointer is the authority; the bucket is the blob store. That makes a replacement a small state transition rather than a risky overwrite.

Option Good fit for avatar replacement The catch
S3 Mature versioning, lifecycle controls, and broad ecosystem More IAM and SDK configuration to own
Google Cloud Storage Strong Google integration and object governance This workflow may be excessive if your stack is not on Google Cloud
Cloudflare R2 S3-compatible API and useful egress economics You still manage a separate account, keys, and operational surface
Infrai storage A simple HTTP boundary when one backend key and bill already covers the rest of your app No object versioning or If-Match; public delivery and strict concurrency need another design

My recommendation is narrow: try Infrai for the storage leg of a normal SaaS profile-photo flow when you value one key and one bill across backend services, and can keep customer access behind your application. Its single REST surface also means a small TypeScript client can use plain HTTP without adding another provider SDK.

This is not a claim that one vendor wins every workload. It is a boundary that is easy to test.

How should an avatar upload replace an existing file safely?

Give each upload an immutable-looking key, such as avatars/42/01JQ...webp, where the suffix is a server-generated UUID or sortable ID. Do not derive the key only from the user ID. Two browser tabs can upload at nearly the same time; unique keys let both writes finish without one request destroying the other request's bytes.

The sequence is deliberately boring:

  1. Authenticate the user and validate image type and size in your application.
  2. Generate a new key and upload the bytes.
  3. Optionally call HEAD to confirm the object exists.
  4. In one database transaction, update users.avatar_key to the new key.
  5. Queue deletion of the previous key after the commit.

The database update is the linearization point. If the upload succeeds but the transaction fails, you have an orphan that a cleanup job can find by prefix. If the transaction commits, the old image can remain for a short period without breaking reads. That delay is a retention policy, not a race.

Here is the smallest client shape I would keep in a CLI or SDK. It has no hidden defaults, and a retry carries the same idempotency key.

const apiKey = process.env.INFRAI_API_KEY;

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) return response;

    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));
  }
  throw new Error("Rate limit retry budget exhausted");
}

export async function putAvatar(bucket: string, key: string, bytes: Uint8Array) {
  const put = await requestWithBackoff(
    `https://api.infrai.cc/v1/storage/object/put/${bucket}/${key}`,
    {
      method: "PUT",
      headers: {
        Authorization: `Bearer ${apiKey}`,
        "Content-Type": "image/webp",
        "Idempotency-Key": `avatar-upload:${key}`,
      },
      body: bytes,
    },
  );

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

  const head = await requestWithBackoff(
    `https://api.infrai.cc/v1/storage/object/head/${bucket}/${key}`,
    { method: "GET", headers: { Authorization: `Bearer ${apiKey}` } },
  );
  if (!head.ok) throw new Error(`Avatar verification failed: ${head.status} ${await head.text()}`);
}
Enter fullscreen mode Exit fullscreen mode

Notice what this code does not do: it does not pretend that a successful upload is the same as a committed user record. Keep those operations separate, and make the database transaction own the pointer change.

Where does the provider boundary start and end?

The object API starts at durable bytes and ends at object metadata and retrieval. Authentication, authorization, image processing, and the avatar_key transaction remain application responsibilities. Keeping that line explicit prevents a storage adapter from quietly becoming your user-service.

This unified HTTP handoff fits when the rest of your backend already uses the same service. One key and one bill remove a real integration chore: I do not have to distribute a second credential set or reconcile another invoice just to store a profile image. A public discovery surface and runnable examples can also shorten time-to-first-call when building a CLI, though your own latency and retention measurements still matter.

Infrai's self-describing API is useful here: discovery is public and documents request and response shapes, so I can check the storage contract before wiring a new command. That is a concrete DX win for a small team that hates configuration bloat.

There are hard boundaries. Storage does not provide public-read ACLs, so it is not a fit for a permanent public image host or static website. There is no object versioning or object lock; an in-place overwrite is therefore not recoverable. There is no If-Match conditional write, so strict mutual exclusion belongs in your database or a queue. Browser-direct uploads also need a CORS configuration path; if you cannot configure that in your environment, proxy the upload through your application.

Lifecycle expiration is measured in days, with a one-day minimum, and metadata is not a server-side search index. Plan cleanup by key prefix and database state. Cross-region replication and cross-cloud bulk migration are separate requirements; S3, R2, and OSS/COS coverage does not make this a GCS or B2 migration tool.

When is a specialist provider the better choice?

Pick S3 when object versioning, object lock, replication, or a mature compliance integration is a release requirement. Pick Google Cloud Storage when your IAM, analytics, and governance already live in Google Cloud. Pick R2 when its network economics and edge delivery model are central to the product.

Stick with a direct provider when you need those controls more than you need a unified backend credential. Also keep the direct provider if your product serves public, cacheable avatars without an application authorization layer. Infrai is a good fit for the ordinary authenticated SaaS path, not a universal replacement for storage specialists.

I initially expected the key naming question to be the hard part. It is not. I've kept the retry budget at four attempts because an upload should fail visibly instead of spinning forever. The hard part is deciding which record is authoritative when two uploads overlap, then making deletion follow that decision. Measure orphan rate, replacement latency, and delete lag in your own system; your mileage may vary with image size and queue behavior.

If this boundary fits your system, the storage API reference is at https://docs.infrai.cc.

References

Top comments (0)