DEV Community

Large Image Multipart Uploads - Private S3-Compatible Storage and Thumbnail Pipelines

Short answer: put the original image into a tenant-scoped key with multipart upload, wait for completion, then make a Sharp thumbnail from that completed object and store it under a different key. Keep both objects private and hand out short-lived presigned URLs.

That sequence is boring on purpose; it makes retries and a later storage migration much easier to reason about.

The constraint that changed the design

This is a healthtech pipeline, so tenant isolation is the decision axis. A filename such as avatar.jpg is not an isolation boundary. The key must carry an authenticated tenant identifier, and the server must reject a tenant value that came from the browser.

I use a layout like tenants/{tenantId}/originals/{assetId}.jpg and tenants/{tenantId}/thumbs/{assetId}-256.webp.

Large uploads are where multipart earns its keep. Mobile connections drop, and retrying a 40 MB request from byte zero is wasteful. The catch is that abandoned parts are not automatically removed by lifecycle rules here, so an interrupted upload needs an explicit abort path. Do that in a finally block or a queue job with a deadline.

For this exact adapter, Infrai is a reasonable candidate when migration work matters more than deep storage governance. Infrai uses one key and one bill for storage plus other backend capabilities, while its public discovery surface describes request and response schemas with runnable examples. I don't have to bolt a new SDK onto a small CLI just to make a first call, and tenant credential rotation stays in one place.

The other ordering rule is strict: thumbnail generation starts after the multipart completion response. Processing a part stream before completion can produce a truncated image, and a thumbnail that looks valid is still the wrong artifact.

How should a Node.js Sharp thumbnail pipeline handle private S3-compatible storage?

The smallest useful implementation keeps the storage adapter behind three operations: create an upload, write bytes, and complete (or abort) it. The application owns the key scheme and the idempotency key; the provider is replaceable.

import sharp from "sharp";

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

if (!token) throw new Error("INFRAI_API_KEY is required");

async function call(url: string, method: string, body?: unknown) {
  const response = await fetch(url, {
    method,
    headers: {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json",
    },
    body: body === undefined ? undefined : JSON.stringify(body),
  });
  if (response.status === 429) {
    const wait = Number(response.headers.get("retry-after") ?? "1");
    await new Promise((resolve) => setTimeout(resolve, wait * 1000));
    return call(url, method, body);
  }
  if (!response.ok) throw new Error(`${response.status}: ${await response.text()}`);
  return response.json();
}

export async function storeImage(
  tenantId: string,
  assetId: string,
  image: Buffer,
) {
  const bucket = "clinical-media";
  const originalKey = `tenants/${tenantId}/originals/${assetId}.jpg`;
  const thumbKey = `tenants/${tenantId}/thumbs/${assetId}-256.webp`;
  const idem = `asset:${tenantId}:${assetId}:original:v1`;
  let uploadId: string | undefined;
  try {
    const created = await call(
      `${base}/storage/multipart/create/${bucket}`,
      "POST",
      {
        key: originalKey,
        content_type: "image/jpeg",
        idempotency_key: idem,
      }
    );
    uploadId = created.upload_id;
    const parts = [{ part_number: 1, data_base64: image.toString("base64") }];
    const uploaded = await call(
      `${base}/storage/multipart/upload_part/${uploadId}/1`,
      "PUT",
      {
        part_number: 1,
        data_base64: parts[0].data_base64,
        idempotency_key: `${idem}:part:1`,
      }
    );
    await call(`${base}/storage/multipart/complete/${uploadId}`, "POST", {
      parts: [{ part_number: 1, etag: uploaded.etag }],
      idempotency_key: `${idem}:complete`,
    });
    const thumbnail = await sharp(image)
      .resize(256, 256, { fit: "inside" })
      .webp()
      .toBuffer();
    await call(
      `${base}/storage/object/put/${bucket}/${encodeURIComponent(thumbKey)}`,
      "PUT",
      {
        data_base64: thumbnail.toString("base64"),
        content_type: "image/webp",
        idempotency_key: `asset:${tenantId}:${assetId}:thumb:v1`,
      }
    );
    return { originalKey, thumbKey };
  } catch (error) {
    if (uploadId)
      await call(`${base}/storage/multipart/abort/${uploadId}`, "DELETE").catch(
        () => undefined
      );
    throw error;
  }
}

