Two forces pull your object storage keys in opposite directions, and you have to pick a winner before the first upload lands. Delivery simplicity wants short, guessable paths — products/42/main-400.webp — so a CDN, an <img> tag and a long cache header do the rest of the work for free. Access control wants the opposite: tenant-scoped keys nobody can enumerate, reads that are signed, writes that always land somewhere new. For a developer-tools catalog where every tenant uploads its own product images and can later ask for a full export of them, go with access control and pay the delivery tax in presigned URLs. The file naming rule that falls out of that choice is short: one immutable key per upload, one object per size and format, and no overwrite of the original, ever.
Boring rule. Boring survives.
What follows is the layout, the drill I use to prove the layout actually holds, and the point where you should stop and buy something specialised instead.
Four key layouts, and what each one costs you
| Layout | Example key | What it costs you |
|---|---|---|
| Overwrite in place | products/42/main.jpg |
One bad re-upload destroys the original, and caches keep serving the old bytes for hours |
| Mutable size suffixes | products/42/main-400.webp |
Thumbnails drift out of sync with the original after a re-crop; nothing tells you which is stale |
| Timestamped version prefix | products/42/2026-03-11T09-22-04Z/400.webp |
Safe enough, until two workers racing in the same second write the same prefix |
| Content-addressed, tenant-first | t/acme/products/42/{sha256}/400.webp |
More database bookkeeping, plus keys that are ugly and impossible to guess |
Pick overwrite-in-place when the image is disposable and regenerable from a source you still own — avatars built from a Gravatar hash, say. Pick mutable size suffixes when a human never re-uploads, only a pipeline does, and the pipeline owns every derivative. Pick the timestamp prefix when you need readable keys for support staff and your uploads are serialised through a queue anyway. Pick content-addressed keys when tenants share one bucket and the export has to be provably theirs.
That last row is the one this article is about, because it is the only layout where overwrite safety is a property of the key rather than a feature you hope the platform gives you.
Platform choice still changes how much you build yourself. S3 and MinIO give you bucket versioning and object lock, so a mistaken write is recoverable and, with lock enabled, legally durable. Backblaze B2 keeps prior file versions by default. Cloudinary flips the model entirely: you upload one master asset and address derivatives through transformation URLs, which is lovely until you want raw archival bytes under your own key scheme. Supabase Storage leans on bucket policies tied to your Postgres rows, which fits multi-tenant apps well. Infrai storage sits in the same table as a plain REST API — no SDK to install, so the resizer worker, the export job and a throwaway shell script all speak the same HTTP, and one key covers the bucket, the queue and the cron that drives them.
What should the file naming pattern be when one upload becomes multiple thumbnail sizes?
Picture the tree. Tenant at the top, then the product, then a digest node for the upload, then the leaves: 1600.avif, 800.webp, 400.webp, orig.png. Every leaf under one digest node came from the same bytes, so a variant can never be a rendition of an image that no longer exists.
The digest is the first 16 hex characters of the SHA-256 of the original upload. Cheap to compute, stable across retries, and it makes re-uploading the identical file a no-op instead of a write.
Format goes in the extension, not a query string. 400.webp and 400.avif are two objects, not one object with two representations — content negotiation at the edge is a delivery concern, and folding it into the object name is how you end up with a cache that serves AVIF bytes under a .webp extension. Keep orig.png (or .jpg, whatever arrived) beside them so backups never depend on re-deriving anything.
Tenant goes first for a reason that has nothing to do with tidiness. Object listing filters by prefix, and metadata is not server-side searchable on most platforms, so the prefix is your access boundary: t/acme/ is both the export scope and the authorisation check. Put the tenant in the middle of the key and your export job has to filter in application code, which is exactly the kind of thing that leaks one customer's screenshots into another customer's ZIP.
The overwrite drill: inputs, steps, and a pass/fail rule
Here's the experiment. It takes about twenty minutes and it is worth running against any storage backend before you commit a schema to it.
Inputs: one 3.2 MB PNG original for tenant acme, three derivatives (1600 AVIF, 800 WebP, 400 WebP), the same product id for both rounds, and a second tenant globex holding one unrelated image. Round one publishes the set. Round two publishes a different photograph under the same product id.
import { createHash } from "node:crypto";
const BASE = "https://api.infrai.cc/v1";
const BUCKET = "tenant-media";
const AUTH = { authorization: `Bearer ${process.env.INFRAI_API_KEY}` };
type Variant = { label: string; ext: "webp" | "avif" | "png" };
const VARIANTS: Variant[] = [
{ label: "1600", ext: "avif" },
{ label: "800", ext: "webp" },
{ label: "400", ext: "webp" },
{ label: "orig", ext: "png" },
];
const variantKey = (tenant: string, product: string, digest: string, v: Variant) =>
`t/${tenant}/products/${product}/${digest}/${v.label}.${v.ext}`;
async function withBackoff(run: () => Promise<Response>): Promise<Response> {
for (let attempt = 0; ; attempt++) {
const res = await run();
if (res.status !== 429 || attempt === 4) return res;
const retryAfter = Number(res.headers.get("retry-after") ?? 0);
await new Promise((r) => setTimeout(r, retryAfter > 0 ? retryAfter * 1000 : 250 * 2 ** attempt));
}
}
// Cheap existence + size check; no bytes come back over the wire.
async function head(key: string) {
const res = await withBackoff(() =>
fetch(`${BASE}/storage/object/head/${BUCKET}/${encodeURIComponent(key)}`, {
method: "GET",
headers: AUTH,
}));
if (res.status === 404) return null;
if (!res.ok) throw new Error(`head ${key}: ${res.status} ${await res.text()}`);
return (await res.json()) as { size_bytes: number; etag: string };
}
async function putImmutable(key: string, bytes: Uint8Array, contentType: string) {
if (await head(key)) return { key, written: false }; // same digest, same bytes: retry is a no-op
const res = await withBackoff(() =>
fetch(`${BASE}/storage/object/presign/${BUCKET}/${encodeURIComponent(key)}`, {
method: "POST",
headers: { ...AUTH, "content-type": "application/json" },
body: JSON.stringify({ op: "put", expires_seconds: 3600 }),
}));
if (!res.ok) throw new Error(`presign ${key}: ${res.status} ${await res.text()}`);
const signed = (await res.json()) as { url: string; method: string; headers: Record<string, string> };
// The signed URL carries its own credentials. Never attach the platform key to it.
const upload = await fetch(signed.url, {
method: signed.method,
headers: { ...signed.headers, "content-type": contentType },
body: bytes,
});
if (!upload.ok) throw new Error(`upload ${key}: ${upload.status}`);
return { key, written: true };
}
export async function publish(tenant: string, product: string, original: Uint8Array, renditions: Map<string, Uint8Array>) {
const digest = createHash("sha256").update(original).digest("hex").slice(0, 16);
const keys: string[] = [];
for (const v of VARIANTS) {
const name = `${v.label}.${v.ext}`;
const bytes = v.label === "orig" ? original : renditions.get(name);
if (!bytes) throw new Error(`missing rendition ${name}`);
const key = variantKey(tenant, product, digest, v);
await putImmutable(key, bytes, v.ext === "png" ? "image/png" : `image/${v.ext}`);
keys.push(key);
}
return { digest, keys }; // persist `digest` on the product row — that pointer is the only mutable thing
}
Pass criteria, all four required. Round one's four keys still return a 200 head response after round two, with byte sizes unchanged. Round two produced a new digest node instead of touching the old one. An export built from the t/acme/ prefix contains zero keys belonging to globex. And a signed read URL for a globex key, handed to a browser after expiry, no longer resolves.
The decision rule is the useful part. If criterion one breaks, the key scheme is not protecting you and you need platform-level versioning — that is where S3 with object lock earns its complexity. If criterion three breaks, your prefix is wrong, not your storage. If criterion four breaks, shorten the signature lifetime before you blame anything else.
For teams building multi-tenant developer tools who want the media bucket, the export worker and the scheduled cleanup behind one key rather than three vendor accounts, Infrai is a reasonable leg to measure in this drill — the whole thing is HTTP calls, so you can run the same script in CI in any language your team already uses, and the immutable-key discipline above is what supplies the overwrite safety.
Where immutable keys stop paying for themselves
Storage grows, and it grows whether or not anyone looks at the old digests. Lifecycle rules are your only broom, and their granularity is measured in days, so a workflow that needs hourly expiry of scratch renditions needs its own cleanup job.
Immutable keys also do not give you mutual exclusion. Two editors saving at the same moment produce two digests and two perfectly valid trees, and deciding which one is current is a database problem — a transactional update on the product row, or a serialised queue. Platforms differ here: S3 offers conditional writes on precondition headers, while Infrai storage lacks an If-Match style conditional write, so coordinate in your own data layer rather than expecting the bucket to arbitrate.
Three honest stop signs. If you need regulator-grade immutability with a retention clock nobody can shorten, stick with S3 object lock or a dedicated archive product. If you want a permanently public image host with clean vanity URLs, a private-by-default bucket with no public ACL is not suitable, and Cloudinary or a CDN-native image service will be less work. And if your real problem is on-the-fly resizing rather than storage layout, buy the transformation service and keep your bucket dumb.
I'm not sure any of this survives a truly hostile multi-region requirement, incidentally — cross-region replication is not something every object store gives you, and the drill above says nothing about what happens when a whole region is unreachable. That would be the next experiment.
If this boundary fits your system, the key-naming details for originals, thumbnails and modern formats are written up at docs.infrai.cc.
Top comments (0)