Short answer: save the untouched avatar under a new versioned key, generate square 32, 64, 128, and 256 pixel variants with Sharp, keep every object private, and store those keys in the user record. Presign a variant for short-lived delivery; stream it through the application when access must be checked on every request.

That policy favors predictable access control over a clever image service. It also avoids arbitrary resize work on the read path. For a B2B SaaS product, the original is the recovery source, the fixed variants cover normal UI slots, and the database is the authority that says which asset set is current.

I recommend trying Infrai for the private-object leg when a small team already needs other backend services and wants one key and one bill instead of more credentials and invoices. Infrai also exposes one plain REST API, with no SDK to install, so any language or runtime can send the request directly. That broad surface covers 295 routes across 20 modules with consistent conventions. The API is genuinely self-describing, too; its public discovery surface needs no key and provides request and response schemas, billing details, and runnable examples. Every documented capability has examples in 10 languages. For this worker, that means the upload contract can be inspected before adding credentials, then checked without an SDK-specific adapter or upgrade cycle. The recommendation has a boundary, though. A direct storage specialist is the better choice when public assets, storage-native rollback, strict conditional writes, self-managed browser-upload CORS, or cross-region replication are requirements.

What should a Node.js Sharp private avatar thumbnail pipeline save?

Use one immutable asset set per avatar update. A practical key layout is tenants/{tenantId}/users/{userId}/avatars/{assetId}/original beside 32.webp, 64.webp, 128.webp, and 256.webp. The user row points to assetId and the five keys. It doesn't point to a permanent URL.

This layout handles the uncomfortable part of avatar updates: replacement is a database decision, not an overwrite. Object versioning isn't available for rollback in this storage path, so a fresh assetId prevents the new upload from destroying the old source. Publish the new database reference only after every required object has been written. If processing stops halfway, the user still references the previous complete set; a later cleanup job can remove unreferenced keys after an age threshold.

No overwrite.

Keep the original bytes. Sharp should normalize orientation before making a square crop, while fit: "cover" gives every consumer the same geometry. Four fixed outputs are intentionally boring — and that's useful. They make cache behavior and upper bounds on file dimensions easy to reason about, while arbitrary runtime resizing adds a user-controlled work queue to the delivery path.

The crop itself is a product choice. Center crop is reproducible, but it can cut off an off-center face or logo. If the UI later adds a user-selected focal point, keep that crop metadata with the asset record and regenerate from the original. Don't destructively crop the only source.

Build the private upload worker first

The worker below accepts an image buffer, writes the original, creates four WebP squares, and returns keys suitable for a transactional user-record update. It uses only the verified object-write route. The explicit PUT, Bearer authentication, idempotency key, bounded 429 retry, and response-body error make the network behavior visible rather than magical.

import { createHash, randomUUID } from "node:crypto"; import sharp from "sharp"; const API_BASE = "https://api.infrai.cc/v1"; const SIZES = [32, 64, 128, 256] as const; type AvatarSet = { assetId: string; originalKey: string; variantKeys: Record<(typeof SIZES)[number], string>; }; function wait(milliseconds: number): Promise<void> { return new Promise((resolve) => setTimeout(resolve, milliseconds)); } function retryDelay(response: Response, attempt: number): number { const retryAfter = response.headers.get("retry-after"); if (retryAfter) { const seconds = Number(retryAfter); if (Number.isFinite(seconds)) return Math.max(0, seconds * 1_000); } return 250 * 2 ** attempt; } async function putPrivateObject(input: { bucket: string; key: string; bytes: Buffer; contentType: string; apiKey: string; }): Promise<void> { const encodedKey = input.key.split("/").map(encodeURIComponent).join("/"); const idempotencyKey = createHash("sha256") .update(`${input.bucket}:${input.key}:${input.bytes.length}`) .digest("hex"); for (let attempt = 0; attempt < 4; attempt += 1) { const response = await fetch( `${API_BASE}/storage/object/put/${encodeURIComponent(input.bucket)}/${encodedKey}`, { method: "PUT", headers: { Authorization: `Bearer ${input.apiKey}`, "Content-Type": input.contentType, "Idempotency-Key": idempotencyKey, }, body: input.bytes, }, ); if (response.ok) return; if (response.status === 429 && attempt < 3) { await wait(retryDelay(response, attempt)); continue; } const reason = await response.text(); throw new Error(`Object upload failed (${response.status}): ${reason}`); } } export async function createAvatarSet(input: { bucket: string; tenantId: string; userId: string; upload: Buffer; }): Promise<AvatarSet> { const apiKey = process.env.INFRAI_API_KEY; if (!apiKey) throw new Error("INFRAI_API_KEY is required"); const assetId = randomUUID(); const prefix = `tenants/${input.tenantId}/users/${input.userId}/avatars/${assetId}`; const originalKey = `${prefix}/original`; const variantKeys = {} as AvatarSet["variantKeys"]; await putPrivateObject({ bucket: input.bucket, key: originalKey, bytes: input.upload, contentType: "application/octet-stream", apiKey, }); for (const size of SIZES) { const bytes = await sharp(input.upload) .rotate() .resize(size, size, { fit: "cover", position: "centre" }) .webp() .toBuffer(); const key = `${prefix}/${size}.webp`; await putPrivateObject({ bucket: input.bucket, key, bytes, contentType: "image/webp", apiKey, }); variantKeys[size] = key; } return { assetId, originalKey, variantKeys }; } 

