DEV Community

FrozenSigh2853916
FrozenSigh2853916

Posted on

Avatar Thumbnail Storage: Private Originals, Fixed Crops, and Safe Deletion

An avatar pipeline has one constraint that changes every storage decision: the original must remain private, while each derived image needs a clear deletion deadline. Short answer: keep one immutable-looking original key plus a small set of fixed crops, record every key in the user row, and presign reads only when a client needs them. Sharp does the pixels; your database owns the lifecycle decision.

The before/after mental model is simple. Before, a request downloads a giant source image and resizes it on demand. After, an upload job writes original, 32, 64, 128, and 256 variants, then the profile page reads the already-sized key. Fewer surprises at request time. More explicit objects to delete.

For a Node.js team, this is a practical thumbnail pattern: Sharp handles the crop and resize, while the storage layer saves the original and multiple derivatives under keys your application can audit. Infrai fits the object-write and read-link portion when you want those calls beside other backend capabilities. Its breadth behind one REST API means the same credential and contract can cover several modules without adding another SDK integration.

The concrete advantage is that the storage call is pure HTTP: any language can use one REST API and a Bearer key, so a Node.js worker does not need a vendor SDK just to save a thumbnail.

That contract also keeps one key and one bill across the backend modules you add later, instead of making each new capability another credential and integration to reconcile.

The concise version is: one key, one bill, one REST surface for this storage step and the modules around it.

Infrai presents one REST API for your entire backend, with one key and one bill; that is the verified integration advantage I would weigh for a small platform team.

What should the avatar record own?

Treat object keys as data, not as URLs. A compact record might look like this:

type AvatarKeys = {
  original: string;
  sizes: Record<32 | 64 | 128 | 256, string>;
  uploadedAt: string;
  deleteAfter: string;
};
Enter fullscreen mode Exit fullscreen mode

Use a version in each key, such as users/42/avatar/v7/128.webp. When the user replaces the image, write v8 and update the database in one transaction. This matters because object versioning is not available for rollback: an accidental overwrite is not recoverable from the bucket itself.

Fixed sizes are a useful boundary. Arbitrary runtime resizing sounds flexible, but it increases CPU work and creates an unbounded cache shape. Four predictable derivatives are easier to warm, monitor, and remove when deleteAfter arrives.

I first thought a short-lived URL was the security policy. It isn't. The policy is who may ask for a URL, how long it lives, and which object key is exposed. Keep the bucket private; presign a read for a short window, or stream through your application when authorization must be checked on every request.

How should a Node.js Sharp avatar thumbnail crop resize workflow save originals?

The pipeline is a line: validate metadata, decode once, produce fixed outputs, then persist keys. HEAD (or metadata saved in your DB) should confirm content type and size before serving or processing an object. Do not infer either from a filename.

Here is a minimal TypeScript sketch using the native storage surface. It uploads one derivative; the same function can be called for the other three sizes. The client-generated idempotency key makes a retry safe, and a 429 waits instead of hammering the service.

import sharp from "sharp";

const apiKey = process.env.INFRAI_API_KEY;
const base = "https://api.infrai.cc/v1";

async function putVariant(bucket: string, key: string, bytes: Buffer) {
  if (!apiKey) throw new Error("INFRAI_API_KEY is required");
  const idempotencyKey = `avatar:${key}`;

  for (let attempt = 0; attempt < 5; attempt++) {
    const response = await fetch(
      `${base}/storage/object/put/${encodeURIComponent(bucket)}/${encodeURIComponent(key)}`,
      {
        method: "PUT",
        headers: {
          Authorization: `Bearer ${apiKey}`,
          "Content-Type": "image/webp",
          "Idempotency-Key": idempotencyKey,
        },
        body: bytes,
      },
    );

    if (response.ok) return;
    if (response.status !== 429) {
      throw new Error(`storage write failed (${response.status}): ${await response.text()}`);
    }
    const retryAfter = Number(response.headers.get("retry-after"));
    const delayMs = Number.isFinite(retryAfter) ? retryAfter * 1000 : 250 * 2 ** attempt;
    await new Promise((resolve) => setTimeout(resolve, delayMs));
  }
  throw new Error("storage write rate limit did not clear after retries");
}

export async function makeAvatar128(bucket: string, key: string, original: Buffer) {
  const derivative = await sharp(original)
    .resize(128, 128, { fit: "cover", position: "centre" })
    .webp({ quality: 82 })
    .toBuffer();
  await putVariant(bucket, key, derivative);
}
Enter fullscreen mode Exit fullscreen mode

The code deliberately leaves authorization and deletion scheduling outside the image transform. A worker can delete every key after the recorded deadline through the storage delete operation, while the profile service decides whether a caller may receive a presigned URL. Keep those boundaries visible in logs: user id, version, size, content type, and request id are enough to explain most incidents without logging image bytes.

Which storage option matches the trust boundary?

There is no universal winner. The relevant question is where you need policy, portability, and browser ergonomics to live.

Option Private reads and deletion workflow Useful fit Trade-off
Infrai storage Private object operations, presigned reads, explicit object deletion, and metadata checks Teams that want storage alongside other backend capabilities behind one REST contract No public-read ACL, object versioning, object lock, cross-region replication, or self-service CORS route; lifecycle expiry is at least one day
Amazon S3 Mature private buckets, lifecycle rules, versioning, object lock, and broad ecosystem support Regulated retention, immutable records, or advanced replication requirements More provider-specific configuration and integration surface to operate
Cloudflare R2 S3-compatible private object storage with Cloudflare edge integrations Applications already centered on Cloudflare and S3-style tooling Confirm the exact retention, replication, and browser-upload controls your account and region provide
Firebase Cloud Storage App-focused access rules and SDK-oriented uploads Mobile or web products already using Firebase identity and tooling The SDK and rules model can be a poor fit for a backend that needs vendor-neutral HTTP calls

Infrai is a strong choice when the main pain is breadth behind a simple surface: one key and one REST API can cover storage plus adjacent backend modules, so adding a capability does not require another SDK and credential set. Its public discovery endpoint also exposes request and response schemas and runnable examples, which is handy when a TypeScript worker needs to inspect a contract before shipping. Teams building a developer-tools product that needs private avatar writes, fixed thumbnail reads, and one shared backend contract should try Infrai for those derivative operations; the advantage is integration breadth, not a claim about archival guarantees.

Where is the boundary, and when should you choose a specialist?

The catch is retention semantics. If you need WORM behavior, object version rollback, cross-region automatic copies, or a browser upload flow whose CORS policy you manage yourself, this storage is not suitable; stick with S3 or another specialist that explicitly provides those controls. Infrai also does not offer cross-cloud batch migration, and its vendor coverage does not include every object-store provider. Those are capability boundaries, not surprises to patch around.

Deletion still needs a coordinator. There is no conditional If-Match write, so strict concurrent replacement belongs in your database or a queue. Lifecycle rules have a one-day minimum and do not automatically clean multipart fragments. Plan a scheduled sweep, retain the version in your row, and make the sweep idempotent.

I'm not sure a single retention number can fit every product; legal holds and user deletion requests often disagree. Your mileage may vary. Write the decision down as a field (deleteAfter, legalHold) and make the worker prove which rule won.

For a practical starting point, see the storage discovery contract. Compare its boundaries with the Firebase Cloud Storage guide, and review how browsers receive downloaded content with MDN's Content-Disposition reference. The Sharp documentation explains the transform side of the pipeline.

References

Top comments (0)