September 30, 2026 · 5 min read

How to auto-delete files after a few days in S3, R2 and B2

Temporary shares pile up: screenshots for a review, a build for a tester, a file for a client. Lifecycle rules let the bucket clean up after itself. The trick is to decide the lifetime when you upload, by putting the file under a prefix that has a rule.

The prefix pattern

Create one rule per lifetime, each limited to its own folder:

  • tmp/1d/ deletes after 1 day
  • tmp/7d/ deletes after 7 days
  • tmp/30d/ deletes after 30 days

Upload a file to tmp/7d/2026/09/report.pdf and it's gone a week later. Everything outside tmp/ is never touched.

Cloudflare R2

  1. Open the bucket's Settings and find Object lifecycle rules, then select Add rule.
  2. Name it, for example expire-7d, and set the prefix to tmp/7d/.
  3. Choose to delete objects 7 days after they were uploaded and save.

Or with Wrangler:

npx wrangler r2 bucket lifecycle add your-bucket expire-7d tmp/7d/ --expire-days 7

Amazon S3

  1. Open the bucket, go to Management and select Create lifecycle rule.
  2. Name the rule and choose Limit the scope using filters with the prefix tmp/7d/.
  3. Under actions, select Expire current versions of objects and enter 7 days. In a versioned bucket, also permanently delete noncurrent versions.

With the AWS CLI:

{
  "Rules": [
    {
      "ID": "expire-7d",
      "Status": "Enabled",
      "Filter": { "Prefix": "tmp/7d/" },
      "Expiration": { "Days": 7 }
    }
  ]
}
aws s3api put-bucket-lifecycle-configuration --bucket your-bucket \
  --lifecycle-configuration file://lifecycle.json

This command replaces the bucket's whole lifecycle configuration, so include any rules that already exist.

Backblaze B2

In the bucket's Lifecycle Settings, choose custom rules and add one with the file name prefix tmp/7d/. B2 works in two stages: days from uploading to hiding and days from hiding to deleting. Set them to 6 and 1 for a file that disappears after about a week.

When exactly are files deleted?

Lifecycle rules run in the background, typically once a day. Amazon S3 counts from the upload time, rounds up to the next midnight UTC, then queues the object for removal; you stop paying for it once it's expired. In practice, a file can stay reachable for up to about a day after its date. If a link must stop working at an exact time, use a presigned URL instead.

Common questions

Do lifecycle rules delete files if my computer is off?

Yes. The rules are stored in the bucket and run on the provider's side, so nothing needs to be running on your end.

Can I delete files after a few hours instead of days?

No. Lifecycle rules work in whole days. For links that should expire within hours, keep the file private and share a presigned URL.

Will a lifecycle rule delete files outside the prefix?

No. A rule with a prefix filter only affects keys that start with that prefix. A rule without a filter applies to the whole bucket, so always set one.