# Replacing, Removing and Cleanup

> How storage keeps owners on a working image through failures and races, and how deleted owners' images and leftovers are cleaned up.

*Canonical: https://makerkit.dev/docs/void-cloudflare/storage/lifecycle*

---

## Replacing

A new upload is stored under a new key first. The owner column moves to it only if it still holds the URL read at the start (a compare-and-set), then the old object is deleted. So:

- **R2 fails:** `500`, the owner keeps the old image.
- **Two uploads at once:** one wins; the other deletes its own object and gets `409 conflict`.
- **The owner was deleted meanwhile:** the new object is deleted, `404 not_found`.
- **The old object can't be deleted:** still `200`; a warning is logged with its key and the sweep removes it.

## Removing

`DELETE /api/uploads/<kind>` clears the column first, then deletes the object, so the owner never points at a missing file. Repeating it, or removing when there is no image, answers `204`.

## When an Owner Is Deleted

`requestPurge` (`apps/web/lib/cleanup.server.ts`), which the kit already calls when an organization or an account is deleted, also enqueues a `storage.purge-owner` [outbox job](../outbox/overview) in the same transaction: every kind's files for that owner are deleted a page at a time, and the count is logged. It never purges an owner that still exists, and a rerun deletes nothing. In delete code you write yourself, call `requestPurge` in the transaction that deletes the owner ([Purge Targets](../cleanup/purge-targets)): that one call purges both their rows and their files. The file purge runs on the outbox's next sweep (within about 5 minutes).

## The Weekly Sweep

Every Sunday at 04:00 UTC (`apps/web/crons/storage-sweep.ts`), one `storage.sweep` job per kind lists its objects and deletes those older than a day that no owner column points at: leftovers of failed deletes. Objects in use, under a day old (an upload may still be writing its owner), or under keys storage never writes are kept. Long listings hand over to a follow-up job; counts are logged.

Images are personal data when they show a face: with the purge and the sweep, a deleted owner's or replaced image is gone from R2 within about 8 days at most.
