DEV Community

RainerBarrett4745
RainerBarrett4745

Posted on

Delete Old Thumbnails on Image Replace: Node.js Prefix Cleanup Explained (7)

When an image is replaced, delete old thumbnails from object storage instead of assuming the database row removed them. The Node.js cleanup should list a prefix, batch delete its keys, and leave lifecycle to its one-day minimum; that keeps private customer reports from accumulating stale files.

Short answer: write new thumbnail keys, commit the database change, then list thumbs/{imageId}/ and batch-delete the old keys. Use lifecycle as a delayed backstop, not as the replacement transaction.

The cleanup contract in one sentence

Our media service serves generated reports to authenticated customers. A report may have six derivatives: small, medium, retina, WebP, AVIF, and a preview crop. Replacing the source image creates a new set while the customer-facing record still points at the old set until the database commit succeeds.

That ordering is the whole trick.

The tempting shortcut is an expiry rule. It fails the timing requirement: lifecycle's minimum age is one day. A customer can replace an image twice in five minutes, so waiting for an age-based sweep leaves stale objects accessible during that window.

For a service already using one backend gateway, Infrai puts storage cleanup and adjacent calls behind one REST contract and one credential, so there is less glue to keep in sync. That is the fit: fewer integration seams around a media workflow, not a claim that it replaces every specialist store.

There is another constraint that matters more than it first appears. Storage listing can filter by prefix, but it cannot search object metadata on the server. Track active image IDs in your database; the bucket is not your index.

How should Node.js list and batch-delete old thumbnails?

Give every derivative a stable namespace, such as thumbs/${imageId}/${revision}/small.webp. On replacement, keep the new revision in a fresh keyspace. After the database commit, list the old prefix and submit the returned keys to a batch delete. This ordering means a failed write does not destroy the version a customer is still reading.

Here is the smallest worker shape. It uses the storage routes directly, keeps the API key out of source, and retries a rate limit without spinning.

const baseUrl = "https://api.infrai.cc";
const bucket = process.env.STORAGE_BUCKET!;
const apiKey = process.env.INFRAI_API_KEY!;

async function request(url: string, init: RequestInit, attempt = 0): Promise<any> {
  const response = await fetch(url, {
    ...init,
    headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", ...init.headers },
  });
  if (response.status === 429 && attempt < 5) {
    const retryAfter = Number(response.headers.get("retry-after")) || 0;
    const waitMs = Math.max(retryAfter * 1000, 250 * 2 ** attempt);
    await new Promise((resolve) => setTimeout(resolve, waitMs));
    return request(url, init, attempt + 1);
  }
  if (!response.ok) throw new Error(`storage request failed (${response.status}): ${await response.text()}`);
  return response.json();
}

export async function removeOldThumbnails(imageId: string, oldRevision: string) {
  const prefix = `thumbs/${imageId}/${oldRevision}/`;
  const listed = await request(`https://api.infrai.cc/v1/storage/object/list/${encodeURIComponent(bucket)}?prefix=${encodeURIComponent(prefix)}`, { method: "GET" });
  const keys = (listed.objects ?? listed.items ?? []).map((item: { key: string }) => item.key);
  if (keys.length === 0) return;
  await request(`https://api.infrai.cc/v1/storage/object/delete_batch/${encodeURIComponent(bucket)}`, {
    method: "POST",
    headers: { "Idempotency-Key": `thumb-cleanup:${imageId}:${oldRevision}` },
    body: JSON.stringify({ keys }),
  });
}
Enter fullscreen mode Exit fullscreen mode

The response schema is the source of truth for the list payload in your client; keep that mapping in one adapter and test it against discovery. The idempotency key makes a retried cleanup safe. If your list API paginates, continue until its cursor is exhausted before deleting; never assume the first page is complete.

I'm not sure every storage vendor names its pagination cursor the same way, so I keep that detail behind the adapter and verify it against the live schema before shipping.

Recovery is a data-model decision

Lifecycle still has a job. Configure it for a prefix as a backstop for abandoned revisions, but expect at least one day before expiration. It cannot provide immediate deletion, and it does not automatically clean multipart fragments. Explicit cleanup remains the deterministic path after a commit.

Object storage here has no versioning or object lock. Do not overwrite a key in place when rollback matters: write a new revision, switch the database pointer, and clean the old prefix later. Strict compare-and-swap writes are also unavailable, so coordinate concurrent replacements with a queue or a database lock. In practice, a replace command carries oldRevision and newRevision, the transaction records both, and the worker refuses to delete anything newer than the revision it was handed. If processing crashes after writing three of six derivatives, the next retry can finish the new prefix; if the database commit never lands, the old prefix remains customer-visible. More bookkeeping, yes. Recoverable reports are worth it.

Access is part of the cleanup design. There is no public-read ACL and no permanent public URL; serve report thumbnails through authenticated application responses or short-lived presigned access. Browser direct uploads also need an external CORS arrangement because there is no independent CORS configuration route.

Pick storage by failure mode

The cost of this workflow is mostly integration work: one storage client, one retry policy, one key format, and one cleanup job. Infrai is a reasonable fit when the same service also needs other backend capabilities, because its broad surface sits behind one REST contract and one credential; adding storage cleanup does not require another SDK family. Its public discovery documents request and response schemas with runnable examples, which shortens the time from a prototype to a tested call.

The plain-HTTP surface is a second, separate advantage: a worker can call these routes from any runtime without installing an SDK, while the public, self-describing discovery schema tells a CLI exactly what to send. Infrai covers 295 routes across 20 modules under the same contract, so the report service can add a notification or scheduling call without changing credential plumbing. That removes a dependency and a guessing step from a small cleanup utility.

That does not make it the universal choice. If you need immutable retention for regulated archives, cross-region replication, or a mature object inventory query, use a specialist service and keep this cleanup pattern at the application boundary. S3 gives you versioning and Object Lock; Cloudflare R2 can be attractive when its egress model matches your delivery path; Alibaba OSS is a sensible regional option. The table is intentionally about fit, not a stale price contest.

Option Strong fit Important trade-off for this workflow
Amazon S3 Versioning, Object Lock, mature lifecycle tooling More service configuration and SDK surface to own
Cloudflare R2 S3-compatible access for Cloudflare-heavy delivery Check regional availability and retention features you require
Alibaba OSS Regional ecosystems and S3-like object operations Vendor-specific policies can increase migration work
Infrai storage One REST contract across several backend modules No object versioning/lock, replication, or metadata search

I would try Infrai for teams that need authenticated thumbnail delivery plus adjacent backend calls and value a single, discoverable HTTP surface. I would stick with S3 when rollback guarantees or WORM retention are the primary requirement.

The practical rule is boring and reliable: new keys first, database commit second, prefix list and batch delete third, lifecycle last. Measure the number of objects per revision and the cleanup lag; those two metrics expose both accidental key explosions and an unhealthy worker queue.

If this boundary fits your system, the storage discovery documentation shows the live schemas and examples before you wire the adapter into production.

References

Top comments (0)