Thuta Learning
AWS Advanced
Data at ScaleDevOpsAdvanced

S3 Advanced: Storage Classes, Lifecycle, Versioning and Object Lock

AWS AdvancedLesson 2350 min

What you'll walk away with

  • Pick storage classes by access pattern and cut cost with lifecycle rules and Intelligent-Tiering
  • Explain how versioning, delete markers and CRR/SRR replication work
  • Tell apart Object Lock governance and compliance modes, and retention versus legal hold
  • Use presigned URLs, Block Public Access, bucket policies and event notifications safely

Explain it simply

Explain it simply

In AWS Fundamentals you created buckets, uploaded objects and hosted a static website. Now you will learn to manage data across its whole life. Think of S3 as a big warehouse: things used every day sit on the front shelves, things used once a month go to the back room, and documents you must keep by law go to the basement.

A lifecycle rule is the worker who moves items automatically when their time comes. Versioning keeps a copy of every edit, and Object Lock is a sealed safe that nobody can open before a set date.

Problem → Why → Solution

The problem: expensive, fragile and failing the audit

A company keeps invoice PDFs and application logs in one bucket, all in S3 Standard, forever. Nobody reads most logs after a week, yet the bill rises every month. One day a bug in a deploy script runs sync --delete and removes thousands of invoices; versioning was never enabled, so there is nothing to restore.

A month later the auditors require invoices to be kept for seven years in a form that cannot be changed or deleted (WORM). Then a developer turns off Block Public Access to send one file to a partner, and the whole bucket is one policy edit away from being public.

what-went-wrong.sh
# BAD 1: no versioning, so --delete removes "extra" objects permanently
aws s3 sync ./export s3://acme-invoices-111122223333/ --delete

# BAD 2: switching off Block Public Access to share a single file
aws s3api delete-public-access-block --bucket acme-invoices-111122223333

S3 defaults are built for simplicity, not for data lifecycles

In a new bucket every object stays in the Standard class forever, and overwrites and deletes are immediate and final. Cost, recovery and compliance depend on features you must switch on yourself (lifecycle, versioning, Object Lock), and sharing a file never needs public access: that is what presigned URLs are for.

Core concept: storage classes, lifecycle, versioning

Every storage class has the same durability (all except One Zone-IA store data across at least three AZs). What differs is the pricing shape: colder classes charge less per GB stored but add retrieval fees, a minimum storage duration (30, 90 or 180 days) and a minimum billable object size. Choosing a class is really a question of how often you will read the data and how long you will keep it.

Storage classUse it forWatch out for
S3 StandardFrequently read dataHighest price per GB stored
S3 Intelligent-TieringUnknown or changing access patternsPer-object monitoring fee; objects under 128 KB are not auto-tiered
S3 Standard-IARead about monthly, needs millisecond accessRetrieval fee, 30-day minimum, 128 KB minimum size
S3 One Zone-IAData you can re-createSingle AZ: lost if that AZ is destroyed
S3 Glacier Instant RetrievalRead about quarterly, still instantly90-day minimum, higher retrieval fee
S3 Glacier Flexible RetrievalArchives that can wait minutes to hours90-day minimum; restore before reading
S3 Glacier Deep ArchiveCompliance archives read rarely180-day minimum; restores take hours

A lifecycle rule selects objects by prefix or tag and, based on their age in days, automatically changes their class (transition) or deletes them (expiration). Use lifecycle when you know the access pattern in advance. When you do not, S3 Intelligent-Tiering watches each object: after 30 days without access it moves to the Infrequent Access tier, after 90 days to the Archive Instant Access tier, and when it is read again it moves back to the Frequent tier with no retrieval fee.

Noncurrent version
In a versioned bucket, when an object is overwritten or deleted, the previous version becomes a noncurrent version and stays in the bucket. You keep paying to store it.

With versioning on, every overwrite creates a new version, and a delete without a version ID does not really delete anything: it just adds a delete marker. Remove the marker and the object is back. Once enabled, versioning can never return to unversioned, only be suspended. Always pair it with a NoncurrentVersionExpiration lifecycle action so old versions do not pile up.

