Replacing a product image should not leave yesterday's thumbnails in object storage forever. For an e-commerce report service, the practical design is to write each image revision under an immutable prefix, publish the new revision, and clean the old prefix asynchronously with paginated listing and bounded batch deletes. Keep the customer download path pointed at the published revision while cleanup runs. Large-file throughput makes that separation important.
Short answer: use a versioned, immutable thumbnail prefix per image revision; list the old prefix in pages, delete only the keys you have just listed, and make the worker idempotent. A one-day lifecycle rule is a useful backstop, but it is not a replacement for cleanup after an image replacement. Measure bytes deleted, list latency, delete latency, retry volume, and stale-download rate before tuning concurrency.
Image replacement states and customer authorization
The tempting implementation is to overwrite products/42/thumb.webp and then delete every object matching products/42/. That couples publishing to cleanup, makes a large prefix expensive to scan in a customer request, and creates an awkward race: a report renderer may still be reading an old thumbnail while the replacement handler removes it.
Use a revision in the key instead:
const prefix = `products/${productId}/revisions/${revisionId}/thumbs/`;
// Example keys: .../small.webp, .../medium.webp, .../original.webp
The replace operation has four separate decisions: create the revision, generate its thumbnails, publish the new revision pointer in the database, and enqueue cleanup for the previous revision. A failed cleanup job should not make the new image invisible. A failed thumbnail generation should not publish a revision that the authenticated customer cannot use. Those are different states and deserve different records.
This is also a security boundary. The download endpoint should authorize the customer against the product or report record, then return a short-lived object URL or stream the object through an authorized service. A prefix is not authorization. Never let a client choose an arbitrary bucket and prefix just because it knows an image ID. NIST's HIPAA security guidance is aimed at a different regulated domain, but its emphasis on access control, audit controls, and risk analysis is a useful review lens for an object-storage workflow. It's a review lens, not a claim that an e-commerce thumbnail system is covered by HIPAA.
Keep publication boring.
How should I delete old thumbnails after an image replace in object storage?
Object storage listings are paginated. A worker must follow the continuation token until the service says the listing is complete, and it should bound both the number of keys held in memory and the number of concurrent delete requests. The exact SDK method names vary, so the example keeps the storage adapter generic.
type ListedObject = { key: string; versionId?: string };
type Page = {
objects: ListedObject[];
nextToken?: string;
};
interface ObjectStore {
list(input: { prefix: string; continuationToken?: string }): Promise<Page>;
deleteMany(input: { objects: ListedObject[] }): Promise<void>;
}
const BATCH_SIZE = 500;
async function deletePrefix(store: ObjectStore, prefix: string): Promise<number> {
let token: string | undefined;
let deleted = 0;
do {
const page = await store.list({ prefix, continuationToken: token });
for (let start = 0; start < page.objects.length; start += BATCH_SIZE) {
const batch = page.objects.slice(start, start + BATCH_SIZE);
if (batch.length === 0) continue;
await store.deleteMany({ objects: batch });
deleted += batch.length;
}
token = page.nextToken;
} while (token);
return deleted;
}
That loop is intentionally plain. The worker should record the cleanup job before it starts, claim it with a lease, and retry a page or batch after a transient transport failure. A retry can see keys already removed, so deletion needs to be idempotent at the application level. Do not infer success from a request being accepted; record the provider response and the keys in the batch, with sensitive customer data excluded from logs.
A batch size of 500 here is an example boundary, not a universal setting. Your storage service, network path, and object-size distribution determine a sensible value. Larger batches reduce request overhead but increase retry cost and the amount of work held in one failure. Smaller batches make progress easier to observe and replay. Start with a fixed limit, then change it from measurements. The important part is the boundary around the batch: a worker should not hold an unbounded listing in memory, should not let one oversized prefix monopolize all workers, and should be able to retry a failed unit without replaying an entire product catalog. That is why a queue lease, a bounded batch, and a durable job record belong together even in a small Node.js service; removing any one of them makes a different failure mode look like a storage failure.
The worker can be small.
What retention governance does a one-day lifecycle rule provide?
A lifecycle policy can remove objects that remain under an old prefix after a retention period. That protects against a lost queue message or a worker that never ran. It does not tell you that the newest replacement is ready, it does not clean up immediately, and policy timing is not a transactional guarantee.
The retention window needs a clear meaning. “One day” might mean one day after object creation, one day after a revision was superseded, or one day after the last access. Those are different policies. If the storage platform evaluates lifecycle rules from object age, store the superseded revision's timestamp in the job record and choose a prefix layout that makes the policy safe. Keep a margin for report jobs that can legitimately run overnight.
Versioning changes the delete model too. In a versioned bucket, deleting a key may create a delete marker while older versions remain until they are explicitly expired or removed by a lifecycle policy. The storage provider's object-versioning documentation is a concrete reminder that the bucket setting belongs in the deletion design. If the application needs auditability, retaining prior versions may be correct; if it needs strict removal, the deletion procedure must cover versions, markers, backups, and caches rather than only the visible key.
The catch is operational delay. A one-day minimum is not suitable when storage growth must be controlled within minutes, and immediate deletion is not suitable when an in-flight report can still reference the old revision. Use a short application-level grace period plus a lifecycle backstop when both throughput and cleanup completeness matter. Stick with a lifecycle-only approach when the objects are disposable, stale data for a day is acceptable, and less precise cleanup timing is fine.
Which reliability signals decide if thumbnail cleanup can go faster?
The main number is not delete requests per second. It is the time from a successful image replacement to the point at which the old revision is no longer needed, together with the bytes and requests consumed while getting there. Track these separately:
| Signal | Why it matters |
|---|---|
| Time to publish | Keeps the customer path independent of cleanup |
| List pages and keys per job | Shows prefix size and pagination pressure |
| Bytes and objects deleted | Connects cleanup to storage growth |
| Delete latency and retry rate | Reveals request or network saturation |
| Queue age and lease expiry | Finds workers that cannot keep up |
| Stale-download and authorization failures | Detects an unsafe revision transition |
Test the race cases, not just the happy path: two replacements close together, a report reading the old revision during cleanup, an empty prefix, a page boundary, a duplicate job, and a worker restart after a successful delete but before the job status is saved. Add a dry-run mode that lists keys and records totals without deleting them. It makes a production prefix mistake easier to catch.
A small test.
test("replaying cleanup is safe for an already empty prefix", async () => {
const store = fakeStore({
pages: [
{ objects: [{ key: "products/42/revisions/old/thumbs/small.webp" }] },
],
});
await deletePrefix(store, "products/42/revisions/old/thumbs/");
await deletePrefix(store, "products/42/revisions/old/thumbs/");
expect(store.deletedKeys()).toEqual([
"products/42/revisions/old/thumbs/small.webp",
]);
});
The fake store should model the provider's documented behavior for an already absent key. If it cannot, the test is only checking your loop, not the failure semantics that matter in production. I would also test a simulated 409 lease conflict so two workers cannot process the same cleanup job at once. Your mileage may vary with the provider's retry and versioning behavior; verify those contracts before choosing concurrency.
A practical boundary for authenticated report downloads
For authenticated e-commerce customers downloading generated reports, publish immutable revisions and keep cleanup off the request path. Use paginated prefix listing, bounded batches, a leased job, and metrics that distinguish object count from bytes. Add a one-day lifecycle policy as recovery for abandoned revisions, with the retention window documented in terms of object age or supersession.
This design is not suitable when legal erasure must complete immediately or when a revision may contain regulated data that cannot remain in backups for the grace period. In that case, use a deletion process designed for the applicable retention and erasure requirements, and verify every storage replica and cache involved. It is also a poor fit for tiny, short-lived files where a single stable key and a provider-managed lifecycle rule are easier to reason about.
For most report systems, the boring separation wins: publication protects availability, asynchronous cleanup protects throughput, and lifecycle rules protect against forgotten work. The exact concurrency should come from your measurements, not from a copied number.
References
- https://csrc.nist.gov/pubs/sp/800/66/r2/final
- https://docs.aws.amazon.com/AmazonS3/latest/userguide/Versioning.html
Top comments (0)