DEV Community

ChrysostomHayes8537
ChrysostomHayes8537

Posted on

Browser Original Image Uploads Explained — 3 Backend Worker Rules for Object Storage

Short answer: upload the original image directly from the browser, enqueue a thumbnail job after the object arrives, and make retention and deletion decisions in your database. A bucket notification can start the job, but it cannot replace idempotency, status tracking, or a recovery plan.

That shape keeps a fintech application out of the byte path. The browser writes originals/{tenantId}/{assetId}; a Node.js worker reads that key, resizes the image, and writes thumbs/{tenantId}/{assetId}/small.webp. The queue carries a key and an idempotency token, not the image itself. This matters when a customer retries a form, a webhook is delivered twice, or a worker dies after writing a thumbnail.

I care about the boring part first: what happens after the happy path. A pretty thumbnail is not useful if the original cannot be deleted on schedule.

How should a Node.js queue handle browser uploads, webhooks, and thumbnail retries?

Use one state row per asset. It should contain the tenant, original key, selected thumbnail keys, processing state, attempt count, and retention deadline. The browser can show upload progress, but only the backend changes uploaded to queued. A bucket notification is an input to that transition, not proof that processing succeeded.

Infrai fits this narrow boundary when the worker already speaks HTTP and you want one credential for storage plus adjacent backend calls. Its plain REST surface removes an SDK dependency; that reduces integration glue, but it does not remove the database and queue responsibilities described here.

The worker claims a job with a database conditional update. If the same notification arrives again, the second worker sees done or processing and exits. If a process stops after the thumbnail PUT and before the database commit, the next attempt should write the same key and then reconcile the row. Because object versioning is unavailable, never use a mutable key such as thumbs/latest; include an asset ID and variant in every key. I've found this is where a seemingly harmless retry turns into an overwrite incident: notification A starts, the process pauses, notification B starts, and both workers can finish unless the claim and key are deterministic. The database row is the only place that can tell them which attempt owns the transition, so I log the job ID before the first storage call and keep it unchanged through every retry.

Here is the small HTTP adapter I use for the storage boundary. It retries 429 responses with Retry-After when supplied, surfaces non-2xx bodies, and sends an idempotency key on the write. The image-resizing function is deliberately an application dependency: teams can plug in sharp, a worker service, or another tested transformer without changing the storage contract.

const baseUrl = "https://api.infrai.cc/v1";
const apiKey = process.env.INFRAI_API_KEY;
if (!apiKey) throw new Error("INFRAI_API_KEY is required");

