Sub topic 16
Lifecycle Rules, Orphan Cleanup, and Egress Cost
This chapter assumes you have read the earlier chapters on presigned uploads, multipart uploads, post-upload processing, and CDN caching. It covers how to keep storage and bandwidth bills under control once an upload system has been running for months. The three levers are lifecycle rules, cleanup of abandoned data, and reducing egress (data leaving your storage or CDN).
Where the money goes
Media systems accumulate cost in three places.
| Cost driver | What causes it | Main lever |
|---|---|---|
| Storage | Bytes kept per month, by storage class | Lifecycle rules, deleting orphans |
| Requests | PUT, GET, LIST and similar calls | Fewer small objects, CDN caching |
| Egress | Bytes sent to viewers | CDN cache hit ratio, smaller variants |
For most public media products, egress dominates. A 2 MB image viewed one million times transfers about 2 TB. Storing that image costs almost nothing by comparison. Storage waste is quieter but never stops growing, because nobody notices objects that no code path references.
Kinds of waste in an upload system
Upload flows create garbage in predictable ways.
- Incomplete multipart uploads. A client calls
create_multipart_upload, sends some parts, and never callscomplete_multipart_upload. The uploaded parts stay in storage and are billed, but they never appear in a normal object listing. - Abandoned direct uploads. A user gets a presigned URL, uploads the file, and never submits the form. The object exists, but no database row points to it.
- Quarantined and rejected files. Files that failed validation or a malware scan remain in a quarantine prefix.
- Superseded originals and variants. A user replaces an avatar. The old original and all its generated variants are no longer referenced.
- Deleted-account data. Rows are removed, but the objects are not.
Each type needs a rule or a job. The simplest case is handled by the storage service itself.
Lifecycle rules
A lifecycle rule is a bucket-level policy that tells the storage service to transition or delete objects automatically, based on age, prefix, or tags. It runs without any code on your side.
Key design supports this. If you separate objects by prefix, such as incoming/, quarantine/, originals/, and variants/, each prefix can have its own policy. Prefix-based layout is the reason to plan keys before launch. Changing a layout later means copying data.
The following Python example sets rules for an S3 bucket.
import boto3
s3 = boto3.client("s3")
s3.put_bucket_lifecycle_configuration(
Bucket="example-uploads",
LifecycleConfiguration={
"Rules": [
{
"ID": "abort-incomplete-multipart",
"Status": "Enabled",
"Filter": {"Prefix": ""},
"AbortIncompleteMultipartUpload": {"DaysAfterInitiation": 2},
},
{
"ID": "expire-unclaimed-incoming",
"Status": "Enabled",
"Filter": {"Prefix": "incoming/"},
"Expiration": {"Days": 1},
},
{
"ID": "expire-quarantine",
"Status": "Enabled",
"Filter": {"Prefix": "quarantine/"},
"Expiration": {"Days": 14},
},
{
"ID": "archive-old-originals",
"Status": "Enabled",
"Filter": {"Prefix": "originals/"},
"Transitions": [
{"Days": 90, "StorageClass": "STANDARD_IA"},
{"Days": 365, "StorageClass": "GLACIER_IR"},
],
},
]
},
)Each rule solves one problem from the list above.
abort-incomplete-multipartdeletes the parts of uploads that never completed. Without it, those parts are billed indefinitely. Two days is long enough for a slow client to finish and short enough to limit waste.expire-unclaimed-incomingremoves objects that were uploaded but never promoted out ofincoming/. This only works if your post-upload pipeline moves or copies accepted files to a permanent prefix. The pipeline, not the user, decides what is kept.expire-quarantinekeeps rejected files long enough for investigation and then deletes them.archive-old-originalsmoves rarely read originals to cheaper classes.
The put_bucket_lifecycle_configuration call replaces the whole configuration. Always send every rule, not only the one you are changing.
Storage class gotchas
Cheaper storage classes come with trade-offs, and these catch teams out.
- Minimum storage duration. Infrequent-access classes bill a minimum number of days (30 for Standard-IA). Deleting earlier still charges for the full period.
- Minimum object size. Small objects are billed as if they were 128 KB in infrequent-access classes. Do not transition thumbnails and other small variants.
- Retrieval fees. Reading from infrequent-access classes costs per GB. A transition rule is a bad deal for files that are still read often.
- Archive retrieval time. Deep archive classes can take hours to restore. Never apply them to anything a user may open.
- Transition requests cost money. Moving millions of tiny objects can cost more than it saves.
A safe pattern is to transition only originals, which are large and rarely read after processing, and leave variants in the standard class where the CDN fetches them. S3 Intelligent-Tiering is an alternative when access patterns are unknown, at the price of a small per-object monitoring fee.
Versioning
If bucket versioning is on, deleting an object only adds a delete marker, and the old bytes stay. Add a NoncurrentVersionExpiration rule to remove old versions after a set number of days. Add ExpiredObjectDeleteMarker cleanup too. Teams that enable versioning for safety and forget these rules often find their bill growing even as visible content shrinks.
Orphan cleanup
Lifecycle rules work on age and prefix. They cannot tell whether a database row references an object. For that you need a reconciliation job.
An orphan is an object with no database reference. A common cause is a replaced avatar or a deleted post. Prefer to prevent orphans at the source: when a record is deleted or replaced, enqueue a deletion job for its objects, and make that job idempotent so retries are safe.
Prevention fails sometimes, so run a periodic sweep as well. The sweep has a safety hazard: an object that was just uploaded may not have its row committed yet. Deleting it would break a real upload in progress. Always apply a grace period.
import boto3
from datetime import datetime, timedelta, timezone
s3 = boto3.client("s3")
BUCKET = "example-uploads"
GRACE = timedelta(days=2)
def find_orphans(referenced_keys: set[str], prefix: str = "originals/"):
cutoff = datetime.now(timezone.utc) - GRACE
paginator = s3.get_paginator("list_objects_v2")
for page in paginator.paginate(Bucket=BUCKET, Prefix=prefix):
for obj in page.get("Contents", []):
if obj["LastModified"] < cutoff and obj["Key"] not in referenced_keys:
yield obj["Key"]
def delete_keys(keys):
batch = []
for key in keys:
batch.append({"Key": key})
if len(batch) == 1000:
s3.delete_objects(Bucket=BUCKET, Delete={"Objects": batch})
batch = []
if batch:
s3.delete_objects(Bucket=BUCKET, Delete={"Objects": batch})This version holds all referenced keys in memory, which only suits small datasets. For large buckets, use S3 Inventory, a scheduled report listing every object. Join the inventory against a database export, and review the resulting orphan list before any deletion.
A cautious rollout looks like this: first run the sweep in report-only mode, compare the count with your expectations, then enable deletion with a cap such as "never delete more than 1% of objects in one run". A bug in the "referenced keys" query would otherwise delete valid media in bulk.
Variants and derived data
Image variants are derived from originals and can be regenerated. That affects cleanup: if a variant is orphaned, delete it freely. If an original is lost, everything derived is lost too. Treat originals as the data you protect, and treat variants as a cache you can rebuild. Some teams delete rarely requested variants with a lifecycle rule and regenerate them on demand.
Egress cost
Egress is the bytes you send out. Two sources matter: storage to CDN (origin egress) and CDN to viewers. Origin egress to a CDN is often free or discounted with the same provider, while CDN-to-viewer traffic is billed per GB, with rates that vary by region. Check your provider's current price list rather than relying on a remembered figure.
The main levers are below.
- Raise the cache hit ratio. Use content-hashed URLs with
Cache-Control: public, max-age=31536000, immutable. Every request answered by the CDN is one the origin does not serve. Avoid cache-busting query strings that differ per user. - Normalize cache keys. If the CDN includes unneeded headers or query parameters in its cache key, identical files are cached many times and hit ratios fall.
- Send fewer bytes. Serve WebP or AVIF variants, size images to the layout (a 400-pixel slot should not receive a 4000-pixel image), and enable compression for text types. Do not compress already compressed formats like JPEG and MP4.
- Offer limited variants. Every extra variant adds storage and splits the cache. Pick a small set of widths.
- Use ranges and adaptive streaming for video. Adaptive bitrate streaming lets a viewer on a slow connection fetch smaller segments. Range requests avoid sending a whole file when a viewer seeks or leaves early.
- Protect against hotlinking and scraping. Signed URLs, referrer checks, and rate limits stop others from consuming your bandwidth.
Private media and caching
Signed URLs conflict with caching, because every signature makes the URL unique. Two options reduce the damage. With CDN-signed URLs or cookies, the CDN validates the signature at the edge and caches the object under a signature-free cache key. This keeps hit ratios high. With storage-presigned URLs, which differ on every request, caching works poorly.
Measure before optimizing
Turn on CDN and storage access logs, or use the provider's metrics, and find answers to a few questions.
- What is the cache hit ratio, by content type?
- Which prefixes hold the most bytes, and how old are they?
- Which 1% of objects account for the most egress?
The answers often point at one cause, such as an oversized hero image or a single video, that is worth more than all the other tuning combined.
Common mistakes
- Writing a lifecycle rule for an empty prefix filter by accident, which then applies to the whole bucket.
- Expiring
incoming/before the pipeline finishes processing a large file. - Deleting orphans without a grace period.
- Transitioning small variants to infrequent-access classes.
- Forgetting versioned and incomplete-multipart data, which are invisible in ordinary listings.
- Testing rules only in production. Apply new rules to a test bucket first, because deletions are hard to undo.
Exercise
A bucket has the prefixes incoming/, originals/, and variants/. Users report that some large video uploads fail to finish processing, and the bill shows growing storage that you cannot find in object listings. Name one lifecycle rule that addresses the hidden storage, and one setting you must check on the rule that expires incoming/.
Show answer
Add an AbortIncompleteMultipartUpload rule (for example after 2 days) to delete parts of multipart uploads that were never completed, since those parts are billed but do not appear in normal listings. For the incoming/ expiration rule, make sure the expiry period is longer than the longest time the pipeline needs to process and promote a large file, so the rule does not delete objects that are still being handled.
Exercise
Why should an orphan sweep skip recently modified objects, and why should it run in report-only mode first?
Show answer
A just-uploaded object may not yet have its database row committed, so deleting it would break a legitimate in-progress upload. Report-only mode lets you compare the orphan count with expectations and catch a faulty "referenced keys" query before it deletes valid media in bulk.