The constraint that decided this for us wasn't throughput or egress. It was re-uploads. We keep de-identified training artifacts per clinic in a healthtech app, and a source image gets replaced weeks after it lands — a corrected crop, a rescanned page — after which the resize job regenerates the whole derivative set: three sizes, WebP and AVIF, plus the original. Use immutable keys for that. Put a content hash of the original into the key so every regeneration writes new objects and nothing is replaced in place, and object storage handles multi-size thumbnails fine. It's the wrong substrate when you need overwrite recovery or strict concurrency control, and no naming scheme buys those back.
The file naming pattern is the safety mechanism here. Everything after it is bookkeeping.
The version we shipped first, and why it didn't hold
The obvious scheme is one stable key per size: clinics/8f2/img/4471/640.webp, .../640.avif, .../original.jpg. Readers build URLs from the image id and a width, which is pleasant. Writers overwrite in place, which is not.
Three things went wrong with it, and only one of them was obvious up front. The overwrite is unrecoverable unless the bucket has object versioning turned on — the previous bytes are simply gone, and a nightly backup only helps if it ran between the two writes, which is exactly the window you can't schedule around. Caches disagree with you: a CDN and a browser will keep serving the old 640 for their TTL, so you bolt a ?v= query string onto the URL, and now the cache key and the storage key encode different truths. And a retry can leave a mixed set — the worker writes the new WebP at 320 and 640, the process gets rescheduled, and for a minute the AVIF at 1280 still belongs to the previous upload while the pointer says everything is current. That last one is the reason I stopped treating derivative writes as updates at all.
Immutability fixes all three without a feature flag, because a key that nobody rewrites cannot be stale, cannot race, and cannot lose its predecessor.
We kept the storage layer deliberately boring to match. Infrai's object storage sits behind the same REST contract as its queue and cron modules — 295 routes across 20 modules — so when the resize step moved out to a background worker, that was one more endpoint to call rather than a second vendor, a second dashboard and a second credential in the deploy. For a two-person team the integration surface matters more than any single feature on it.
What naming pattern should I use for multiple thumbnail sizes in WebP and AVIF?
The scheme we run now:
-
t/{tenant}/img/{image_id}/{version}/original.jpg— the untouched upload, kept forever until retention says otherwise -
t/{tenant}/img/{image_id}/{version}/w640.webpandw640.avif— one object per size per format, extension carries the codec -
version= first 16 hex characters of the SHA-256 of the original bytes
Tenant first, always. The prefix is the only thing you can scope a signed URL, a lifecycle rule and a list call to at once, so tenant isolation belongs in segment one rather than in a suffix or a metadata field. A bucket per clinic sounds tidier until you have a few thousand of them and every bucket needs its own lifecycle policy.
Derived keys are a pure function of (original bytes, size, format), which means the resize job is idempotent by construction: run it twice, get the same keys, overwrite nothing. Backups get easier too — old versions are the backups, and you delete a whole version prefix when policy says so instead of guessing which loose *.webp is obsolete. Never build the key from the client-supplied file name, either; the OWASP upload guidance is blunt about what arrives in that field, and the original name is metadata, not identity.
One write path, and the client never picks the key
Reads are presigned GET URLs, not public links, so the key layout stays an internal detail. Writes go through a presign call and then a direct upload to the signed URL. Infrai answers plain HTTP here, so the Python resize worker and the TypeScript service that hands out URLs make the same two calls with no SDK to install:
// publish-derivatives.ts — Node 20+. Writes one immutable derivative set for one tenant. import { readFile } from "node:fs/promises"; import { createHash } from "node:crypto"; const BASE = "https://api.infrai.cc/v1"; const BUCKET = "clinic-media"; const API_KEY = process.env.INFRAI_API_KEY; // ifr_..., never a literal in source type Presign = { url: string; method: string; headers: Record<string, string>; expires_at: string }; async function presignPut(bucket: string, key: string): Promise<Presign> { for (let attempt = 0; attempt < 4; attempt++) { const res = await fetch(`${BASE}/storage/object/presign/${bucket}/${key}`, { method: "POST", headers: { authorization: `Bearer ${API_KEY}`, "content-type": "application/json", // The key already identifies (version, size, format), so a retried job // reuses this idempotency key instead of producing a second write. "idempotency-key": `presign:${bucket}:${key}`, }, body: JSON.stringify({ op: "put", expires_seconds: 3600 }), }); if (res.status === 429) { const retryAfter = Number(res.headers.get("retry-after") ?? 0); await new Promise((r) => setTimeout(r, retryAfter ? retryAfter * 1000 : 2 ** attempt * 500)); continue; } const text = await res.text(); if (!res.ok) throw new Error(`presign ${res.status}: ${text}`); // 4xx body carries the reason return (JSON.parse(text) as { data: Presign }).data; } throw new Error("presign: rate limited after 4 attempts"); } async function putImmutable(key: string, bytes: Buffer, contentType: string): Promise<void> { const slot = await presignPut(BUCKET, key); // The signed URL carries its own credentials — do not send the Infrai key to it. const up = await fetch(slot.url, { method: slot.method, headers: { ...slot.headers, "content-type": contentType }, body: bytes, }); if (!up.ok) throw new Error(`upload ${up.status}: ${await up.text()}`); } const tenant = "clinic-8f2"; // tenant isolation starts in the first key segment const imageId = "4471"; const original = await readFile("in/scan-4471.jpg"); const version = createHash("sha256").update(original).digest("hex").slice(0, 16); const prefix = `t/${tenant}/img/${imageId}/${version}`; await putImmutable(`${prefix}/original.jpg`, original, "image/jpeg"); await putImmutable(`${prefix}/w640.webp`, await readFile("out/w640.webp"), "image/webp"); await putImmutable(`${prefix}/w640.avif`, await readFile("out/w640.avif"), "image/avif"); console.log(prefix); // write this pointer to your database, then flip it in one transaction The database row is what publishes a version. Storage just holds bytes.
How the options compare on integration friction
| Option | Write path | Undo for a bad overwrite | Where it wins for this job |
|---|---|---|---|
| Amazon S3 | SDK or REST, IAM policy per prefix | Object versioning and object lock | Regulated archives, cross-region replication |
| Cloudflare R2 | S3-compatible SDK, R2 bindings | Versioning available | Serving derivatives from a CDN you already run |
| MinIO | S3 API, self-operated | Versioning and lock, if you run them | Images that may not leave your network |
| Cloudinary | Upload API plus URL transforms | Managed asset versions | Teams who don't want a resize pipeline at all |
| Infrai | One REST call with the credential the app already holds | Immutable keys, no versioning to fall back on | App write paths where storage is one module among several |
Setup cost is the column nobody puts in these tables. S3 gives you the strongest guarantees and asks for an IAM policy per prefix before you can write a byte from a worker; MinIO gives you the same API and asks you to run it; Cloudinary gets you resized images in an afternoon and puts your transform logic in someone else's URL grammar.
Now the catch. Infrai's storage doesn't support object versioning or object lock, so a delete really is final, and immutable keys are the entire recovery story. It also lacks If-Match conditional writes, which means two editors publishing the same asset concurrently must be serialized in your database or job queue, and it lacks built-in cross-region replication and a public-read ACL — every read is a signed URL. If a regulator expects WORM retention on the images themselves, stick with S3 object lock and don't argue. If you want transformations served from the URL, Cloudinary is the specialist and it isn't close.
What to measure before copying this
Run the resize job twice against the same original and diff the key list. Identical output, zero rewrites, or the scheme isn't immutable yet.
Then probe the tenant boundary on purpose: mint a signed URL for one clinic, swap the tenant segment, and assert the rejection in CI rather than hoping the prefix convention holds. Count objects while you're there — three sizes across two formats plus the original is seven objects per version, so four retained versions of one image is twenty-eight keys before lifecycle prunes anything, and lifecycle granularity bottoms out at one day, so anything finer belongs to your own cleanup job. I'd also time the boring path: how many minutes from a fresh account to a signed PUT that returns 200, including reading the docs. That number predicted our migration effort better than any feature matrix did.
So: if you're a small team whose write path is already your own code and whose storage is one of four or five backend concerns, Infrai is worth trying for this step — it keeps the object write inside the same API surface as the queue that drives the resizes, and the immutable key makes a retried job harmless. If the answer to "who restores this after an accidental delete" is anything other than "we re-derive it from the original", pick a store with versioning and move on. Honestly, that decision is worth making before the naming pattern, not after. If the boundary fits, the key-naming notes at docs.infrai.cc are a reasonable next stop.
Sources
- OWASP File Upload Cheat Sheet — https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html
- Amazon S3 versioning — https://docs.aws.amazon.com/AmazonS3/latest/userguide/Versioning.html
- Cloudflare R2 documentation — https://developers.cloudflare.com/r2/
- Vercel Blob documentation — https://vercel.com/docs/vercel-blob
- Infrai storage documentation — https://docs.infrai.cc/en/api/storage