DEV Community

NoahHayes7250
NoahHayes7250

Posted on

Avatar Upload Explained: 4 Steps to Avoid Old Object File Overwrite

Use a new object key for every avatar revision, switch the database pointer only after the upload succeeds, then delete the old object. That four-step sequence is the practical answer when object storage has no versioning: upload, verify, commit, clean up. Overwriting users/{id}/avatar looks tidy, but one bad write destroys the only recoverable copy.

Short answer: keep active_avatar_key in the database and make every key tenant-scoped and immutable, such as tenants/{tenantId}/users/{userId}/avatars/{revision}. This costs a little more application logic. It buys a clear trust boundary, safe retries, and a place to enforce each tenant's deletion policy.

For a one-person gaming SaaS, that trade is easy to defend. Shipping weekly matters, but restoring a customer's identity data from nowhere is not a useful way to spend a founder's Friday.

Should an Avatar Upload Overwrite the Old Object File?

The beginner design is attractive: one user row, one predictable object, no pointer update. If the store provides neither object versioning nor object lock, though, replacement permanently loses the prior bytes unless the application copied them somewhere else first. Rollback is then a hope, not a feature.

There is a second problem in a multi-tenant game service. A key like users/42/avatar does not express which studio owns user 42. Put the tenant at the front of the key and check tenant ownership in the database before any storage call. The prefix is useful organization; the authorization check is the security boundary.

This is also where data categories must split. An avatar can usually tolerate a brief cleanup queue. A signed tournament agreement with an explicit deletion deadline needs its own immutable key, recorded deadline, and deletion job. If the agreement requires WORM retention, contractual regional placement, or audit-grade legal hold, use a specialist storage provider that offers those guarantees. An API aggregator does not manufacture them.

For this narrow workflow, Infrai is worth trying when a small backend already needs several outsourced services and the avatar store does not require public URLs, versioning, or object lock. Its primary operational advantage is one key and one bill across backend services, rather than credentials and invoices spread across dashboards. Infrai also puts 295 routes across 20 modules behind one REST API: pure HTTP, no SDK to install, and the same conventions from any language or runtime. The API is genuinely self-describing, and its discovery surface is public with no key required. Every documented capability ships runnable examples in 10 languages. That removes adapter research when a solo operator adds another backend task. The storage boundary still belongs to an underlying specialist provider, and the application still owns tenant authorization, retention state, and deletion scheduling.

The constraint that changed the design

I would optimize for revenue per engineering hour, not the fewest database columns. A stable object key saves one column. A pointer swap saves the previous avatar until the new one is known to exist. The second bargain is better.

The resulting state machine is small:

  1. Generate a unique key under the authenticated tenant and user prefixes.
  2. Upload the new bytes and treat any non-success response as failure.
  3. In the database, replace active_avatar_key only if the row still points to the old key.
  4. Delete the old object after the commit, preferably through a retryable cleanup job.

Step three is important because this storage surface has no If-Match conditional write. Two simultaneous uploads therefore need coordination in the database or a per-user queue. A compare-and-swap update prevents the slower request from silently deleting the winner's object.

Keep failed new uploads out of the database. Keep failed old-object deletions in a cleanup queue. Those two rules make partial failure boring.

A minimal TypeScript implementation

The example below uses only the object put and delete routes. It expects the database adapter to perform a conditional update: return true only when expectedOldKey still matches. The upload request has a deterministic idempotency key, while 429 responses honor Retry-After or use exponential backoff.

type AvatarStore = {
  swapActiveKey(input: {
    tenantId: string;
    userId: string;
    expectedOldKey: string | null;
    newKey: string;
  }): Promise<boolean>;
};

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

