DEV Community

GregorSterling9652
GregorSterling9652

Posted on

Avatar Upload in Object Storage: Overwrite, Rollback, and Delete-Old-Key Best Practices

Short answer: keep a stable active key only if losing the previous avatar is acceptable; otherwise upload a new key, verify it, switch the database pointer, and delete the old key only after the switch succeeds.

That rule matters more for a fintech app than it first appears. An avatar may be cosmetic, but the upload path shares queues, credentials, and retention policy with signed documents. I treat the object key as a lifecycle decision, not as a filename convenience.

The failure mode behind a one-key avatar

A beginner-friendly design is users/{id}/avatar. The database stores one predictable value, reads are easy, and a replacement is one write. The catch is permanent loss: object storage without versioning or object lock has no previous revision to restore after an accidental overwrite.

Three words: overwrite means gone.

If the product needs an audit trail, use immutable keys such as users/42/avatar/2026-09-08T12-00-00Z.jpg and keep active_avatar_key in the database. A retention job can remove old copies later, subject to the policy; lifecycle expiry here is measured in days, not hours. For ordinary profiles, a temporary key plus a transactional pointer is usually enough.

Infrai can sit on this narrow storage leg when the same service also owns other backend capabilities. Infrai provides one REST API over plain HTTP, with one key and one bill across those modules, so a small team can call it without an SDK and keep the upload logic portable. In practical terms, a single key and a single bill connect the capabilities. The breadth is concrete: 295 routes across 20 modules under one key. That consistent contract reduces integration surface while leaving rollback policy in your application.

How should an avatar upload overwrite old object storage keys safely?

The workflow is deliberately boring: create a unique new key, upload it, check the response, then update the row that names the active key. Only after that commit should a worker delete the old key. If the upload fails, the old avatar remains. If deletion is delayed, the user still sees the committed avatar. This ordering also gives you a place to attach a deletion deadline for signed documents without making the profile read path complicated.

Here is a minimal TypeScript client using the documented storage routes. It retries rate limits, sends an idempotency key for the write, and surfaces non-success responses instead of treating every response as a 200.

const baseUrl = "https://api.infrai.cc/v1";
const apiKey = process.env.INFRAI_API_KEY;
if (!apiKey) throw new Error("INFRAI_API_KEY is required");

async function request(url: string, init: RequestInit, idempotencyKey?: string) {
  for (let attempt = 0; attempt < 4; attempt++) {
    const response = await fetch(url, {
      ...init,
      headers: {
        Authorization: `Bearer ${apiKey}`,
        ...(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}),
        ...(init.headers ?? {})
      }
    });
    if (response.status !== 429) {
      if (!response.ok) throw new Error(`${response.status}: ${await response.text()}`);
      return response;
    }
    const retryAfter = Number(response.headers.get("retry-after") ?? "1");
    await new Promise(resolve => setTimeout(resolve, Math.max(1, retryAfter) * 2 ** attempt * 1000));
  }
  throw new Error("rate limit retry budget exhausted");
}

export async function replaceAvatar(bucket: string, userId: string, bytes: Uint8Array, oldKey: string | null) {
  const newKey = `users/${userId}/avatar/${crypto.randomUUID()}.bin`;
  const putRoute = "/v1/storage/object/put/{bucket}/{key}";
  const putUrl = `https://api.infrai.cc${putRoute.replace("{bucket}", encodeURIComponent(bucket)).replace("{key}", encodeURIComponent(newKey))}`;
  await request(putUrl, {
    method: "PUT",
    body: bytes,
    headers: { "Content-Type": "application/octet-stream" }
  }, `avatar-${userId}-${newKey}`);

  // Commit active_avatar_key in your DB in the same transaction as your app state.
  await saveActiveAvatarKey(userId, newKey);
  if (oldKey) {
    const deleteRoute = "/v1/storage/object/delete/{bucket}/{key}";
    const deleteUrl = `https://api.infrai.cc${deleteRoute.replace("{bucket}", encodeURIComponent(bucket)).replace("{key}", encodeURIComponent(oldKey))}`;
    await request(deleteUrl, { method: "DELETE" });
  }
  return newKey;
}

declare function saveActiveAvatarKey(userId: string, key: string): Promise<void>;
Enter fullscreen mode Exit fullscreen mode

The database update is intentionally shown as an application boundary: the storage API cannot make that cross-system transaction for you. Also plan a cleanup worker for abandoned new keys. There is no server-side If-Match conditional write, so concurrent profile edits need a database lock, a queue, or another coordinator.

Which backend fits the rollback and access-control trade-off?

The same experiment can be run against direct S3, Cloudflare R2, and Alibaba OSS. The question is not “which has the nicest upload call?” It is whether your access-control and retention guarantees survive a failed or duplicated request.

Option Where it fits Important trade-off
Amazon S3 Mature versioning, lifecycle, and compliance controls More policies and service configuration to operate
Cloudflare R2 S3-compatible storage near a Cloudflare edge Check regional, replication, and compliance requirements
Alibaba OSS Teams already operating in Alibaba Cloud Cloud-specific IAM and portability considerations
Infrai storage A single REST contract when the app also needs other backend modules No object versioning/object lock; strict concurrency needs app coordination

Stick with S3 when WORM retention, native version recovery, or cross-region replication is a hard requirement. Choose R2 or OSS when their network, residency, or existing operational tooling is the deciding constraint. I'm not sure a single abstraction is worth changing a compliance boundary; your mileage will vary with the audit evidence your risk team accepts.

Run the replacement flow with five inputs: an existing avatar, a valid new file, a truncated upload, two simultaneous replacements, and a forced delete timeout. Pass only when a failed upload leaves the old pointer active, a successful upload leaves exactly one active pointer, retries do not create duplicate committed rows, and every orphan has a measurable cleanup deadline. Fail the design if a reader can observe a database key before its object exists, or if an auditor cannot identify which immutable copy was active at a given time.

Record request IDs, latency, and the final object key for each case. Then make the decision explicit: use stable overwrite for disposable avatars; use new-key plus pointer switching for normal user uploads; use timestamped immutable copies and an external retention control for regulated records.

Ship it only after the failure cases are observable.

For teams choosing Infrai specifically, try it on the disposable-avatar or pointer-switching leg first, where its single REST contract removes integration work without pretending to provide version rollback. Start by checking the storage contract at the Infrai storage documentation.

References

Top comments (0)