S3 Versioning and Lifecycle
Two S3 features protect data and control cost over time: versioning keeps every version of an object, and lifecycle rules move or delete objects automatically as they age.
Versioning
Once versioning is enabled on a bucket, every upload of an existing key creates a new version instead of overwriting, and a delete inserts a delete marker instead of removing the data. You can restore any previous version. A bucket's versioning state is unversioned (default), enabled or suspended; once enabled it can never return to unversioned.
aws s3api put-bucket-versioning --bucket tad-reports \
--versioning-configuration Status=Enabled
aws s3api list-object-versions --bucket tad-reports --prefix q1.csv \
--query "[Versions[].[VersionId,IsLatest,Size], DeleteMarkers[].[VersionId,IsLatest]]"Sample output:
[
[
["3HL4kqtJlcpXroDTDmJ.rmSpXd3dIbrHY", false, 1840],
["UIORUnfndfiufdisojhr398493jfdkjFJ", false, 1532]
],
[
["0Ju1mXJn4dL4Oy0Cm1c9mNLplsOprpBY", true]
]
]Model: a versioned bucket
class VersionedBucket:
def __init__(self):
self.versions = {} # key -> list of (version_id, data or None for a delete marker)
self.counter = 0
def _new_id(self):
self.counter += 1
return f"v{self.counter}"
def put(self, key, data):
vid = self._new_id()
self.versions.setdefault(key, []).append((vid, data))
return vid
def delete(self, key):
vid = self._new_id()
self.versions.setdefault(key, []).append((vid, None)) # delete marker
return vid
def get(self, key, version_id=None):
history = self.versions.get(key, [])
if version_id:
return dict(history).get(version_id, "NoSuchVersion")
if not history or history[-1][1] is None:
return "NoSuchKey (404)"
return history[-1][1]
def delete_version(self, key, version_id):
self.versions[key] = [v for v in self.versions[key] if v[0] != version_id]
b = VersionedBucket()
v1 = b.put("q1.csv", "revenue,100")
v2 = b.put("q1.csv", "revenue,120")
marker = b.delete("q1.csv")
print("latest after delete:", b.get("q1.csv"))
print("old version", v1, "->", b.get("q1.csv", v1))
print("history:", [vid for vid, _ in b.versions["q1.csv"]])
b.delete_version("q1.csv", marker) # removing the marker "undeletes"
print("after removing the delete marker:", b.get("q1.csv"))latest after delete: NoSuchKey (404)
old version v1 -> revenue,100
history: ['v1', 'v2', 'v3']
after removing the delete marker: revenue,120
Note: Every version is billed as stored data. A frequently overwritten object in a versioned bucket can quietly multiply storage costs, so pair versioning with a lifecycle rule that expires old (noncurrent) versions.
MFA Delete can additionally require an MFA code to permanently delete versions or change the versioning state, and S3 Object Lock can make versions undeletable for a retention period.
Lifecycle rules
A lifecycle configuration is a list of rules, each with a filter (prefix and/or tags) and actions:
{
"Rules": [{
"ID": "logs-tiering",
"Filter": { "Prefix": "logs/" },
"Status": "Enabled",
"Transitions": [
{ "Days": 30, "StorageClass": "STANDARD_IA" },
{ "Days": 90, "StorageClass": "GLACIER_IR" },
{ "Days": 365, "StorageClass": "DEEP_ARCHIVE" }
],
"Expiration": { "Days": 2555 },
"NoncurrentVersionExpiration": { "NoncurrentDays": 30 },
"AbortIncompleteMultipartUpload": { "DaysAfterInitiation": 7 }
}]
}aws s3api put-bucket-lifecycle-configuration --bucket tad-logs \
--lifecycle-configuration file://lifecycle.jsonModel: where is an object on day N?
rule = {
"prefix": "logs/",
"transitions": [(30, "STANDARD_IA"), (90, "GLACIER_IR"), (365, "DEEP_ARCHIVE")],
"expiration_days": 2555, # about 7 years
}
def state(key, age_days):
if not key.startswith(rule["prefix"]):
return "STANDARD (rule does not apply)"
if age_days >= rule["expiration_days"]:
return "expired (deleted)"
current = "STANDARD"
for day, cls in rule["transitions"]:
if age_days >= day:
current = cls
return current
for age in (0, 29, 30, 120, 400, 2555):
print(f"logs/app.log at day {age:>4}: {state('logs/app.log', age)}")
print(f"images/a.png at day 400: {state('images/a.png', 400)}")logs/app.log at day 0: STANDARD
logs/app.log at day 29: STANDARD
logs/app.log at day 30: STANDARD_IA
logs/app.log at day 120: GLACIER_IR
logs/app.log at day 400: DEEP_ARCHIVE
logs/app.log at day 2555: expired (deleted)
images/a.png at day 400: STANDARD (rule does not apply)
Model: what the lifecycle saves
One month of logs (100 GB) kept for a year, with and without the rule (example prices, $/GB-month):
PRICE = {"STANDARD": 0.023, "STANDARD_IA": 0.0125, "GLACIER_IR": 0.004, "DEEP_ARCHIVE": 0.00099}
transitions = [(30, "STANDARD_IA"), (90, "GLACIER_IR"), (365, "DEEP_ARCHIVE")]
def class_on(day):
cls = "STANDARD"
for d, c in transitions:
if day >= d:
cls = c
return cls
gb = 100
with_rule = sum(gb * PRICE[class_on(day)] / 30 for day in range(365))
without = gb * PRICE["STANDARD"] / 30 * 365
print(f"one year, no lifecycle : ${without:6.2f}")
print(f"one year, with lifecycle: ${with_rule:6.2f}")
print(f"saving: {1 - with_rule / without:.0%}")one year, no lifecycle : $ 27.98
one year, with lifecycle: $ 8.47
saving: 70%
Tip: Transition rules have minimums too: objects must stay at least 30 days in Standard before moving to Standard-IA, and small objects (under 128 KB) are not transitioned by default because it would cost more than it saves.
Test yourself
In a versioned bucket, what does a simple DELETE request do?
- Permanently deletes all versions
- Adds a delete marker; older versions remain
- Fails
- Moves the object to Glacier
Can a bucket go back to 'unversioned' after versioning was enabled?
- Yes, any time
- No, it can only be suspended
- Only with MFA
- Only by AWS Support
Which lifecycle action stops old versions from piling up?
- Transitions
- NoncurrentVersionExpiration
- AbortIncompleteMultipartUpload
- Replication