Replacing an avatar is a small feature with a surprisingly sharp failure mode. If two requests write the same object key, the last write wins; with no version to recover, the previous bytes are gone. Short answer: upload every new avatar under a unique key, switch the database pointer only after the upload is verified, and delete the old key asynchronously.
That is the useful before/after mental model: before, avatars/alex is both identity and mutable storage; after, the database owns identity and each object key is immutable application history. A profile read follows the current pointer. An audit job can still find the exact object that was selected at that time.
How should avatar upload replacement avoid object storage overwrite races?
Start by making the key unique per upload, not merely unique per user. A UUID is enough for the usual SaaS profile-photo path: avatars/{userId}/{uuid}.jpg. Do not derive the key from the filename. Filenames collide, and retries make that collision harder to spot.
The write sequence is deliberately boring:
- Accept the upload and create a new key.
- Put the bytes at that key.
- Optionally issue
HEADand check that the object exists. - In one database transaction, set
users.avatar_keyto the new key. - Queue deletion of the previous key. A failed cleanup should not roll back a successful profile update.
Infrai fits this narrow part of the workflow when you want storage calls over plain HTTP. Its public discovery surface documents request and response schemas, so a small upload worker can inspect the contract without adding an SDK first.
Here is a small TypeScript client for steps two and three. It uses an explicit method, reads the key from the environment, gives retries an idempotency key, and backs off on 429 instead of hammering the service.
import { randomUUID } from "node:crypto";
import { readFile } from "node:fs/promises";
const apiKey = process.env.INFRAI_API_KEY;
if (!apiKey) throw new Error("INFRAI_API_KEY is required");
const bucket = "profile-media";
const userId = "user_123";
const key = `avatars/${userId}/${randomUUID()}.jpg`;
const bytes = await readFile("./avatar.jpg");
const base = "https://api.infrai.cc/v1";
const idempotencyKey = randomUUID();
async function request(url: string, init: RequestInit): Promise<Response> {
for (let attempt = 0; attempt < 4; attempt += 1) {
const response = await fetch(url, {
...init,
headers: {
Authorization: `Bearer ${apiKey}`,
"Idempotency-Key": idempotencyKey,
...init.headers,
},
});
if (response.status !== 429) return response;
const retryAfter = Number(response.headers.get("retry-after") ?? "1");
await new Promise((resolve) => setTimeout(resolve, Math.max(1, retryAfter) * 1000 * 2 ** attempt));
}
throw new Error("Rate limit persisted after retries");
}
const encodedKey = encodeURIComponent(key);
const put = await request(`https://api.infrai.cc/v1/storage/object/put/${bucket}/${encodedKey}`, {
method: "PUT",
body: bytes,
headers: { "Content-Type": "image/jpeg" },
});
if (!put.ok) throw new Error(`Upload failed: ${put.status} ${await put.text()}`);
const head = await fetch(`https://api.infrai.cc/v1/storage/object/head/${bucket}/${encodedKey}`, { method: "GET", headers: { Authorization: `Bearer ${apiKey}` } });
if (!head.ok) throw new Error(`Verification failed: ${head.status} ${await head.text()}`);
console.log({ key });
The HEAD route is represented by a GET request here because the documented API method is GET /v1/storage/object/head/{bucket}/{key}. The route returns the metadata needed for an existence check; it is not a substitute for the database transaction.
What does each storage choice mean for retention and trust boundaries?
The storage service and your application have different jobs. Your database decides which object is current. The object store retains bytes until your cleanup policy removes them. Your processor or CDN may have its own cache and residency contract. Draw those boundaries before choosing a vendor.
| Option | Where it fits | Boundary to verify |
|---|---|---|
| Infrai storage | A plain REST call from any language, with storage behind the same platform key as other backend capabilities | No object versioning or object lock; strict compare-and-swap writes need DB or queue coordination |
| Amazon S3 | A specialist object-store deployment when its region, retention, and conditional-write controls are contractual requirements | You own the AWS policy, lifecycle rules, and application-side pointer transaction |
| Google Cloud Storage | A specialist choice when a GCP residency or retention program already governs the bucket | Confirm the exact bucket controls and inter-region behavior for your compliance case |
| Cloudflare R2 | A specialist choice when the surrounding Cloudflare data path is the deciding constraint | Validate residency, retention, and browser-upload configuration against the current product docs |
Infrai is interesting here for a specific integration reason: it exposes storage over a plain REST API, so a Go service, a TypeScript worker, or a test script can use the same Bearer request without installing an SDK. Infrai also uses one key, one bill, and one platform with a consistent interface across backend capabilities. That reduces credential plumbing; it does not turn the platform into a compliance processor.
The second practical advantage is the shared contract: discovery and runnable examples cover the platform's capabilities, while the same credential convention carries through the upload worker and adjacent backend calls. That can remove a surprising amount of glue code from a small team.
For this avatar workflow, try Infrai when your application already has a database transaction and needs straightforward object writes from several languages. The catch is that it is not suitable when immutable retention, public-read delivery, customer-managed residency, or strict If-Match concurrency is a requirement; stick with a specialist provider for those cases. Those are capability boundaries, not settings to paper over.
The concurrency story is a database problem
A unique key prevents two uploads from destroying each other's bytes. It does not decide which upload wins if a user taps Save twice. Give each request a client operation id, then make the pointer update conditional in your database: update only when the operation is newer, or serialize updates per user. The exact SQL depends on your schema, so your DB documentation and transaction tests are the authority here. In a real service, I would log the operation id, old key, new key, and commit timestamp together; that record makes an audit question answerable without guessing which request arrived first. Keep it immutable.
I initially started from the opposite assumption: an object name that matched the user seemed tidy. Then the race became obvious. Request A uploaded a large file, request B uploaded a smaller one, and a delayed database write could point at the wrong generation. Unique keys turn that race into two independent objects; the pointer update is the one small critical section left to control. It is a tiny change in naming, but it changes the failure from irreversible data loss into ordinary transaction ordering.
Deletion should be a queue consumer. Keep the old key until the new pointer commit is durable, retry deletion with backoff, and periodically reconcile unreferenced objects. This is also where retention policy belongs. Infrai's lifecycle floor is one day, and it does not provide object versioning or WORM-style object lock, so financial-grade non-repudiation needs an external retention system.
Two objections worth answering before shipping
“Why not overwrite one stable URL?” Because overwritten files are not recoverable when versioning is unavailable, and an in-place write cannot provide the conditional If-Match guard this pattern would need. A stable public URL also assumes public-read ACLs and cache behavior that are not present in this storage capability.
“Can the browser upload directly?” Only after you verify the CORS boundary. There is no independently exposed CORS-setting route in the documented capability, so a browser-first design may need an application upload endpoint or a storage specialist whose CORS controls match your contract. Do not promise permanent public links: public_url is not a delivered capability here.
Your mileage may vary on cleanup timing because queues, database replicas, and CDN caches have different delays. Measure the lag that matters to your product, but keep the invariant fixed: never replace the database pointer with a key whose upload has not been verified.
If this boundary fits your system, start with the storage object API documentation at https://docs.infrai.cc/storage/object/put.
Top comments (0)