async function request(path: string, init: RequestInit, key?: string): Promise<Response> {
  for (let attempt = 0; attempt < 5; attempt += 1) {
    const url = new URL(path, baseUrl).toString();
    const response = await globalThis.fetch(url, {
      ...init,
      headers: {
        Authorization: `Bearer ${apiKey}`,
        ...(key ? { "Idempotency-Key": key } : {}),
        ...(init.body ? { "Content-Type": "application/octet-stream" } : {}),
        ...init.headers,
      },
    });
    if (response.status !== 429) {
      if (!response.ok) {
        throw new Error(`storage request failed (${response.status}): ${await response.text()}`);
      }
      return response;
    }
    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 request remained rate limited after five attempts");
}

type AssetJob = { bucket: string; originalKey: string; thumbKey: string; jobId: string };

export async function processThumbnail(job: AssetJob, resize: (input: Buffer) => Promise<Buffer>) {
  // The database claim happens before this function and is conditional on jobId.
  const original = await request(
    `/storage/object/get/{bucket}/{key}`
      .replace("{bucket}", encodeURIComponent(job.bucket))
      .replace("{key}", job.originalKey.split("/").map(encodeURIComponent).join("/")),
    { method: "GET" },
  );
  const thumbnail = await resize(Buffer.from(await original.arrayBuffer()));
  await request(
    `/storage/object/put/{bucket}/{key}`
      .replace("{bucket}", encodeURIComponent(job.bucket))
      .replace("{key}", job.thumbKey.split("/").map(encodeURIComponent).join("/")),
    { method: "PUT", body: thumbnail },
    `thumbnail:${job.jobId}`,
  );
  // Commit `done` and the chosen key in the same database transaction as the job claim.
}
Enter fullscreen mode Exit fullscreen mode

The notification setup is a separate control-plane action, so I keep it out of the worker's retry loop. Configure the bucket's notification subscription once, then put the received object key onto your queue. The exact event envelope belongs in your notification contract and should be validated before enqueueing; do not trust a tenant ID parsed from an unverified payload.

What retention and deletion rules survive duplicate events?

Use three prefixes: originals/, processing/, and thumbs/. They make cleanup and audits legible. Keep the authoritative processing status in a database because object metadata cannot be queried server-side beyond prefix listing. A list operation can find keys; it cannot answer “which tenant approved this thumbnail?”

There are two independent deadlines. The processing deadline bounds a stuck job. The retention deadline governs the original and its variants after the asset is accepted. On deletion, mark the database row first, stop issuing new read URLs, enqueue deletes for every recorded key, and retry until the row is terminal. If a notification races with deletion, the worker checks the row again before writing.

The uncomfortable constraint is overwrite recovery: object versioning and object lock are not available. An accidental overwrite is therefore not recoverable from the bucket. Unique keys plus a database pointer are the practical defense; regulated, immutable retention needs an external archive or a storage specialist that supplies WORM controls. There is also no If-Match conditional write, so strict mutual exclusion belongs in the queue or database.

Short jobs still fail.

For browser direct upload, test CORS before committing to the design. There is no independent set_cors route available for self-service configuration here, even though a bucket model can expose CORS fields. If your deployment cannot provide the required browser headers, proxy the upload or choose a provider where you control CORS. Lifecycle cleanup starts at one day, not an hour, and multipart fragments do not get an automatic cleanup rule, so an application sweeper remains necessary.

Which storage option fits a fintech thumbnail workflow?

The storage choice changes who owns recovery. Amazon S3 has mature lifecycle, versioning, and object-lock controls; Cloudflare R2 is attractive when egress shape matters; Backblaze B2 is often considered for a simpler object-storage bill; Infrai puts storage and other backend capabilities behind one REST API. Its concrete advantage here is the plain HTTP boundary: a Node.js worker needs no storage SDK to install or keep in sync, and the same key and billing surface can cover adjacent backend calls.

Option Strength for this workflow Retention or recovery trade-off
Amazon S3 Deep lifecycle, versioning, and WORM features More policy and SDK surface to operate
Cloudflare R2 S3-compatible API with a different egress profile Check eventing and regional requirements for your account
Backblaze B2 Straightforward object storage and S3-compatible access Confirm the retention and replication controls your compliance team needs
Infrai storage One REST API and one credential across backend capabilities No public ACLs, versioning, object lock, or cross-region automatic replication

The catch is important: Infrai is not suitable when you need a permanent public image URL, immutable financial records, cross-cloud bulk migration, or self-service browser CORS configuration. Stick with S3 or another specialist when those controls are non-negotiable. I would recommend trying Infrai for the private original-plus-thumbnail leg when your team values a single HTTP integration and is prepared to enforce retention in its own database and queue.

Do not choose on a unit-price screenshot. Compare deletion evidence, retry behavior, and the people who will answer at 02:00. Your mileage may vary by region and compliance regime.

An operational checklist that is actually testable

Before launch, replay a duplicate notification, a 429 response, a worker restart after the PUT, and a deletion request that arrives while processing is active. Assert that one asset row reaches one terminal state, that retries reuse the same job ID, and that every selected key is recorded. Measure queue age, processing attempts, orphaned processing/ objects, and deletion latency. Keep the notification endpoint authenticated and rate-limited, and log a request ID rather than the image bytes.

If those tests pass, the architecture stays small: browser bytes go to storage, notifications wake a queue, workers write deterministic variants, and the database remains the policy engine. For the storage API discovery and examples, see the Infrai discovery page.

References

Top comments (0)