text
LIFECYCLE OF ONE INVOICE OBJECT
-------------------------------
  day 0        day 30          day 90             day 365
  PUT -------> STANDARD_IA --> GLACIER_IR -------> DEEP_ARCHIVE
  (Standard)   (min 30 days)   (min 90 days)       (min 180 days)

  overwrite / delete (versioned bucket):
  current v2 --> becomes noncurrent --> expired after N noncurrent days
  delete     --> delete marker on top; remove the marker to restore
Mental model: manage data by its age
  1. Write lands in Standard (versioned)
  2. Lifecycle tiers it down as it ages
  3. Old versions expire on a schedule
  4. Object Lock blocks deletes if required
  5. Share via presigned URL, never public

Choosing a class comes down to two questions: how often will it be read, and how long will it be kept?

Pattern: a lifecycle configuration in JSON

lifecycle.json
{
  "Rules": [
    {
      "ID": "invoices-tiering",
      "Filter": { "Prefix": "invoices/" },
      "Status": "Enabled",
      "Transitions": [
        { "Days": 30, "StorageClass": "STANDARD_IA" },
        { "Days": 90, "StorageClass": "GLACIER_IR" },
        { "Days": 365, "StorageClass": "DEEP_ARCHIVE" }
      ],
      "NoncurrentVersionExpiration": {
        "NoncurrentDays": 90,
        "NewerNoncurrentVersions": 3
      },
      "AbortIncompleteMultipartUpload": { "DaysAfterInitiation": 7 }
    },
    {
      "ID": "expire-app-logs",
      "Filter": { "Prefix": "logs/" },
      "Status": "Enabled",
      "Expiration": { "Days": 90 },
      "NoncurrentVersionExpiration": { "NoncurrentDays": 7 },
      "AbortIncompleteMultipartUpload": { "DaysAfterInitiation": 7 }
    }
  ]
}

Apply it with aws s3api put-bucket-lifecycle-configuration --bucket <bucket> --lifecycle-configuration file://lifecycle.json. The first rule steps invoices down through three classes by age and deletes noncurrent versions after 90 days (while still keeping the newest three). The second rule deletes logs at 90 days. AbortIncompleteMultipartUpload cleans up parts of unfinished multipart uploads, which are invisible but still billed. A new lifecycle configuration replaces the old one, so keep all rules in one file.

Versioning, lifecycle and a presigned URL with boto3

This script enables versioning on a bucket, writes one object twice and then deletes it. You will see that the delete only adds a delete marker, and then recover the object by removing the marker. Finally it applies a lifecycle rule and creates a presigned URL valid for five minutes.

Version IDs and signatures change on every run, so they are not printed; the script prints only stable facts (version counts, content, signing algorithm). The presigned URL is signed locally, so it needs no network call. To run it in your own account, create the bucket first with aws s3api create-bucket and change the bucket name to one of your own.

s3_lifecycle_demo.py
from urllib.parse import parse_qs, urlsplit

import boto3
from botocore.config import Config

BUCKET = "acme-invoices-111122223333"
KEY = "2026/inv-001.pdf"
s3 = boto3.client("s3", region_name="us-east-1",
                  config=Config(signature_version="s3v4"))

# 1. Versioning: an overwrite keeps the old copy as a noncurrent version
s3.put_bucket_versioning(Bucket=BUCKET,
                         VersioningConfiguration={"Status": "Enabled"})
for body in (b"invoice v1", b"invoice v2"):
    s3.put_object(Bucket=BUCKET, Key=KEY, Body=body)

# 2. A plain delete on a versioned bucket only adds a delete marker
s3.delete_object(Bucket=BUCKET, Key=KEY)
listing = s3.list_object_versions(Bucket=BUCKET, Prefix="2026/")
print("versions kept:", len(listing["Versions"]))
print("delete markers:", len(listing["DeleteMarkers"]))

# 3. Undo the delete by removing the delete marker itself
marker_id = listing["DeleteMarkers"][0]["VersionId"]
s3.delete_object(Bucket=BUCKET, Key=KEY, VersionId=marker_id)
body = s3.get_object(Bucket=BUCKET, Key=KEY)["Body"].read()
print("restored content:", body.decode())

