S3 versioning, lifecycle rules and replication
-
Phase 0: Before you start
-
Phase 1: The foundation
-
Phase 2: Operations and security
-
Phase 3: SQL Server on AWS
-
Phase 4: Troubleshooting step by step
-
Phase 5: Final project and career
Somebody deletes a folder by mistake, a script overwrites last month’s config, and meanwhile the storage bill keeps creeping up. S3 lifecycle rules, versioning and replication let you deal with all of that without buying any extra tools.
You’ll switch on versioning, recover a deleted file, write lifecycle rules that move and expire data, and replicate a bucket from Mumbai to Singapore. On the way you’ll build a cleanup script for versioned buckets that you’ll keep using for the rest of the course.
| Time | You need | By the end you can |
|---|---|---|
| 60 minutes | Lessons 16 and 17 done, your laptop signed in as saat-admin. Cost: well under USD 0.01 (a few KB copied across Regions). | Undo deletes and overwrites with versioning, write lifecycle rules for tiering and cleanup, set up Cross-Region Replication, and delete a versioned bucket completely. |
What it is, in one line
S3 lifecycle rules move or delete objects automatically as they age, versioning keeps every old copy of an object, and replication copies new objects to another bucket.
In Simple Words
A notebook that never loses a page
Imagine a notebook where you never rub anything out. When you change a page you write a fresh one and keep the old page behind it, and if you tear a page out, a sticky note saying “removed” goes on top while the page itself stays there. Peel off the sticky note and the page is back, and that’s versioning.
Old notebooks start filling your shelf, so you make a rule: after a month they go to the cupboard, after three months to the storeroom, and after a year they get shredded. That’s a lifecycle rule. Replication is a friend in another city who photocopies every new page you write, so a fire at your house doesn’t take everything with it.
Engineer's View
How the three features really work
Versioning is set per bucket and can be unversioned, enabled or suspended, but once enabled it can never go back to unversioned. Every PUT creates a new version ID, the newest one is current and the older ones become noncurrent. A plain DELETE only adds a delete marker, and if you delete that marker by its version ID the object comes back. Keep in mind that every version is stored and billed.
Lifecycle rules filter by prefix, tags or size and can run transitions (Standard-IA after at least 30 days, for example), expirations, noncurrent version expirations and cleanup of incomplete multipart uploads. S3 applies them in the background, roughly once a day, and since September 2024 transitions skip objects smaller than 128 KB by default.
Replication, Cross-Region or Same-Region, needs versioning on both buckets and an IAM role that S3 can assume. It only copies objects written after the rule exists, so for older objects you need S3 Batch Replication. Delete markers aren’t replicated unless you switch that on, and deletes of specific versions are never replicated, which keeps the copy safe from a malicious delete.
How it works, step by step
Here’s what happens to a single key in a versioned bucket.
1Each upload adds a version
Uploading config.txt a second time doesn’t replace the first copy. Version 1 becomes noncurrent and you can still read it using its version ID.
2A delete only adds a marker
aws s3 rm hides the object behind a delete marker. aws s3 ls shows nothing, yet both versions are still sitting there.
3Removing the marker restores it
Delete the marker by its version ID and the newest real version becomes current again.
4Lifecycle keeps the cost in check
Without a rule, noncurrent versions keep piling up forever. These are the lab’s rules:
In most real buckets the cleanup-versions rule matters more than the tiering one. It expires noncurrent versions after 30 days while keeping the newest three, clears out expired delete markers, and aborts multipart uploads that have been sitting half-finished for 7 days.
✅ Checkpoint: You can explain a delete marker, why noncurrent versions need a lifecycle rule, and what replication does and doesn’t copy.
Hands-on lab: versioning, S3 lifecycle rules and replication
Before you run any command, double-check it
Read every command twice before you press Enter. Check the target: the system or account, the IDs, the names and the sizes. These commands are for learning and were tested in our lab, not on your system. At work, run the read-only list commands first, follow your change process, make sure a backup exists, and ask a second person to check anything that changes or deletes data. You run them at your own risk.
Sign in and set names for a source bucket in Mumbai and a destination bucket in Singapore:
cd C:\aws-lab
aws login --profile saat-admin
$env:AWS_PROFILE = 'saat-admin'
$acct = aws sts get-caller-identity --query Account --output text
$src = "saat-src-$acct-ap-south-1-an"
$dst = "saat-dst-$acct-ap-southeast-1-an"
aws s3api create-bucket --bucket $src --bucket-namespace account-regional --region ap-south-1 --create-bucket-configuration LocationConstraint=ap-south-1 | Out-Null
aws s3api put-bucket-versioning --bucket $src --versioning-configuration Status=Enabled
aws s3api get-bucket-versioning --bucket $src --query Status --output textYou should see this:
Enabled1Overwrite a file and read the old version
Paste this whole block:
Set-Content config.txt "max_connections=100"
aws s3 cp config.txt "s3://$src/config.txt" | Out-Null
Set-Content config.txt "max_connections=500"
aws s3 cp config.txt "s3://$src/config.txt" | Out-Null
aws s3api list-object-versions --bucket $src --prefix config.txt --query "Versions[].[VersionId,IsLatest,Size]" --output text
$old = aws s3api list-object-versions --bucket $src --prefix config.txt --query 'Versions[?IsLatest==`false`].VersionId | [0]' --output text
aws s3api get-object --bucket $src --key config.txt --version-id $old old-config.txt | Out-Null
Get-Content old-config.txtYou should see something like this:
Xb8n3Lq2Vt7Rw1Zp9Ks4Mc6Jd0Hf5Ga. True 21
0pQ7Tz4Wn9Lk2Rs6Vb1Xm8Yc3Jd5Hf0E False 21
max_connections=100Nothing was lost in the overwrite. Version 1 is still there, and you’ve just downloaded it using its version ID.
2Delete the file, then bring it back
Paste this whole block:
aws s3 rm "s3://$src/config.txt"
aws s3 ls "s3://$src/"
aws s3api list-object-versions --bucket $src --prefix config.txt --query "DeleteMarkers[].[VersionId,IsLatest]" --output text
$marker = aws s3api list-object-versions --bucket $src --prefix config.txt --query "DeleteMarkers[0].VersionId" --output text
aws s3api delete-object --bucket $src --key config.txt --version-id $marker | Out-Null
aws s3 ls "s3://$src/"You should see something like this (the first ls prints nothing at all):
delete: s3://saat-src-111122223333-ap-south-1-an/config.txt
mQ3tVq8Lp0aZ.4kXvR9sTn2YbWc6HdEf True
2026-10-20 16:02:18 21 config.txtThe “deleted” file is back. That’s the five-minute fix for most “I deleted the wrong thing” calls, but it only works on buckets that had versioning on before the delete happened.
3Add lifecycle rules
Paste this whole block:
@'
{
"Rules": [
{
"ID": "logs-tiering",
"Status": "Enabled",
"Filter": { "Prefix": "logs/" },
"Transitions": [
{ "Days": 30, "StorageClass": "STANDARD_IA" },
{ "Days": 90, "StorageClass": "GLACIER_IR" }
],
"Expiration": { "Days": 365 }
},
{
"ID": "cleanup-versions",
"Status": "Enabled",
"Filter": {},
"NoncurrentVersionExpiration": { "NoncurrentDays": 30, "NewerNoncurrentVersions": 3 },
"Expiration": { "ExpiredObjectDeleteMarker": true },
"AbortIncompleteMultipartUpload": { "DaysAfterInitiation": 7 }
}
]
}
'@ | Set-Content lifecycle.json
aws s3api put-bucket-lifecycle-configuration --bucket $src --lifecycle-configuration file://lifecycle.json
aws s3api get-bucket-lifecycle-configuration --bucket $src --query "Rules[].[ID,Status]" --output textYou should see this:
logs-tiering Enabled
cleanup-versions EnabledNothing moves today, because the rules act on objects as they get older and S3 only checks about once a day. In a real bucket you’d see the transitions in Storage Lens or on the bill after a month.

