Sub topic 11
Versioning and recovering from mistakes
This chapter assumes you can create a bucket, upload objects with the AWS CLI or boto3, and read a basic IAM or bucket policy. You should also know that an object is identified by a bucket and a key.
Why versioning exists
By default, an S3 bucket keeps one object per key. If you upload reports/2026/report.csv twice, the second upload replaces the first. If you delete the key, the object is gone. A script with a wrong prefix, a faulty deployment, or a mistyped aws s3 rm --recursive can destroy data with no way back.
Versioning keeps every version of an object under the same key. An overwrite adds a new version, and a delete adds a marker. The earlier data stays in the bucket until something removes it on purpose. This makes versioning the first protection to turn on for data you cannot easily recreate.
Bucket versioning states
A bucket is in one of three states.
| State | Meaning |
|---|---|
| Unversioned | The default. Objects have no version ID (the ID is the string `null`). Overwrites and deletes are permanent. |
| Enabled | Every new write gets a unique version ID. Older versions are kept. |
| Suspended | New writes get the version ID `null`. Existing versions are kept. |
Once you enable versioning, you cannot return the bucket to the unversioned state. You can only suspend it. Suspending stops new unique IDs but does not delete any stored versions, and you keep paying for them.
Turning it on
Enable versioning and list what is stored under a prefix:
aws s3api put-bucket-versioning \
--bucket my-example-bucket-123456789012 \
--versioning-configuration Status=Enabled
aws s3api list-object-versions \
--bucket my-example-bucket-123456789012 \
--prefix reports/The change applies to writes made after you enable it. Objects that already existed keep the version ID null until they are overwritten, and then the new write gets a real ID. The null version stays as an older version.
The output of list-object-versions has a Versions array and a DeleteMarkers array. Each entry has a Key, a VersionId, an IsLatest flag and a LastModified time. Exactly one entry per key has IsLatest set to true.
What happens on overwrite and delete
The following diagram shows how a key changes as you write and delete it.
Three rules cover most of the behavior.
- Overwrite. A
PUTto an existing key creates a new version and makes it current. The old version remains and can be read by its ID. - Delete without a version ID. S3 does not remove data. It adds a delete marker, which is a zero-byte placeholder that becomes the current version. A plain
GETon the key then returns404 Not Found. The older versions are still there. - Delete with a version ID. This is a permanent delete of that one version. It cannot be undone. Deleting a delete marker by its ID removes the marker, so the previous version becomes current again.
Reading old versions
Most read calls accept a version ID. With the CLI, get-object writes the data to a local file:
aws s3api get-object \
--bucket my-example-bucket-123456789012 \
--key reports/2026/report.csv \
--version-id "EXAMPLE_VERSION_ID" \
restored-report.csvA GET without a version ID returns the current version. If the current version is a delete marker, the call fails with a 404, and the response header x-amz-delete-marker: true tells you why.
Recovering from mistakes
Recovery depends on what went wrong.
Recovering from an accidental delete
If someone deleted a key without a version ID, the current version is a delete marker. Remove that marker and the previous version returns. First find the marker's ID:
aws s3api list-object-versions \
--bucket my-example-bucket-123456789012 \
--prefix reports/2026/report.csv \
--query "DeleteMarkers[?IsLatest==\`true\`].[Key,VersionId]" \
--output textThen delete the marker by ID:
aws s3api delete-object \
--bucket my-example-bucket-123456789012 \
--key reports/2026/report.csv \
--version-id "DELETE_MARKER_VERSION_ID"Recovering from a bad overwrite
If someone uploaded a corrupted file, you have two options.
- Copy the good version forward. Copy the old version onto the same key. This creates a new current version with the old content, and the bad version stays in history. This is the usual choice because it removes nothing.
- Delete the bad version by ID. The previous version becomes current. This is permanent for the bad version.
Copying forward looks like this in boto3:
import boto3
s3 = boto3.client("s3")
bucket = "my-example-bucket-123456789012"
key = "reports/2026/report.csv"
versions = s3.list_object_versions(Bucket=bucket, Prefix=key)
entries = [v for v in versions.get("Versions", []) if v["Key"] == key]
entries.sort(key=lambda v: v["LastModified"], reverse=True)
if len(entries) < 2:
raise SystemExit("No earlier version to restore")
previous = entries[1]
s3.copy_object(
Bucket=bucket,
Key=key,
CopySource={"Bucket": bucket, "Key": key, "VersionId": previous["VersionId"]},
)
print("Restored version", previous["VersionId"])The script sorts by LastModified and takes the second newest version. It assumes the newest version is the bad one and that a single call returns every version of the key, which holds for a key with fewer than 1,000 versions. For keys with more history, use a paginator (s3.get_paginator("list_object_versions")).
copy_object handles source objects up to 5 GB. For larger objects, use the managed s3.copy method, which switches to multipart copy.
Interaction with lifecycle rules
Versioning changes how lifecycle rules behave, and the chapter on lifecycle covers the rules in full. The points that matter here:
- On a versioned bucket, an
Expirationrule on current objects does not delete data. It adds a delete marker. The data becomes a noncurrent version. NoncurrentVersionExpirationremoves noncurrent versions after a set number of days. Without it, old versions accumulate forever and add to your bill.NoncurrentVersionTransitionmoves noncurrent versions to a cheaper storage class.- A delete marker with no remaining versions beneath it is an expired object delete marker. Lifecycle can clean these up with
ExpiredObjectDeleteMarker, because they add listing clutter and slow down list calls.
A rule that keeps recovery possible but limits cost:
{
"Rules": [
{
"ID": "trim-old-versions",
"Status": "Enabled",
"Filter": { "Prefix": "reports/" },
"NoncurrentVersionTransitions": [
{ "NoncurrentDays": 30, "StorageClass": "STANDARD_IA" }
],
"NoncurrentVersionExpiration": {
"NoncurrentDays": 90,
"NewerNoncurrentVersions": 3
},
"Expiration": { "ExpiredObjectDeleteMarker": true }
}
]
}Here a noncurrent version moves to Standard-IA after 30 days as noncurrent. A version is removed after 90 days as noncurrent, but only if more than three newer noncurrent versions exist, so the three most recent are always kept. Expired delete markers are cleaned up.
Interaction with replication
Replication requires versioning on both the source and the destination bucket. Replication copies new versions, and it copies delete markers only if you enable delete marker replication. It never replicates deletes that name a version ID, which protects the destination from a destructive delete at the source. Replication applies to objects written after you create the rule, so existing objects need a separate backfill. The replication chapter covers this in detail.
Costs and edge cases
- Every version is billed. A 1 GB file overwritten daily for 30 days uses about 30 GB. Use noncurrent-version lifecycle rules to bound this.
- Delete markers cost almost nothing in storage but are real entries in listings.
- Listings can slow down. A prefix with millions of delete markers makes list calls slower. Clean up expired markers.
- Suspended is not off. After suspending, an overwrite replaces the
nullversion, but versions created while enabled remain. - Permissions are separate.
s3:GetObjectVersionis needed to read a specific version,s3:ListBucketVersionsto list versions, ands3:DeleteObjectVersionto delete one. A role with onlys3:GetObjectcannot fetch an old version. - Versioning does not stop bucket deletion problems. A bucket with versions or delete markers cannot be deleted until all of them are removed.
Exercise
A versioned bucket holds data/a.txt with two versions, v1 and v2 (current). A user runs aws s3api delete-object --bucket B --key data/a.txt with no version ID. What does aws s3 cp s3://B/data/a.txt - return, which operation brings v2 back, and why is that operation safe?
Show answer
The copy fails with a 404 error because the current version is now a delete marker. To bring v2 back, find the delete marker's version ID with list-object-versions and run delete-object with --version-id set to that ID. Removing the marker makes v2 the current version again. It is safe because only the zero-byte marker is deleted, and both v1 and v2 stay stored.
Exercise
Your bucket has versioning enabled and a lifecycle rule with only Expiration set to 30 days on current objects. After 30 days storage usage has not dropped. Why, and which setting would you add?
Show answer
On a versioned bucket, expiring a current object only adds a delete marker, and the data becomes a noncurrent version that is still stored and billed. Add a NoncurrentVersionExpiration action (for example NoncurrentDays: 30) so the noncurrent versions are removed, and consider ExpiredObjectDeleteMarker to clean up the leftover markers.