# 4. Lifecycle: tier current objects down, expire old versions
s3.put_bucket_lifecycle_configuration(
    Bucket=BUCKET,
    LifecycleConfiguration={"Rules": [{
        "ID": "tier-and-expire-invoices",
        "Filter": {"Prefix": "2026/"},
        "Status": "Enabled",
        "Transitions": [{"Days": 30, "StorageClass": "STANDARD_IA"},
                        {"Days": 90, "StorageClass": "GLACIER_IR"}],
        "NoncurrentVersionExpiration": {"NoncurrentDays": 60},
    }]},
)
rule = s3.get_bucket_lifecycle_configuration(Bucket=BUCKET)["Rules"][0]
print("lifecycle:", [t["StorageClass"] for t in rule["Transitions"]])

# 5. Presigned URL: time-limited GET without making anything public
url = s3.generate_presigned_url(
    "get_object", Params={"Bucket": BUCKET, "Key": KEY}, ExpiresIn=300
)
query = parse_qs(urlsplit(url).query)
print("presigned path:", urlsplit(url).path)
print("signature:", query["X-Amz-Algorithm"][0],
      "| expires in:", query["X-Amz-Expires"][0], "s")

Not runnable in the browser

This code runs against a real AWS account, so it cannot run in the browser playground. Try it in your own terminal or in AWS CloudShell.

Code breakdown

  1. Enable versionings3.put_bucket_versioning(..., VersioningConfiguration={"Status": "Enabled"})

    From now on every overwrite creates a new version, which is why both 'invoice v1' and 'invoice v2' are kept.

  2. Delete markers3.delete_object(Bucket=BUCKET, Key=KEY)

    A delete without a version ID removes no data; it puts a delete marker on top as the current version. The output shows versions kept: 2 and delete markers: 1.

  3. Undo by deleting the markers3.delete_object(Bucket=BUCKET, Key=KEY, VersionId=marker_id)

    Deleting the marker by its version ID makes v2 current again. A delete with a version ID is permanent, so restrict s3:DeleteObjectVersion tightly in IAM.

  4. Presigned URLs3.generate_presigned_url("get_object", ..., ExpiresIn=300)

    A URL signed with SigV4 using the caller's credentials. Anyone holding it can GET this one object for five minutes while the bucket stays private. It only works if the signer itself has s3:GetObject.

You should see
versions kept: 2
delete markers: 1
restored content: invoice v2
lifecycle: ['STANDARD_IA', 'GLACIER_IR']
presigned path: /2026/inv-001.pdf
signature: AWS4-HMAC-SHA256 | expires in: 300 s

Replication and Object Lock

S3 Replication copies new objects from one bucket to another asynchronously: Cross-Region Replication (CRR) to another Region, Same-Region Replication (SRR) within one. Both buckets must have versioning enabled, and S3 needs an IAM role to act with. The destination can be in another account; replicating to a separate backup account is a common defence against ransomware or leaked credentials.

Watch three things. Objects that existed before the rule are not copied automatically (use S3 Batch Replication). Delete markers are not replicated by default. And if you need a guarantee on speed, enable S3 Replication Time Control (RTC), which comes with an SLA to replicate most objects within 15 minutes at extra cost.

Object Lock makes an object version WORM (write once, read many). It requires versioning and offers two kinds of protection. A retention period protects the version until a date, while a legal hold is an ON/OFF flag with no expiry, used to preserve data until, say, a legal case is over. One version can have both at once.

ModeWho can shorten or deleteWhen to use it
GovernancePrincipals with s3:BypassGovernanceRetention, using the bypass headerInternal policy, or testing before committing to compliance
ComplianceNobody, including the root user; retention can only be extendedData a regulator requires to be WORM
Legal holdWhoever has s3:PutObjectLegalHold, by turning it OFFPreservation with no known end date
replication-and-lock.sh
# Replication rules live in JSON (role ARN, destination bucket, filters)
aws s3api put-bucket-replication \
  --bucket acme-invoices-111122223333 \
  --replication-configuration file://replication.json

