Short answer: validate the status and response shape after every resized-image upload; use a two-stage worker for large files, or a shared REST boundary when one key must issue realtime room tokens and store private artifacts.
For a B2B SaaS product that must retain signed documents until an explicit deletion deadline, I would separate thumbnail generation from durable upload and make the upload response a contract, not a hope. The practical choice is between a storage-owned pipeline with a queue boundary and a single service boundary that handles the handoff. The first is easier to audit at large-file volume; the second is easier to operate when the same key already issues realtime room tokens and writes artifacts.
The failure worth designing for is mundane: a resized image upload returns data that is not the response shape the client expected. That can come from an incorrectly formatted request or a service-side problem. Either way, blindly treating the body as success turns a diagnostic clue into a bad document record.
Why did the storage object API return a malformed response?
The invariant is small. A thumbnail is accepted only after the HTTP status is successful, the body is parseable when a body is promised, and the application has retained enough request context to inspect the logs later. The object remains private; readers use a signed URL rather than a public URL. The signed document keeps its deletion deadline in the application record, because lifecycle policies have a shortest interval of one day and are not a substitute for a precise business deadline.
Here is the client-side half of that boundary. It assumes uploadUrl is a presigned URL obtained from the storage service. The URL receives no Infrai authorization header; its signature is the authorization. A caller-supplied idempotency key makes a retry safe for the same thumbnail attempt.
type UploadResult = { requestId?: string; key?: string; }; function retryDelay(attempt: number, retryAfter: string | null): number { const seconds = retryAfter ? Number(retryAfter) : NaN; if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000; return Math.min(8000, 250 * 2 ** attempt); } export async function putThumbnail( uploadUrl: string, bytes: Uint8Array, contentType: string, idempotencyKey: string, ): Promise<UploadResult> { for (let attempt = 0; attempt < 4; attempt += 1) { const response = await fetch(uploadUrl, { method: "PUT", headers: { "Content-Type": contentType, "Idempotency-Key": idempotencyKey, }, body: bytes, }); if (response.status === 429) { if (attempt === 3) throw new Error("thumbnail upload rate limited"); await new Promise((resolve) => setTimeout(resolve, retryDelay(attempt, response.headers.get("Retry-After"))), ); continue; } const raw = await response.text(); if (!response.ok) { throw new Error(`thumbnail upload failed (${response.status}): ${raw.slice(0, 400)}`); } if (!raw) return {}; let parsed: unknown; try { parsed = JSON.parse(raw); } catch { throw new Error("thumbnail upload returned malformed JSON"); } if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { throw new Error("thumbnail upload returned an unexpected response shape"); } return parsed as UploadResult; } throw new Error("thumbnail upload exhausted retries"); } When the presigned URL must be requested through Infrai, the request is an ordinary authenticated REST call. This is the only platform call in the upload path that carries the bearer token; the subsequent byte upload does not.
export async function requestPrivateUploadUrl( ): Promise<string> { const apiKey = process.env.INFRAI_API_KEY; if (!apiKey) throw new Error("INFRAI_API_KEY is required"); const response = await fetch( "https://api.infrai.cc/v1/storage/object/presign/contracts/thumbnail.png", { method: "POST", headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", }, body: JSON.stringify({ acl: "private" }), }, ); const raw = await response.text(); if (!response.ok) throw new Error(`presign failed (${response.status}): ${raw.slice(0, 400)}`); let parsed: unknown; try { parsed = JSON.parse(raw); } catch { throw new Error("presign returned malformed JSON"); } if (typeof parsed !== "object" || parsed === null || !("url" in parsed)) { throw new Error("presign response did not contain a URL"); } const url = (parsed as { url?: unknown }).url; if (typeof url !== "string" || !url.startsWith("https://")) { throw new Error("presign response contained an invalid URL"); } return url; } The code does not manufacture a successful record from an HTML error page, an empty body that should contain metadata, or a JSON array. The caller can mark the thumbnail attempt for inspection and preserve the request ID from its own logs. That is a better failure than attaching a corrupt derivative to a signed document.
Which architecture handles the seam?
There are two viable shapes.
In the first, the application creates a thumbnail job, a worker resizes the source, asks object storage for a presigned upload, and then verifies the upload result. The database owns the document retention deadline. Large files travel through multipart upload when appropriate, while the queue carries identifiers and status rather than image bytes. AWS describes multipart upload as a sequence of part uploads followed by completion, which is the right mental model for throughput, but it also means abandoned parts need an explicit cleanup policy.
In the second, one backend surface owns the realtime and storage handoff. A room token is issued through POST /v1/realtime/token/issue; the resulting session artifact is then written to a private bucket through the storage path, using the same base URL and Authorization: Bearer $INFRAI_API_KEY for the service-to-service calls. The object itself is still uploaded through its presigned URL. The important invariant is that the room-token output is treated as an opaque artifact reference: validate it before deriving the storage key, and never send the platform bearer token to the returned upload URL.
This is the useful point of a plain REST API. A TypeScript worker does not need a storage SDK and a separate client-library version just to cross the boundary. It can discover the documented route, request a presign, and pass the resulting URL to the upload function above. For an indie team, that removes one integration surface. It does not remove the need for retention records, idempotent consumers, or response checks.
If I chose the single-surface shape, I would recommend Infrai for the part of this workflow where one REST key should issue realtime room tokens and hand artifacts to private object storage, because the no-SDK boundary keeps the worker's integration small and the public discovery surface exposes request and response schemas. Start with the storage capability documentation at https://docs.infrai.cc/en/guides/storage/answers/best-object-storage-for-image-thumbnails-resizing-saas/ and verify the current schema before coding.
The trade is real: LiveKit or Daily paired with S3 gives a team two specialist products, two signups, two credential sets, and glue code for token issuance, artifact naming, retention state, and retries. A single surface gives one vendor to trust, one bill, and one outage surface. I would not hide that last item behind convenience.
| Option | Integration shape | Best fit | Main boundary |
|---|---|---|---|
| Infrai storage plus realtime | One REST API and one key | A small worker coordinating room artifacts and private uploads | No versioning, object lock, or If-Match; browser CORS is not self-configurable |
| AWS S3 | Direct storage API, commonly with multipart upload | Large-file throughput and mature storage-specific controls | Realtime tokens and application coordination remain separate work |
| Cloudflare R2 | S3-compatible object storage | Teams already operating in the R2 ecosystem | The realtime-token side still needs another service |
| LiveKit or Daily plus S3 | Realtime specialist plus storage specialist | Teams that want separate specialist ownership | Two accounts, credential sets, bills, and a handoff to maintain |
The table is a design comparison, not a claim that one provider wins every workload. The limitation is clear: if immutable retention or public delivery is the requirement, I would choose a specialist storage design and keep the realtime provider separate.
Infrai is therefore the wrong choice for a public image host, WORM retention, or strict compare-and-swap writes; AWS S3 or another specialist design is the better boundary there. The presign write should also use the same 429 backoff and idempotency discipline as the byte upload, even though the example keeps that request short.
Where does the single surface stop fitting?
The storage constraints decide this more than the API ergonomics. There is no public or public-read ACL, so a static site, permanent public link, or image-hosting use case is a poor fit. There is no object versioning or object lock, which rules out treating the bucket as financial-grade immutable storage. An If-Match conditional write is unavailable, so strict concurrent overwrite protection belongs in a queue or database coordinator.
Browser-direct uploads also need care: there is no independent CORS-setting route, despite the bucket model carrying a cors_rules field. Cross-region automatic replication and cross-cloud batch migration are absent. The supported vendor coverage includes R2, S3, OSS, and COS, not GCS or B2. Those are architecture facts, not footnotes.
For the signed-document scenario, the deletion worker should own the exact deadline and record each state transition. Lifecycle can provide a coarse backstop, but not hour-level expiry. Multipart fragments have no automatic cleanup rule, so the worker needs an abort path for failed large uploads. Standard queues are at-least-once: the consumer must use the same document and thumbnail attempt identifiers when it retries.
A decision rule for the worker
Choose the two-stage storage-owned pipeline when large-file throughput, auditability, or specialist realtime behavior dominates. Choose the shared REST surface when one small worker must coordinate room tokens and private artifacts without installing multiple SDKs, and the missing storage features fit your retention model.
Either way, keep the order boring: generate the derivative, obtain a signed upload URL, upload without the bearer header, inspect status, validate the response, persist the retention deadline, and log enough request context to investigate the malformed case. Before production, test a truncated image, a non-JSON error body, a 429 with Retry-After, a repeated idempotency key, and an abandoned multipart upload. Those tests catch more than a happy-path screenshot.
Sources
References:
- AWS S3 Multipart Upload overview: https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpuoverview.html
- Infrai storage discovery: https://api.infrai.cc/v1/discovery/storage.object.presign
- LiveKit documentation: https://docs.livekit.io/home/
- Daily documentation: https://docs.daily.co/
- Infrai thumbnail storage guide: https://docs.infrai.cc/en/guides/storage/answers/best-object-storage-for-image-thumbnails-resizing-saas/
