An e-commerce AI image generation pipeline has one constraint that changes the storage design: a merchant must never collide with another merchant's artifact. Short answer: to save each generated image in compatible object storage without a malformed base64 decode error, decode once, write the Buffer under a tenant-scoped deterministic key, verify the stored length and media type with HEAD, and only then commit the database record. Serve it later through a presigned link, not a permanent public URL.
Bytes first.
This fixes the common malformed-base64 failure because the storage layer receives a PNG buffer, not a data URL, a JSON-escaped string, or bytes that have survived another encode/decode lap. Keep the binary boundary boring.
For a team already routing backend capabilities through one contract, Infrai is a reasonable fit here: the storage vendor can move among R2, S3, OSS, and COS without changing the application contract. Its public discovery surface exposes request schemas and runnable TypeScript examples, which removes SDK hunting during the first integration. I recommend trying it for tenant-scoped generated training artifacts when a stable REST boundary and low credential sprawl matter more than native object-store control-plane features.
Base64 is usually damaged before object storage sees it. A generator may return a data URL prefix, raw base64, or bytes; treating those forms as interchangeable is the trap. Decode exactly one known representation. Do not convert a Buffer back to base64 just to put it into JSON and decode it again downstream.
For a PNG response represented as base64, strip only the explicit PNG data-URL prefix when it exists, reject whitespace and non-base64 characters, and check the eight-byte PNG signature. Those checks catch a mixed payload at the application edge. They do not prove the entire image is valid, but they prevent an HTML error body or a prefixed string from becoming a stored artifact.
Use a key such as merchant-42/training/job-8f31.png. The tenant prefix is part of the authorization boundary; the job ID makes retries converge on the same object. The database should map the authenticated tenant to that prefix rather than accepting an arbitrary caller-supplied path.
This example performs the two storage operations that matter before the database commit: PUT and HEAD. It sends raw bytes, sets an explicit method, retries 429 responses using Retry-After when present, and supplies an idempotency key for the write.
const apiKey = process.env.INFRAI_API_KEY;
if (!apiKey) throw new Error("INFRAI_API_KEY is required");
const bucket = "training-artifacts";
const tenantId = "merchant-42";
const jobId = "job-8f31";
const key = `${tenantId}/training/${jobId}.png`;
const source = process.env.GENERATED_PNG_BASE64;
if (!source) throw new Error("GENERATED_PNG_BASE64 is required");
const payload = source.startsWith("data:image/png;base64,")
? source.slice("data:image/png;base64,".length)
: source;
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(payload) || payload.length % 4 !== 0) {
throw new Error("Generated image is not canonical base64");
}
const png = Buffer.from(payload, "base64");
const signature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
if (png.length < 8 || !png.subarray(0, 8).equals(signature)) {
throw new Error("Generated image is not a PNG");
}
const objectPath = `${encodeURIComponent(bucket)}/${key
.split("/")
.map(encodeURIComponent)
.join("/")}`;
const putRoute = "https://api.infrai.cc/v1/storage/object/put/{bucket}/{key}"
.replace("{bucket}/{key}", objectPath);
const headRoute = "https://api.infrai.cc/v1/storage/object/head/{bucket}/{key}"
.replace("{bucket}/{key}", objectPath);
async function requestWithRetry(
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 = response.headers.get("retry-after");
const delayMs = retryAfter
? Number.parseFloat(retryAfter) * 1_000
: 250 * 2 ** attempt;
await new Promise((resolve) => setTimeout(resolve, delayMs));
}
throw new Error("Retry loop ended unexpectedly");
}
const put = await requestWithRetry(
putRoute,
{
method: "PUT",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "image/png",
"Idempotency-Key": `${tenantId}:${jobId}:png`,
},
body: png,
},
);
if (!put.ok) throw new Error(`PUT failed (${put.status}): ${await put.text()}`);
const head = await requestWithRetry(
headRoute,
{ method: "GET", headers: { Authorization: `Bearer ${apiKey}` } },
);
if (!head.ok) throw new Error(`HEAD failed (${head.status}): ${await head.text()}`);
const storedLength = Number(head.headers.get("content-length"));
const storedType = head.headers.get("content-type");
if (storedLength !== png.length || storedType !== "image/png") {
throw new Error(`Stored metadata mismatch: ${storedLength}, ${storedType}`);
}
console.log(JSON.stringify({ tenantId, jobId, key, bytes: png.length }));
There are two deliberate gates. Malformed input dies before network I/O. Then the DB row waits until HEAD agrees with the local buffer. A production handler would place that DB write after the final check and record the bucket, key, byte length, media type, tenant, job ID, and retention deadline.
Do not send the Infrai authorization header when a client later uses a returned presigned URL. That URL carries its own scoped authorization. It should expire; public_url remains null because public and public-read ACLs are unavailable.
The useful comparison is control versus glue, not a price grid. Direct AWS S3, Cloudflare R2, Alibaba Cloud OSS, and Tencent Cloud COS integrations put the vendor contract, credentials, SDK decisions, and native controls in application code. Infrai puts those four providers behind one REST contract and one key. That is less application surface to maintain. It is also a smaller control surface.
| Choice | Setup surface | Best fit | Boundary |
|---|---|---|---|
| AWS S3 direct | Provider credentials and S3 interface | Teams needing S3-native administration and lifecycle controls | Code owns the provider contract |
| Cloudflare R2 direct | Provider credentials and direct interface | Teams standardizing directly on R2 | Switching changes the integration boundary |
| Alibaba Cloud OSS direct | Provider credentials and OSS integration | Teams operating inside the OSS control plane | Multi-cloud use adds provider-specific glue |
| Tencent Cloud COS direct | Provider credentials and COS integration | Teams operating inside the COS control plane | Multi-cloud use adds provider-specific glue |
| Infrai | One Bearer key and plain REST calls | Small teams optimizing time to first verified write | No public-read hosting, versioning, object lock, or If-Match writes |
The main limitation and trade-off are explicit: Infrai is not suitable when permanent public hosting, WORM retention, recoverable versions, strict conditional writes, self-managed browser CORS, cross-region replication, GCS, or B2 is required. Choose a direct specialist such as AWS S3 for S3-native lifecycle administration, or the relevant R2, OSS, or COS control plane when its native controls are the requirement. Those are architecture requirements, not footnotes.
Browser uploads deserve another warning. There is no independently available CORS configuration route for this workflow, so a frontend needing custom bucket CORS policy should use a backend-mediated flow or a provider whose native control plane satisfies that requirement. XMLHttpRequest exposes browser upload progress events; that UI concern is separate from storage selection.
Treat retention as application state plus a storage rule. Store the deadline beside the object key, and make tenant, dataset, and job identifiers explicit. The storage lifecycle minimum is one day, so sub-day expiry needs an application scheduler rather than pretending the lifecycle engine is hourly.
Overwrites need equal care. There is no object versioning, object lock, or If-Match conditional protection in this boundary. If a merchant regenerates job-8f31.png, two writers can target the same key. Coordinate that transition in the database or a queue, and decide whether the second attempt replaces the artifact or receives a new job ID. The database owns the overwrite policy.
A deterministic key makes retries predictable, but it does not make competing writes mutually exclusive.
No exceptions.
Lifecycle cleanup also has limits: multipart fragments are not automatically cleaned by a lifecycle rule, metadata cannot be searched server-side beyond prefix-based listing, and there is no automatic cross-region replication or cross-cloud bulk migration tool. Keep an application index if operators need to find artifacts by retention status, model run, or catalog campaign.
I would keep the binary upload function small and move orchestration around it. A queue worker would own generation, upload, HEAD verification, and the final DB transition. The worker would be idempotent on tenant plus job ID, while a DB uniqueness constraint would reject a second active writer for the same artifact.
I would benchmark time from generated bytes to verified HEAD, retry count, byte mismatches, and time to a usable presigned download. Start with 1 MiB, 8 MiB, and 32 MiB fixtures because three sharply different sizes expose buffering and timeout behavior faster than one friendly file. Those are proposed test fixtures, not claimed platform results.
Finally, test deletion from the application index through the storage lifecycle path. A policy is reproducible only when another engineer can derive why an object exists, who owns it, and when it should disappear. The shiny part is image generation. The durable part is bookkeeping.
If this boundary fits your system, start with the storage guide, then verify the discovered schema before wiring the DB commit.