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.

A lifecycle rule tells R2 what to do with objects as they age. It can delete objects some days after upload, move them from Standard to Infrequent Access storage, or abort incomplete multipart uploads. You pick a prefix, an action, and an age.

Rules run at the storage layer. No code review, no confirmation prompt. A rule with a prefix that’s too broad removes a lot of data, and R2 applies it within roughly a day of an object matching. Treat a lifecycle rule with the same care as a DELETE without a WHERE.

Add a rule with Wrangler:

npx wrangler r2 bucket lifecycle add my-app-files

The command asks you for prefix, action, and age interactively. Before touching anything, look at what’s already active:

npx wrangler r2 bucket lifecycle list my-app-files

Every bucket ships with one default rule: incomplete multipart uploads are aborted seven days after they start. That one is a gift. Leave it on.

Deletion is a policy decision

Decide who owns the data and how long it must live before you configure deletion. “Exports older than 30 days” sounds harmless until you learn the billing team promised customers a 90-day download window.

Keep the retention you promised users, or the law requires, separate from cache cleanup. The two change for different reasons and answer to different people.

This is where the prefix design from earlier lessons pays off. 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 tell them apart. 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. It protects them from bad code and from a bad lifecycle rule alike.

Test on a disposable prefix

Before enabling a rule on real data, list the objects the prefix matches. Read the count. Ask whether every one of them should die.

Then rehearse it. Upload one object under tmp/exports/ and one under uploads/. Add a short practice rule on tmp/exports/, wait it out, and verify only the first object disappeared. That single experiment teaches you more about prefix matching than the docs will.

Lesson completed