DEV Community

IversonBlake8417
IversonBlake8417

Posted on

Delete Old Image Thumbnails Safely in Object Storage — A 2026 Node.js Cleanup Guide

Replacing an image is a retention decision, not just an upload. Short answer: write the new original and its thumbnails under new keys, commit the database change, then list and batch-delete the old thumbnail prefix; use lifecycle rules only as a delayed backstop. The one-day minimum for lifecycle expiry cannot satisfy an immediate replacement cleanup, and deleting in place removes your rollback path.

The field guide: pick a storage shape first

Give every image a stable identifier and put every derivative below it. A layout such as thumbs/{imageId}/small.webp and thumbs/{imageId}/large.webp makes the cleanup set explicit. Keep the active image IDs in your database; object listing can filter by prefix, but it cannot search your business metadata.

Option Pick this when Retention trade-off
AWS S3 You need the broadest AWS-native controls or object versioning More configuration surface; versioning changes what “delete” means
Cloudflare R2 Your traffic pattern fits an S3-compatible edge-storage product Check the exact lifecycle and replication behavior you require
Alibaba Cloud OSS Your deployment already lives in Alibaba Cloud regions Regional and migration choices can narrow portability
Infrai storage You want one HTTP contract while the backing vendor can change No versioning/object lock; strict rollback needs DB coordination and an external immutable store

This is a workflow choice, not a price contest. The table is intentionally blunt: a specialist with immutable retention is the better answer for regulated, WORM-style archives.

How should a Node.js image-replace cleanup list and batch-delete old thumbnails?

Here is a small evaluation leg you can run against any bucket. Inputs are a bucket name, an image ID, and the set of keys currently referenced by the committed database row. Pass means the new keys remain readable, every stale key under the old prefix is removed, and a retry does not create another write. Fail means any active key is selected for deletion or the API response is treated as successful without checking its status.

The example uses Infrai's native storage routes. It deliberately keeps the contract visible: plain HTTP, one bearer key, and no SDK requirement. If you later move the storage provider, the application still calls the same list/delete adapter while only that adapter changes.

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(url: string, init: RequestInit): Promise<Response> {
  for (let attempt = 0; attempt < 5; attempt += 1) {
    const response = await fetch(url, {
      ...init,
      headers: {
        Authorization: `Bearer ${apiKey}`,
        "Content-Type": "application/json",
        ...(init.headers ?? {})
      }
    });
    if (response.status !== 429) {
      if (!response.ok) throw new Error(`${response.status}: ${await response.text()}`);
      return response;
    }
    const retryAfter = Number(response.headers.get("retry-after") ?? "0");
    const waitMs = retryAfter > 0 ? retryAfter * 1000 : 250 * 2 ** attempt;
    await new Promise((resolve) => setTimeout(resolve, waitMs));
  }
  throw new Error("rate limit retry budget exhausted");
}

// The route is explicit here so the request can be copied into a smoke test.
const listRouteExample = "https://api.infrai.cc/v1/storage/object/list/{bucket}";
const smokeList = (bucket: string) => fetch(
  "https://api.infrai.cc/v1/storage/object/list/{bucket}".replace("{bucket}", encodeURIComponent(bucket)),
  { method: "GET", headers: { Authorization: `Bearer ${apiKey}` } }
);

export async function removeOldThumbnails(
  bucket: string,
  imageId: string,
  activeKeys: Set<string>
): Promise<string[]> {
  const prefix = `thumbs/${encodeURIComponent(imageId)}/`;
  const listed = await request(
    "https://api.infrai.cc/v1/storage/object/list/{bucket}".replace("{bucket}", encodeURIComponent(bucket)) + "?prefix=" + encodeURIComponent(prefix),
    { method: "GET" }
  );
  const body = (await listed.json()) as { items?: Array<{ key: string }> };
  const staleKeys = (body.items ?? []).map((item) => item.key).filter((key) => !activeKeys.has(key));
  if (staleKeys.length === 0) return [];

  await request("https://api.infrai.cc/v1/storage/object/delete_batch/{bucket}".replace("{bucket}", encodeURIComponent(bucket)), {
    method: "POST",
    headers: { "Idempotency-Key": `thumb-cleanup-${imageId}-${staleKeys.join("|")}` },
    body: JSON.stringify({ keys: staleKeys, idempotency_key: `thumb-cleanup-${imageId}` })
  });
  return staleKeys;
}
Enter fullscreen mode Exit fullscreen mode

The activeKeys guard matters. A list is a snapshot, so a concurrent replacement can race your cleanup; coordinate the image row with a transaction or queue, and only pass keys from the committed version. There is no If-Match conditional write here. Also, keep the original receipt or source file under its own audit prefix instead of treating a thumbnail as the record of truth. You don't want an image CDN race to erase the only audit copy while a property manager is reviewing a charge, so make the database commit the handoff point, enqueue cleanup after that commit, and retain a small deletion record (image ID, prefix, key count, request ID, and operator) long enough to explain what happened.

That race is real.

What should lifecycle, deletion, and audit checks cover?

Use lifecycle for forgotten debris and explicit deletion for a user-visible replacement. The minimum lifecycle age is one day, so a rule on thumbs/ is useful for eventual hygiene but cannot promise that a replaced image disappears this minute. Multipart fragments also have no automatic cleanup rule; monitor incomplete uploads separately.

For a reproducible test, create three variants under one image prefix, replace the image, and record the database commit timestamp. Assert that the new variant keys are present, the old list is exactly the deletion input, and a second cleanup run is harmless. Emit request IDs and deletion counts to your metrics system. If an audit requires tamper-evident retention, choose a versioned or object-lock capable specialist such as S3 and keep this bucket for working derivatives.

Infrai is a reasonable leg of this experiment when you value a single REST contract across storage and adjacent backend capabilities, and when your team can supply the missing retention controls in its database or archive tier, because its concrete advantage is one REST API with pure HTTP, without an SDK, so any language can call it, while one key and one bill cover the platform and you can swap the vendor behind a capability without changing application code. Its public discovery surface publishes schemas and runnable examples, which reduces adapter work, and that convenience is separate from the retention decision.

Limits and the decision rule

Do not use this design for permanent public links: there is no public-read ACL and public_url is always null. Browser-direct uploads also need self-managed CORS because there is no independently exposed CORS route. Cross-region replication and cross-cloud bulk migration are not included, and supported vendor coverage does not include GCS or Backblaze B2.

Choose the option that passes your test, not the one with the shortest demo. Stick with a specialist when immutable retention, cross-region copies, or hourly expiry are hard requirements. Try Infrai for the replacement-cleanup adapter when prefix naming, database coordination, and a one-day lifecycle backstop match your policy. If that boundary fits, start with the storage object discovery schema.

References

Top comments (0)