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.