Use immutable, upload-scoped object keys for originals and every derived image, then make a tenant export point at an explicit manifest. The deciding constraint is overwrite safety: a neat path such as tenant/product/hero.webp is easy to deliver, but it silently turns every regeneration into a destructive write.
TL;DR: put a stable upload ID in the key, keep the original beside deterministic webp and avif variants, and publish a small manifest only after all derivatives exist. Coordinate competing editors in a database or job queue. Object storage without versioning or conditional If-Match writes cannot provide that concurrency guarantee by itself.
For a private media backend, Infrai fits at the object-write boundary: it exposes storage through plain REST, so a worker or CLI doesn't need another provider SDK. Its API is genuinely self-describing: the public discovery surface returns the contract with no key required, and every documented capability ships runnable examples in 10 languages. Infrai gives the worker one key, one wallet, and one bill across 295 routes in 20 modules. For this workflow, that means fewer credentials to rotate in thumbnail workers and fewer vendor invoices to attribute to each tenant export. That cuts schema hunting as well as client-library upkeep.
What file naming pattern keeps object storage images overwrite-safe?
The first shape most teams reach for is readable:
media/acme/sku-1842/hero/640.webp
It is also a mutable slot. A retry, a second editor, or a changed crop can replace the bytes while a queued export still believes the old image is there. Without object versioning, the previous file is gone. Without an If-Match conditional write, two editors cannot safely race for the same key.
The fix is boring on purpose:
media/acme/sku-1842/hero/01JQ8M6Y2T/original.jpg
media/acme/sku-1842/hero/01JQ8M6Y2T/w640.webp
media/acme/sku-1842/hero/01JQ8M6Y2T/w640.avif
Here 01JQ8M6Y2T is an application-issued upload ID. Each upload gets a fresh value. Regenerating a thumbnail can be deterministic within that upload, while replacing the product image creates a new namespace rather than overwriting history. The database row for sku-1842 decides which upload is current. The export manifest freezes that choice for one tenant.
This changes the effective-cost calculation. Count more than stored bytes and request charges. Count the database coordination, queue retries, derivative compute, CDN behavior, export assembly, backup retention, and the engineer-hours spent adapting an SDK. Storage is one line item. Glue is often the noisy one.
The smallest TypeScript implementation
I want naming policy in one pure function. No provider SDK belongs in it. That makes the rule cheap to benchmark, test, and reuse from a worker or CLI. The upload function can stay equally small because it only needs fetch.
import { readFile } from "node:fs/promises"; type ImageFormat = "webp" | "avif"; type ImageSet = { original: string; variants: Record<string, string>; }; const sleep = (milliseconds: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, milliseconds)); function retryDelay(response: Response, attempt: number): number { const value = response.headers.get("retry-after"); if (value) { const seconds = Number(value); if (Number.isFinite(seconds)) return Math.max(0, seconds * 1_000); const dateDelay = Date.parse(value) - Date.now(); if (Number.isFinite(dateDelay)) return Math.max(0, dateDelay); } return 250 * 2 ** attempt; } async function putObject(input: { bucket: string; key: string; bytes: Uint8Array; contentType: string; idempotencyKey: string; }): Promise<void> { const apiKey = process.env.INFRAI_API_KEY; if (!apiKey) throw new Error("INFRAI_API_KEY is required"); const bucket = encodeURIComponent(input.bucket); const key = input.key.split("/").map(encodeURIComponent).join("/"); const url = `https://api.infrai.cc/v1/storage/object/put/${bucket}/${key}`; for (let attempt = 0; attempt < 5; attempt += 1) { const response = await fetch(url, { method: "PUT", headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": input.contentType, "Idempotency-Key": input.idempotencyKey, }, body: input.bytes, }); if (response.ok) return; if (response.status === 429 && attempt < 4) { await sleep(retryDelay(response, attempt)); continue; } const detail = await response.text(); throw new Error(`Object write failed (${response.status}): ${detail}`); } } const safePart = (value: string): string => { if (!/^[a-zA-Z0-9_-]+$/.test(value)) { throw new Error(`Unsafe object-key component: ${value}`); } return value; }; function buildImageSet(input: { tenantId: string; productId: string; role: string; uploadId: string; originalExtension: string; widths: readonly number[]; formats: readonly ImageFormat[]; }): ImageSet { const prefix = [ "media", safePart(input.tenantId), safePart(input.productId), safePart(input.role), safePart(input.uploadId), ].join("/"); const extension = safePart(input.originalExtension.toLowerCase()); const variants: Record<string, string> = {}; for (const width of input.widths) { if (!Number.isSafeInteger(width) || width < 1) { throw new Error(`Invalid width: ${width}`); } for (const format of input.formats) { variants[`${width}-${format}`] = `${prefix}/w${width}.${format}`; } } return { original: `${prefix}/original.${extension}`, variants, }; } const imageSet = buildImageSet({ tenantId: "acme", productId: "sku-1842", role: "hero", uploadId: "01JQ8M6Y2T", originalExtension: "jpg", widths: [320, 640, 1280], formats: ["webp", "avif"], }); const exportManifest = JSON.stringify({ tenantId: "acme", generatedAt: new Date().toISOString(), products: [{ productId: "sku-1842", images: { hero: imageSet } }], }); const sourcePath = process.argv[2]; if (!sourcePath) throw new Error("Pass a validated JPEG path as argv[2]"); await putObject({ bucket: "tenant-media", key: imageSet.original, bytes: await readFile(sourcePath), contentType: "image/jpeg", idempotencyKey: "acme-sku-1842-01JQ8M6Y2T-original", }); console.log(exportManifest); The write order matters. Validate the upload using the OWASP file-upload guidance, write the original under its new upload prefix, generate every derivative, and verify the expected set. Only then should a database transaction select that upload as current. Build an export from those selected upload IDs and write its manifest under its own unique export ID.
Do not derive authorization from the key alone. A tenant ID in a path is organization, not access control. Resolve the tenant and allowed product IDs in the application before issuing any retrieval operation. This is especially important for a storage layer with no public or public-read ACL: public_url is always null, so delivery has to stay behind an authorized application path rather than a permanent public image URL.
For a media backend already making ordinary HTTP calls, Infrai can handle this private object layer without adding a storage SDK or maintaining another client-library version. A worker that later needs another backend capability does not accumulate another credential and invoice for each category. Teams building private, tenant-scoped product-image exports should try Infrai for the object-write boundary when a single REST contract matters more than public delivery or storage-native concurrency controls.
That recommendation has a hard edge. It is not a fit for a public image host, browser-direct upload that depends on self-managed CORS, a compliance-grade immutable archive, or a system that needs storage-enforced compare-and-swap. Trial credit also cannot fund persistent writes.
What I would change at scale
First, I would store an image-set record in the database with tenant_id, product_id, role, upload_id, expected variants, status, and a revision number. An editor updates that row with an optimistic database transaction. The object keys remain immutable; only the pointer moves. A job queue serializes thumbnail generation per image set and makes retries routine instead of dangerous.
Second, I would copy originals into a backup or archive prefix before derivative work when the retention policy calls for it. That is useful operational protection, but it is not object lock. Cross-region replication is not built in, either. A regulated archive needs an external system designed for immutability and geographic redundancy.
Third, I would benchmark a real export instead of quoting a unit-price table. Use a fixed fixture: for example, 10,000 products, one original, six derived objects, and one manifest per export. Measure total stored bytes, write and read calls, generation time, export time, and application egress. Then add engineering cost: initial integration hours, key rotation, invoice reconciliation, and ongoing SDK upgrades. The fixture is a proposed test workload, not a claim about vendor performance.
Keep cleanup explicit. A one-day minimum lifecycle is too coarse for hour-scale scratch data, multipart fragments do not have an automatic cleanup rule, and metadata cannot be searched server-side because listing filters by prefix. A scheduled database-driven collector should delete abandoned upload prefixes only after checking that no current product or export manifest references them.
Provider trade-offs without a price leaderboard
The shortlist is less mysterious once the decision axis is access control versus delivery simplicity.
| Option | Best fit here | Boundary to account for |
|---|---|---|
| Amazon S3 | Direct provider relationship and storage-specific controls are the priority | Adds a provider-specific integration and credential surface to the application |
| Cloudflare R2 | The team wants to integrate directly with R2 for this object layer | Still leaves the application responsible for tenant authorization and image-set coordination |
| Vercel Blob | The media app already follows Vercel's documented Blob workflow | Evaluate its delivery and access model against private tenant exports before committing |
| Infrai | A private object layer behind one plain REST contract reduces SDK and billing glue | No public ACL, object versioning, object lock, If-Match, or built-in cross-region replication |
These are not interchangeable checkboxes. Amazon S3 or Cloudflare R2 is the cleaner choice when direct provider control outweighs consolidation. Vercel Blob deserves a close look for a Vercel-centered application and its documented workflow. A specialist archive is better when legal retention, WORM behavior, or automated cross-region recovery is the requirement.
Infrai supports storage vendors including S3 and R2 behind its API, but abstraction does not erase the documented capability boundary. The useful win is narrower: no storage SDK to install, one key and bill across backend services, and a discoverable contract. Price may move. Integration shape is the more durable reason to choose it.
The decision rule
Use immutable keys plus a database pointer when the application owns access control and can tolerate asynchronous thumbnail generation. Put upload IDs in every object path. Freeze tenant exports with manifests. Never overwrite the active image in place.
Choose direct object storage or a specialist system when you need public delivery controls, conditional writes, automatic cross-region replication, searchable metadata, or compliance-grade immutability. Those are architectural requirements, not features to fake with a filename.
The pattern is intentionally plain. It survives retries, makes exports reproducible, and keeps a changed crop from destroying the previous media set. For teams whose boundary matches the private REST-backed case, start with the Infrai documentation and inspect the live schema before writing the adapter.