# Hold one invoice for an ongoing legal case (no expiry date)
aws s3api put-object-legal-hold \
  --bucket acme-audit-111122223333 \
  --key invoices/inv-001.pdf \
  --legal-hold Status=ON

Access control, presigned URLs and event notifications

New buckets have Block Public Access on by default and Object Ownership set to 'Bucket owner enforced', which disables ACLs. That is what AWS recommends: control access with bucket policies and IAM policies, not ACLs. Turning on Block Public Access at the account level as well stops a single bucket from being misconfigured into public.

A bucket policy is a resource-based policy, so it can grant access to principals in other accounts, deny any request that is not HTTPS, or allow access only through a VPC endpoint. The policy below rejects every request without TLS and lets a reporting role read only the reports/ prefix.

bucket-policy.json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "DenyInsecureTransport",
      "Effect": "Deny",
      "Principal": "*",
      "Action": "s3:*",
      "Resource": [
        "arn:aws:s3:::acme-invoices-111122223333",
        "arn:aws:s3:::acme-invoices-111122223333/*"
      ],
      "Condition": { "Bool": { "aws:SecureTransport": "false" } }
    },
    {
      "Sid": "AllowReportingRoleRead",
      "Effect": "Allow",
      "Principal": { "AWS": "arn:aws:iam::111122223333:role/reporting" },
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::acme-invoices-111122223333/reports/*"
    }
  ]
}

A presigned URL is the right way to share one file for a limited time. It carries only the signer's permissions and lasts at most seven days with SigV4; if it was signed with temporary credentials (an IAM role), it dies when those credentials expire. Presigned PUT URLs work for uploads too, letting a browser upload straight to S3 without passing through your servers.

Event notifications send a message to an SQS queue, SNS topic or Lambda function when objects are created, deleted and so on. If you enable EventBridge on the bucket, all events flow to EventBridge, which gives richer filtering and many more targets. Notifications are delivered at least once, so write idempotent consumers.

In production

How teams use it in production

Most teams split data into buckets by sensitivity and lifetime: app uploads, logs, the data lake, the audit archive. Every bucket gets versioning, default encryption, Block Public Access, a TLS-only policy and a lifecycle with NoncurrentVersionExpiration from an IaC template, so no hand-made console bucket is left behind without them.

The audit archive is replicated into a separate account with Object Lock in compliance mode, so even production admins cannot delete it. On the cost side, teams use S3 Storage Lens and Storage Class Analysis to find which prefixes have gone cold before writing lifecycle rules. For user uploads, the backend issues a presigned PUT URL, and when the upload lands an event notification triggers a virus-scan and thumbnail Lambda. For the audit bucket they also turn on CloudTrail data events or S3 server access logging, so every read and every delete attempt leaves a record.

Common mistakes

Common mistakes

Versioning without noncurrent expiration

A job that overwrites one file daily creates 365 versions a year, and you pay for all of them. Noncurrent versions do not show in the console's default listing, so the growing bill is often noticed late. Whenever you enable versioning, add NoncurrentVersionExpiration.

Tiering small or short-lived objects

IA and Glacier classes have minimum storage durations and minimum billable sizes, and every lifecycle transition costs a request fee. Move an object that will live 40 days into Glacier and you pay for 90. (By default, lifecycle no longer transitions objects smaller than 128 KB.) Check object sizes and lifetimes before writing rules.

Using compliance mode without testing

Set compliance mode with a mistaken ten-year retention and not even the root user can delete those versions; you pay to store them for ten years. Test with governance mode and short retention first, then switch to compliance.

Expecting replication to copy existing objects

A replication rule only copies objects written after it was added. Use S3 Batch Replication for existing data, or your DR bucket will be only half full.

💰 Cost & Cleanup

S3 charges per GB-month by class, per request, retrieval fees for IA and Glacier, and lifecycle transition request fees (per 1,000 objects). With versioning you pay for every version. Replication adds destination storage, inter-Region data transfer, and an RTC fee if enabled. The classic free tier includes 5 GB of S3 Standard, and this lab's tiny files cost cents at most. An Object Lock bucket can only be emptied after governance retention ends (or with a bypass), so never use compliance mode in a lab.

Clean up when you are done

cleanup.sh
# Release the legal hold from the challenge first
aws s3api put-object-legal-hold --bucket acme-audit-111122223333 \
  --key invoices/inv-001.pdf --legal-hold Status=OFF

# A versioned bucket is only empty when every version and delete marker is gone
for BUCKET in acme-invoices-111122223333 acme-audit-111122223333; do
  aws s3api list-object-versions --bucket "$BUCKET" \
    --query '{Objects: [Versions, DeleteMarkers][].{Key: Key, VersionId: VersionId}}' \
    --output json > versions.json
  aws s3api delete-objects --bucket "$BUCKET" \
    --delete file://versions.json --bypass-governance-retention
  aws s3api delete-bucket --bucket "$BUCKET"
done

Mini challenge

Protect invoices with Object Lock

Create a new audit bucket where every new object automatically gets a default retention. Then place one invoice under legal hold and confirm it cannot be deleted.

  • Create the bucket with Object Lock enabled (this turns on versioning automatically)
  • Set a default retention of GOVERNANCE mode for 1 day
  • Upload invoices/inv-001.pdf and turn its legal hold ON
  • Try deleting it by version ID and confirm you get AccessDenied

Expected: The final delete-object command fails with an AccessDenied error. After the lab, the cleanup script turns the legal hold OFF and deletes with the bypass.

Show hint

Use --object-lock-enabled-for-bucket on create-bucket, then put-object-lock-configuration. Get the version ID with a --query on list-object-versions.

Show solution
solution.sh
BUCKET=acme-audit-111122223333

aws s3api create-bucket --bucket "$BUCKET" --object-lock-enabled-for-bucket

cat > lock.json <<'JSON'
{"ObjectLockEnabled": "Enabled",
 "Rule": {"DefaultRetention": {"Mode": "GOVERNANCE", "Days": 1}}}
JSON
aws s3api put-object-lock-configuration --bucket "$BUCKET" \
  --object-lock-configuration file://lock.json

echo "invoice 001" > inv-001.pdf
aws s3api put-object --bucket "$BUCKET" \
  --key invoices/inv-001.pdf --body inv-001.pdf

aws s3api put-object-legal-hold --bucket "$BUCKET" \
  --key invoices/inv-001.pdf --legal-hold Status=ON

VERSION_ID=$(aws s3api list-object-versions --bucket "$BUCKET" \
  --prefix invoices/inv-001.pdf --query 'Versions[0].VersionId' --output text)

# Expected to fail with AccessDenied (legal hold + governance retention)
aws s3api delete-object --bucket "$BUCKET" \
  --key invoices/inv-001.pdf --version-id "$VERSION_ID"

Quick quiz 1 / 3

You want CRR from us-east-1 to eu-west-1. What is strictly required?

Quick quiz 2 / 3

A regulator requires trade records to be kept for 7 years where nobody, including the root user, can delete them. What do you use?

Quick quiz 3 / 3

A Lambda function creates presigned URLs with ExpiresIn of 7 days, but they stop working after a few hours. Why?

What to remember

  • Pick a storage class by access frequency and retention; colder classes add retrieval fees and minimum durations.
  • Use lifecycle rules when you know the pattern and Intelligent-Tiering when you do not; with versioning, always add NoncurrentVersionExpiration.
  • Replication (CRR/SRR) needs versioning on both buckets and does not copy existing objects.
  • Object Lock compliance mode cannot be bypassed by anyone, governance mode can be bypassed with permission, and a legal hold has no expiry.
  • Keep Block Public Access on, use bucket policies instead of ACLs, and share files with presigned URLs.

Amazon S3 storage classes — AWS Documentation

Managing the lifecycle of objects — AWS Documentation

Locking objects with Object Lock — AWS Documentation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

S3 Advanced: Storage Classes, Lifecycle, Versioning and Object Lock | Thuta Learning