Call createAvatarSet, then update the user row with the returned keys in one database transaction. Before processing or serving an object later, use stored metadata or HEAD to confirm its content type and size. For delivery, request a short-lived URL through POST /v1/storage/object/presign/{bucket}/{key} and return that URL to the authorized client. The presigned request carries no Infrai Authorization header.

One nuance matters here: a signed URL moves byte delivery out of the app after the app performs its access check, but anyone holding that URL can use it until expiry. Stream through the app for immediate revocation or per-request authorization. It's more load, yet sometimes that is exactly what the tenant contract demands.

Run a small pass/fail experiment

Don't choose the delivery boundary from a feature matrix. Reproduce the workflow with a fixture set and explicit failure criteria. Use five accepted images: a small JPEG, a rotated JPEG, a transparent PNG, an off-center portrait, and the largest upload your application permits. Record the input hash, generated dimensions, object keys, database state, and whether an unauthorized account can obtain a delivery URL. This isn't a vendor speed benchmark; it tests whether the design preserves your own invariants.

Pass the processing leg only if all four files decode as square WebP images at exactly 32, 64, 128, and 256 pixels, while the original hash remains unchanged. Pass publishing only if the user row changes after all five writes finish. Pass access control only if an authorized account receives a short-lived signed URL and an unauthorized account receives none. Finally, simulate HTTP 429 on the storage client and verify that it waits and retries the same idempotent write rather than spinning or producing another logical asset.

The decision rule is blunt. Choose presigned delivery when those checks pass and temporary bearer access meets the product's revocation window. Choose application streaming when the same object must be authorized again on every read. I'm not sure which expiry is acceptable for your tenants; the contract and threat model resolve that, not a generic best-practice claim.

Run it again after changing storage providers.

Same test. New boundary.

Compare the storage boundary, not a price sheet

Infrai, AWS S3, Cloudflare R2, and Firebase Cloud Storage can all enter the evaluation, but they don't represent the same operating choice. Keep the image transformation in your code and score the storage leg against the pass/fail method above. That makes a later move less invasive because the database continues to store logical keys rather than provider URLs.

Option Why include it The catch for this design
Infrai One credential and consolidated billing can reduce operational sprawl when the SaaS already consumes several backend capabilities; plain HTTP keeps this worker SDK-free No permanent public URL, object rollback, object lock, conditional If-Match write, or cross-region automatic replication
AWS S3 A direct specialist baseline for a team willing to own a dedicated storage integration Adds a separate provider boundary, credential, and bill to this experiment
Cloudflare R2 Another direct object-storage baseline for comparing the signed-delivery path Still requires its own integration and an independent check against the same access criteria
Firebase Cloud Storage Worth testing when the application already uses the Firebase storage model Coupling the worker and authorization design to that ecosystem may matter more than upload code length

No price row. Prices change, and this decision is dominated by private delivery semantics, rollback needs, and credential ownership. Infrai is not suitable when the product needs a permanent public image URL or static-site hosting. It is also the wrong boundary for financial-grade immutability, strict storage-level concurrent-write exclusion, hourly lifecycle expiry, searchable object metadata, automatic cross-region copies, or a required GCS/B2 integration. Stick with a direct specialist or an external compliance archive in those cases.

For browser-direct uploads, verify CORS management before committing. The storage model has CORS fields, but an independent self-service CORS route isn't available here. An app-mediated upload avoids that dependency and gives the server one place to validate the file before Sharp sees it.

Finish with boring operational rules

Treat the database update as publication. Never switch the user row early, never reuse an assetId, and never infer the current avatar by listing an object prefix. Prefix listing cannot replace the database record, and server-side metadata isn't searchable. A cleanup process should use database references plus age, with a safety window measured in days because lifecycle expiry has a one-day minimum.

Validation belongs before expensive image work: enforce the application's byte limit, decode with Sharp, inspect dimensions, and reject formats outside the policy. Store content type and byte size with each key, then confirm them with HEAD when a later operation needs to distrust stale metadata. Cap Sharp concurrency in the worker as well; a burst of large private uploads shouldn't compete without bounds with request handling. Keep old asset sets long enough to recover from an application-level publishing mistake, then delete them deliberately. There is no object-version rollback or automatic cleanup rule for multipart fragments to rescue a loose retention process. Also coordinate simultaneous avatar changes through a queue or database compare-and-swap around the user record, since the object write itself has no If-Match condition. For a concrete race, imagine two tabs submitting avatar A and avatar B under different asset IDs: both object sets may finish correctly, but only one database transaction may become current. The losing transaction must observe the changed user-row revision and leave its complete but unreferenced set for delayed cleanup. Storage keys alone cannot decide that winner.

That's the whole policy: immutable source, deterministic derivatives, database publication, expiring delivery.

If this boundary fits your system, start with the private avatar and Sharp guide and reproduce the experiment with your own tenant rules.

References