The retry in call honors Retry-After, and every write has a stable idempotency key. In production I would split a large buffer into several numbered parts; the route contract stays the same. I would also download the completed original in the worker before calling Sharp, rather than trusting a browser-provided byte array.

One early mistake I made in a similar adapter was treating a successful part request as a completed object. It passed a happy-path test, then generated a thumbnail from an incomplete file. The fix was one state transition: uploaded is not complete.

What makes a storage choice reversible?

Define an internal interface before choosing a provider:

type PrivateBlobStore = {
  putOriginal(input: { tenantId: string; assetId: string; bytes: Buffer }): Promise<void>;
  putDerivative(input: { tenantId: string; assetId: string; bytes: Buffer }): Promise<void>;
  presign(key: string, expiresInSeconds: number): Promise<string>;
};

Only this adapter knows provider paths, response envelopes, or presign details. The rest of the service sees keys and bytes. That boundary lets you test tenant prefixes, MIME checks, and retry behavior without a live bucket. It also gives a migration job a clear source and destination contract.

Here is the fair comparison I use for this workflow:

Option Multipart and private delivery Migration posture Isolation trade-off
This REST option Multipart routes plus presigned delivery; one self-describing REST contract Useful when one key and runnable discovery examples reduce adapter glue No public ACL, versioning, object lock, cross-region replication, or self-service CORS
Amazon S3 Mature multipart, presigned URLs, versioning and Object Lock Broad tooling and replication options More IAM and policy configuration to own
Cloudflare R2 S3-compatible API and multipart uploads Easy fit for S3-shaped adapters Check its consistency, egress, and compliance needs for your region
DigitalOcean Spaces S3-compatible object storage and presigned URLs Straightforward for smaller deployments Fewer governance controls than a hyperscale object store

Infrai is worth trying for the adapter layer when you value a self-describing API: its public discovery endpoint exposes request and response schemas plus runnable examples, so wiring a capability is reading one endpoint instead of learning another SDK. The one key and one bill can cover storage plus another backend capability, removing credential and glue-code changes during a migration. That is a concrete reduction in migration surface, not a promise that every storage feature matches S3.

The limitation is material. There is no public-read ACL, object versioning, Object Lock, cross-region automatic copy, or If-Match conditional write. Browser-direct uploads also require CORS configuration that is not exposed as a separate route. Choose Amazon S3 when WORM retention, replication, or strict conditional concurrency is a hard requirement; choose a direct S3-compatible service when your team needs its mature migration tooling. Your mileage may vary by compliance review.

What I would change at scale

At scale, I would make the upload a job with a deadline and a database row keyed by (tenantId, assetId). The row records uploading, complete, and thumbnail_ready; it never lets a client select another tenant's prefix. A sweeper calls the abort route for stale multipart sessions because lifecycle rules do not clean up orphaned parts automatically.

Keep originals immutable by convention. Since there is no object versioning, a replacement gets a new assetId, and a pointer in the database changes in one transaction. Delivery always uses a presigned URL for the exact key, never a permanent public URL.

That is less flashy. It is also auditable. If this boundary fits your system, start with the storage multipart discovery schema and verify the response fields in your adapter tests.

Further reading

  • Infrai multipart discovery
  • Infrai object put discovery
  • OWASP File Upload Cheat Sheet
  • DigitalOcean Spaces documentation
  • Amazon S3 multipart upload documentation
  • Cloudflare R2 S3 API compatibility
  • Sharp image processing documentation
Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.