Lifecycle, security, and operations
Apply retention and lifecycle rules
Translate product retention into automatic expiration and storage-class rules without deleting authoritative data too early.
8 minute lesson
Lifecycle rules can expire objects or change their storage treatment based on age and prefix. A rule can delete objects some days after upload, transition them from Standard to Infrequent Access storage, or abort incomplete multipart uploads.
They run at the storage layer, with no code review and no confirmation prompt. An incorrect broad prefix can remove large sets of data, and R2 applies the rule within roughly a day of an object matching it.
Add a rule with Wrangler:
npx wrangler r2 bucket lifecycle add my-app-files
The command walks you through prefix, action, and age interactively. Check what’s active on a bucket before touching anything:
npx wrangler r2 bucket lifecycle list my-app-files
Every bucket already has one default rule: incomplete multipart uploads are aborted seven days after initiation. That one is a gift, leave it on.
Deletion is a policy decision
Define ownership and retention before configuring deletion. “Exports older than 30 days” sounds harmless until you learn the billing team promised customers a 90-day download window. Keep legal, billing, and user-promised retention separate from cache cleanup, because the two change for different reasons and answer to different people.
Prefix design from earlier lessons pays off here. When temporary files live under tmp/exports/, a rule can target exactly that set:
rule: expire-temp-exports
prefix: tmp/exports/
action: delete after 30 days
If temporary and permanent objects share a prefix, no lifecycle rule can separate them, and you’re back to writing cleanup scripts.
For data that must survive mistakes, R2 has the opposite tool: a bucket lock rule prevents deletion or overwriting of matching objects for a set period, which protects them from bad code and from a bad lifecycle rule alike.
Test on a disposable prefix
Preview the matching key set and test on a disposable prefix before enabling a rule on real data. List the objects the prefix matches, read the count, and ask whether every one of them should die.
Add a short practice lifecycle to temporary exports, then confirm permanent uploads do not match it. Upload one object under tmp/exports/ and one under uploads/, wait out the rule, and verify only the first disappeared. That single experiment teaches you more about prefix matching than the docs will.
Lesson completed