Bucket Lifecycle — Let the Bucket Tidy Itself
Six months after launch, Hoplink's bucket is full of clutter: "temporary" uploads nobody opened again, half-finished multipart uploads from dropped connections, and old files that are still kept but almost never read. You could write a nightly Worker to hunt them down. Better: tell the bucket the rules once and let R2 enforce them.
The rule
Name a prefix, an age and an action — R2 does the rest.
A lifecycle rule has three parts:
- Which objects — usually a key prefix, such as
tmp/, or the whole bucket. - When — an age in days since the object was uploaded (or a fixed date).
- What — one of three actions:
- Delete the object.
- Abort incomplete multipart uploads older than the age, freeing the space their parts use.
- Move to Infrequent Access, a storage class that costs less per gigabyte stored but charges for each retrieval, and has a minimum storage duration.
You manage rules in the dashboard or with Wrangler, for example wrangler r2 bucket lifecycle add hop-files (it asks for the prefix, age and action), and wrangler r2 bucket lifecycle list hop-files to review them. New buckets already come with a default rule that aborts multipart uploads left incomplete for seven days.
Lifecycle rules are not instant. R2 checks objects in the background, so an object may linger for a while after it becomes eligible. If your app must never serve an expired file, check the age in your Worker as well.
The bucket itself has a lifecycle too: wrangler r2 bucket create to begin, and wrangler r2 bucket delete at the end — which only works once the bucket is empty.
The shortcut
Give every key prefix a retention sentence at design time: "Objects under X live for N days, then Y." If you cannot say the sentence, you have not decided how long the data should live — and it will live forever.
Sort keys by prefix
Uploads land in
tmp/; when a link is saved, the Worker copies the file tofiles/. Link previews go tothumbs/.
Trap: moving busy files to Infrequent Access. Each read is billed, so a popular file can end up costing more than it did in Standard storage.
Drills
Answer fast — trust the rule.
What three things does a lifecycle rule specify?
Which rule frees space held by parts of uploads that never finished?
A rule deletes tmp/ objects after 1 day. A 26-hour-old temp file is still downloadable. Why?
When is moving objects to Infrequent Access a poor choice?
You are retiring an old bucket, but wrangler r2 bucket delete old-hop-files refuses. What must happen first?
Remember
- Name a prefix, an age and an action — R2 does the rest.
- Shortcut: write a retention sentence for every prefix before you ship.
- Trap: Infrequent Access for hot files, and expecting rules to run the instant an object is eligible.