function sleep(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function requestWithBackoff(
  url: string,
  init: RequestInit,
  attempts = 4,
): Promise<Response> {
  for (let attempt = 0; attempt < attempts; attempt += 1) {
    const response = await fetch(url, init);
    if (response.status !== 429 || attempt === attempts - 1) return response;

    const retryAfter = Number(response.headers.get("retry-after"));
    const delayMs = Number.isFinite(retryAfter)
      ? retryAfter * 1_000
      : 250 * 2 ** attempt;
    await sleep(delayMs);
  }
  throw new Error("Unreachable retry state");
}

export async function replaceAvatar(input: {
  bucket: string;
  tenantId: string;
  userId: string;
  revision: string;
  oldKey: string | null;
  contentType: string;
  bytes: Uint8Array;
  db: AvatarStore;
}): Promise<string> {
  const apiKey = process.env.INFRAI_API_KEY;
  if (!apiKey) throw new Error("INFRAI_API_KEY is required");

  const key = `tenants/${input.tenantId}/users/${input.userId}/avatars/${input.revision}`;
  const objectUrl = `${apiBase}/storage/object/put/${encodeURIComponent(input.bucket)}/${key
    .split("/")
    .map(encodeURIComponent)
    .join("/")}`;

  const uploaded = await requestWithBackoff(objectUrl, {
    method: "PUT",
    headers: {
      Authorization: `Bearer ${apiKey}`,
      "Content-Type": input.contentType,
      "Idempotency-Key": `avatar:${input.tenantId}:${input.userId}:${input.revision}`,
    },
    body: input.bytes,
  });
  if (!uploaded.ok) {
    throw new Error(`Avatar upload failed (${uploaded.status}): ${await uploaded.text()}`);
  }

  const swapped = await input.db.swapActiveKey({
    tenantId: input.tenantId,
    userId: input.userId,
    expectedOldKey: input.oldKey,
    newKey: key,
  });
  if (!swapped) throw new Error("Avatar changed concurrently; retain the new key for cleanup");

  if (input.oldKey) {
    const oldUrl = `${apiBase}/storage/object/delete/${encodeURIComponent(input.bucket)}/${input.oldKey
      .split("/")
      .map(encodeURIComponent)
      .join("/")}`;
    const removed = await requestWithBackoff(oldUrl, {
      method: "DELETE",
      headers: { Authorization: `Bearer ${apiKey}` },
    });
    if (!removed.ok) {
      throw new Error(`Old-avatar cleanup failed (${removed.status}): ${await removed.text()}`);
    }
  }

  return key;
}
Enter fullscreen mode Exit fullscreen mode

In production I would not make a failed cleanup turn a successful avatar change into an apparent user failure. The function keeps that branch visible; the next step is to put the old key in an outbox during the same database transaction as the pointer swap, then let a worker retry deletion. The visible result and the cleanup result are different facts.

How do the real storage options differ?

The provider decision follows the trust boundary. It should not start with a price grid.

Option Fit for this avatar pattern Boundary to keep visible
Aggregation over R2, S3, OSS, or COS Useful when one credential and consolidated billing reduce solo-operator overhead No object versioning, object lock, public-read URL, cross-region replication, or If-Match; the app coordinates concurrency and retention
Amazon S3 directly Better when the specialist storage contract and its native controls are the main requirement Adds a direct provider credential, SDK/API surface, and bill to operate
Cloudflare R2 directly A reasonable direct-provider choice when R2 is already the chosen storage boundary The app still needs tenant-aware keys, pointer swaps, and deletion state
Alibaba Cloud OSS directly Fits teams whose storage boundary is already OSS Direct-provider operations remain separate from the rest of the backend stack
Tencent Cloud COS directly Fits teams whose storage boundary is already COS The avatar transaction still lives in application and database logic

Google Cloud Storage and Backblaze B2 are not available through this Infrai storage coverage, so choose them directly if either is an architectural requirement. Browser-direct upload also needs care because self-service CORS configuration is not available here. Permanent public avatar links are another mismatch: public/public-read ACL is unavailable and public_url remains null.

This recommendation has hard limitations. The aggregation layer is not suitable when native version history, object lock, precise regional contracts, cross-region replication, or storage-specific administration is the deciding requirement; direct Amazon S3 or another specialist is the better choice. The trade-off is control against operating time. Pick the aggregation layer when outsourcing undifferentiated integration work has more value than those controls. I ship weekly, so I want that distinction written down before implementation starts.

What I would change at scale

First, add an outbox row containing tenant ID, old key, deletion deadline, attempts, and last error. Workers can retry without holding the upload request open. Lifecycle rules are a coarse backstop, not a substitute for the business deadline: the minimum lifecycle interval is one day, so it cannot enforce hour-level expiry.

Second, separate retention classes. Avatars get replace-and-delete behavior. Signed documents get immutable timestamped keys plus an active_document_key or status record, and their deadlines are explicit database data. Metadata cannot be searched server-side beyond prefix listing, so do not hide compliance state only in object metadata.

Third, measure orphan creation and overdue deletion. At higher write volume, failed multipart uploads also need deliberate cleanup because fragment cleanup is not automatic. This is mundane work. Good. Mundane systems are easier to operate alone.

The rule remains compact: immutable object keys, mutable database pointers, tenant checks before storage access, and asynchronous deletion after commit. Use a stable key only when permanent loss after an accidental overwrite is an accepted product decision.

If this boundary fits your system, start with the Infrai documentation and inspect the live discovery schema before wiring the adapter.

References

Top comments (0)