4Replicate to Singapore
Paste this whole block. It creates the destination bucket with versioning, plus a replication role and the rule:
aws s3api create-bucket --bucket $dst --bucket-namespace account-regional --region ap-southeast-1 --create-bucket-configuration LocationConstraint=ap-southeast-1 | Out-Null
aws s3api put-bucket-versioning --bucket $dst --region ap-southeast-1 --versioning-configuration Status=Enabled
'{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "s3.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }' | Set-Content repl-trust.json
@'
{
"Version": "2012-10-17",
"Statement": [
{ "Effect": "Allow", "Action": ["s3:GetReplicationConfiguration", "s3:ListBucket"], "Resource": "arn:aws:s3:::SRC" },
{ "Effect": "Allow", "Action": ["s3:GetObjectVersionForReplication", "s3:GetObjectVersionAcl", "s3:GetObjectVersionTagging"], "Resource": "arn:aws:s3:::SRC/*" },
{ "Effect": "Allow", "Action": ["s3:ReplicateObject", "s3:ReplicateDelete", "s3:ReplicateTags"], "Resource": "arn:aws:s3:::DST/*" }
]
}
'@ -replace 'SRC', $src -replace 'DST', $dst | Set-Content repl-policy.json
$roleArn = aws iam create-role --role-name saat-s3-replication --assume-role-policy-document file://repl-trust.json --query Role.Arn --output text
aws iam put-role-policy --role-name saat-s3-replication --policy-name replicate --policy-document file://repl-policy.json
@'
{
"Role": "ROLE_ARN",
"Rules": [
{
"ID": "all-to-singapore",
"Status": "Enabled",
"Priority": 1,
"Filter": {},
"DeleteMarkerReplication": { "Status": "Disabled" },
"Destination": { "Bucket": "arn:aws:s3:::DST" }
}
]
}
'@ -replace 'ROLE_ARN', $roleArn -replace 'DST', $dst | Set-Content replication.json
Start-Sleep 15
aws s3api put-bucket-replication --bucket $src --replication-configuration file://replication.json
'{ "order": "o-1001", "amount": 2499 }' | Set-Content o-1001.json
aws s3 cp o-1001.json "s3://$src/orders/o-1001.json" | Out-Null
do { Start-Sleep 10; $st = aws s3api head-object --bucket $src --key orders/o-1001.json --query ReplicationStatus --output text } until ($st -ne 'PENDING')
$st
aws s3api head-object --bucket $dst --key orders/o-1001.json --region ap-southeast-1 --query ReplicationStatus --output textYou should see this, usually within a minute:
COMPLETED
REPLICAThe source shows COMPLETED and the copy in Singapore shows REPLICA. Now check config.txt, which was there before the rule:
aws s3 ls "s3://$dst/" --region ap-southeast-1 --recursiveYou should see something like this:
2026-10-20 16:09:44 39 orders/o-1001.jsonOnly the new object made it across. Replication never copies objects that existed before the rule, and for those you’d run S3 Batch Replication.
✅ Checkpoint: You restored an overwritten file and a deleted one from versions, two lifecycle rules are Enabled, and orders/o-1001.json shows REPLICA in Singapore. Keep it all for the break lab.
Break It, Then Fix It
Two errors that come straight from real change requests: a lifecycle rule that’s “too aggressive”, and a DR bucket somebody tried to save money on.
1Break it: move logs to Standard-IA after 7 days
Try a rule that looks cheaper:
(Get-Content lifecycle.json -Raw) -replace '"Days": 30', '"Days": 7' | Set-Content lifecycle-bad.json
aws s3api put-bucket-lifecycle-configuration --bucket $src --lifecycle-configuration file://lifecycle-bad.jsonYou’ll get this error:
An error occurred (InvalidArgument) when calling the PutBucketLifecycleConfiguration operation: 'Days' in Transition action must be greater than or equal to 30 for storageClass 'STANDARD_IA'S3 rejects the whole configuration, so your good rules stay in place. Standard-IA bills for at least 30 days anyway, so moving data any sooner could never save money. Fix: keep it at 30 days or more for Standard-IA, or use Intelligent-Tiering if you don’t know how the data will be read.
2Break it: suspend versioning on the DR copy
Somebody suspends versioning on the destination “to save cost”, and then the replication rule gets redeployed:
aws s3api put-bucket-versioning --bucket $dst --region ap-southeast-1 --versioning-configuration Status=Suspended
aws s3api put-bucket-replication --bucket $src --replication-configuration file://replication.jsonYou’ll get this error:
An error occurred (InvalidRequest) when calling the PutBucketReplication operation: Destination bucket must have versioning enabled.
Replication needs versions on both sides. Any pipeline that redeploys bucket settings will fail at this step, and you can’t trust the DR copy any more. Fix: turn versioning back on and redeploy:
aws s3api put-bucket-versioning --bucket $dst --region ap-southeast-1 --versioning-configuration Status=Enabled
aws s3api put-bucket-replication --bucket $src --replication-configuration file://replication.json
aws s3api get-bucket-replication --bucket $src --query "ReplicationConfiguration.Rules[0].Status" --output textYou should see this:
EnabledNow clean up. aws s3 rb --force can’t empty a versioned bucket because it only removes current versions, so save this script, which you’ll use again in later lessons:
@'
param([Parameter(Mandatory)][string]$Bucket, [string]$Region = 'ap-south-1')
$v = aws s3api list-object-versions --bucket $Bucket --region $Region --output json | ConvertFrom-Json
$objs = @(@($v.Versions) + @($v.DeleteMarkers) | Where-Object { $_ } | ForEach-Object { @{ Key = $_.Key; VersionId = $_.VersionId } })
if ($objs.Count -gt 0) {
@{ Objects = $objs; Quiet = $true } | ConvertTo-Json -Depth 5 | Set-Content "$env:TEMP\del.json"
aws s3api delete-objects --bucket $Bucket --region $Region --delete "file://$env:TEMP\del.json" | Out-Null
}
aws s3api delete-bucket --bucket $Bucket --region $Region
"Removed $($objs.Count) versions and markers, then deleted $Bucket"
'@ | Set-Content C:\aws-lab\Remove-LabBucket.ps1
.\Remove-LabBucket.ps1 -Bucket $src
.\Remove-LabBucket.ps1 -Bucket $dst -Region ap-southeast-1
aws iam delete-role-policy --role-name saat-s3-replication --policy-name replicate
aws iam delete-role --role-name saat-s3-replication
Remove-Item config.txt, old-config.txt, lifecycle*.json, repl-*.json, replication.json, o-1001.json
.\Find-LabResources.ps1You should see something like this:
Removed 3 versions and markers, then deleted saat-src-111122223333-ap-south-1-an
Removed 1 versions and markers, then deleted saat-dst-111122223333-ap-southeast-1-an✅ Checkpoint: You saw the 30-day Standard-IA rule enforced and fixed replication after versioning was suspended. Both buckets and the replication role are gone, and Remove-LabBucket.ps1 is saved.
This happened at work
The bucket that cost more every month
A logistics company switched on versioning for its tracking bucket after a scare with an accidental delete. A device service rewrote a status file for each of its 40,000 trucks every five minutes, and nobody thought to add a lifecycle rule. Every rewrite kept the old copy, so within eight months the bucket was holding over 90 million noncurrent versions and its storage line on the bill had grown tenfold. It was the finance team, not the engineers, who spotted it first.
The fix took one afternoon. They added a lifecycle rule that expires noncurrent versions after 7 days while keeping the newest two, and put a check in their bucket template that refuses versioning unless a noncurrent expiration rule comes with it. Within a month the bill was back to normal, as S3 cleared the old versions in the background.
Common mistakes and troubleshooting
| Mistake | What happens | What to do |
|---|---|---|
| Versioning without a noncurrent expiration rule | Old versions are billed for ever | Always pair versioning with NoncurrentVersionExpiration |
| Expecting replication to copy existing objects | The DR bucket is missing the older data | Run S3 Batch Replication for existing objects |
Using aws s3 rb --force on a versioned bucket | BucketNotEmpty, because versions remain | Delete all versions and markers first (Remove-LabBucket.ps1) |
| Moving tiny objects to Standard-IA or Glacier | Minimum size and duration charges make it cost more | Filter by size or keep them in Standard |
| Suspending versioning on a replica bucket | Replication changes fail and the DR copy can’t be trusted | Keep versioning enabled on both sides |
| Forgetting incomplete multipart uploads | Hidden parts keep costing money | Add AbortIncompleteMultipartUpload to every bucket |
Interview questions
Click a question to open it. They’re worded the way an interviewer would ask them, and under each one you’ll find why they ask it and one way to answer, which you should put in your own words.
Fresher level
1. Can you explain in simple words what S3 versioning does?
Why they ask this: It’s basic data protection in S3, and versioning is behind most S3 recovery stories.
How you might answer: It’s a bucket setting that keeps every version of every object. If someone overwrites a file, S3 keeps the old one as a version, and if someone deletes it, S3 only adds a delete marker, so I can always go back and recover the older data.
2. A user deleted an important file by mistake, and the bucket has versioning on. How do you get it back?
Why they ask this: It’s a practical recovery skill. Once you understand delete markers, it’s a two-minute fix.
How you might answer: I’d find the delete marker with list-object-versions and delete that marker by its version ID. The previous version becomes current again and the file is back.
3. How would you explain a lifecycle rule to a manager who wants a smaller S3 bill?
Why they ask this: They want cost basics and the ability to explain them to people who aren’t engineers, since lifecycle rules are often the first S3 saving a team makes.
How you might answer: I’d say it’s a rule on the bucket that moves objects to cheaper storage, or deletes them, after a set number of days. It can pick objects by prefix, tags or size, so we only touch the data we’ve chosen.
2–5 years experience
4. You’re asked to set up Cross-Region Replication. What needs to be in place for it to work?
Why they ask this: They’re checking you know the setup, because if one piece is missing, replication quietly does nothing.
How you might answer: Versioning has to be on in both buckets, and S3 needs an IAM role it can assume, with read permissions on the source and replicate permissions on the destination. If the objects use SSE-KMS, that role needs KMS permissions as well.
5. A versioned bucket gets more expensive every month, even though the team says they don’t add much data. What’s going on?
Why they ask this: It’s cost troubleshooting. Old versions are the hidden cost that comes with versioning.
How you might answer: Most likely noncurrent versions are piling up, usually from frequent overwrites, and I’d confirm that with Storage Lens or list-object-versions. Then I’d add a lifecycle rule with NoncurrentVersionExpiration, maybe with NewerNoncurrentVersions so only a few old versions are kept.
6. If someone deletes a file in the source bucket, does replication delete it in the destination too?
Why they ask this: These replication details decide whether your copy protects you at all.
How you might answer: Delete markers only get replicated if I turn on delete marker replication, and deletes of a specific version are never replicated. That protects the destination if someone permanently deletes data, whether by accident or on purpose.
Senior level
7. Your company is worried about ransomware or a rogue admin wiping S3 data. How would you protect it?
Why they ask this: They want defence in depth that still holds when the person with admin rights is the problem.
How you might answer: For critical data I’d use versioning with Object Lock in compliance mode, and replicate to a separate account with a different owner, without delete marker replication. SCPs would block changes to the lifecycle and versioning settings. I’d also turn on MFA delete for root and use AWS Backup for S3 with a locked vault.
8. You have 2 PB of mixed data in S3 and need to cut costs. How would you plan the lifecycle rules?
Why they ask this: It’s cost engineering at scale. At this size, a careless rule can cost more than it saves.
How you might answer: I’d use Storage Lens and access logs to group the data by access pattern and object size. Where the pattern is unknown I’d go with Intelligent-Tiering, and I’d move large cold objects by age while skipping the small ones. And before applying anything to billions of objects, I’d work out what the transition requests would cost.
Quick quiz
Q1. What does a simple DELETE do in a versioned bucket?
- Removes all versions
- Adds a delete marker
- Suspends versioning
- Moves the object to Glacier
Show answer
B: The object is hidden behind a delete marker and the versions remain.
Q2. What is the minimum age for a Standard-IA lifecycle transition?
- 1 day
- 7 days
- 30 days
- 90 days
Show answer
C: S3 needs at least 30 days before a STANDARD_IA transition.
Q3. Which objects does a new replication rule copy?
- All existing objects
- Only objects written after the rule exists
- Only deleted objects
- Only tagged objects
Show answer
B: Objects that already existed need S3 Batch Replication.
Q4. What must the destination bucket have for replication?
- Public access
- Versioning enabled
- Lifecycle rules
- The same Region
Show answer
B: The source and the destination both need versioning.
Q5. Why didn’t aws s3 rb --force work on a versioned bucket?
- Versions and delete markers remain
- The bucket was encrypted
- Replication was on
- The CLI was old
Show answer
A: You have to delete every version and marker first.
Quick recap
- Versioning keeps every version, and a delete only adds a marker that you can remove.
- Whenever you turn on versioning, add a noncurrent version expiration rule too.
- Standard-IA transitions need at least 30 days, and tiny objects get skipped by default.
- Replication needs versioning on both sides and only copies new objects.
- Remove-LabBucket.ps1 deletes every version before it deletes a bucket.
Next lesson
Lesson 19: Route 53 DNS → You’ll create hosted zones and records, use private DNS inside saat-vpc and work through name resolution problems.
Further reading: S3 lifecycle rules
Want to go deeper into S3 lifecycle rules? Read Managing the lifecycle of objects and Replicating objects within and across Regions. You can also see the full plan for this course on the AWS Cloud Administration course page.
