Skip to content

Lesson 4 of 30Core services

S3

Store files in S3, choose storage classes and lifecycle rules, lock buckets down, and hand out presigned URLs.

15 min read0/4 questions

S3 (Simple Storage Service) is where nearly every AWS app keeps its files: user uploads, images, backups, logs, static websites, data lake tables. It stores objects with 11 nines of durability, scales without you thinking about it, and is also the service behind the most famous cloud data leaks. Using it well means knowing both its storage classes and its permission model.

Buckets, objects and keys

S3 has two concepts:

  • A bucket is a container with a globally unique name, like acme-uploads-prod. It lives in one Region.
  • An object is a file plus metadata, up to 5 TB. Each object has a key, its full name inside the bucket.

There are no real folders. The key users/42/avatar.png is one string. The console shows users/ and 42/ as folders because it groups keys by prefix (the part before a /). Prefixes matter because listing and lifecycle rules work on them, and S3's request throughput scales per prefix.

the CLI
aws s3 mb s3://acme-uploads-prod --region us-east-1aws s3 cp avatar.png s3://acme-uploads-prod/users/42/avatar.pngaws s3 ls s3://acme-uploads-prod/users/42/aws s3 sync ./dist s3://acme-site-prod --delete
Pythonprefixes.py
keys = [ "users/42/avatar.png", "users/42/cover.jpg", "users/7/avatar.png", "logs/2026/10/20/app.log",] def list_prefix(keys, prefix, delimiter="/"): files, folders = [], set() for key in keys: if not key.startswith(prefix): continue rest = key[len(prefix):] if delimiter in rest: folders.add(prefix + rest.split(delimiter)[0] + delimiter) else: files.append(key) return sorted(folders), files print(list_prefix(keys, "users/"))print(list_prefix(keys, "users/42/"))
Output
Press Run (⌘ Enter) to see what happens.

That is roughly what ListObjectsV2 with Prefix and Delimiter does, and why the console can pretend there are folders.

Quick check
You 'rename a folder' in S3 from old/ to new/ and it has 10,000 files. What actually happens?
Need a nudge? A hint rules out a wrong answer.

Storage classes and lifecycle rules

Every object has a storage class that trades storage price against retrieval cost and speed. Example prices below are approximate us-east-1 list prices per GB-month; they change, so treat them as rough ratios.

S3 storage classes, hot to cold
  1. S3 Standardabout $0.023/GB, instant, no retrieval fee
  2. S3 Intelligent-Tieringmoves objects between tiers by access pattern
  3. S3 Standard-IAabout $0.0125/GB, instant, per-GB retrieval fee
  4. S3 One Zone-IAcheaper, but one AZ only
  5. S3 Glacier Instant Retrievalabout $0.004/GB, milliseconds, higher retrieval fee
  6. S3 Glacier Flexible Retrievalminutes to hours to restore
  7. S3 Glacier Deep Archiveabout $0.001/GB, up to 12+ hours to restore

Standard is the default. Best for data read often, like app images and active uploads.

1/4

A lifecycle rule moves or deletes objects automatically as they age:

lifecycle.json
{
  "Rules": [
    {
      "ID": "age-out-logs",
      "Filter": { "Prefix": "logs/" },
      "Status": "Enabled",
      "Transitions": [
        { "Days": 30, "StorageClass": "STANDARD_IA" },
        { "Days": 90, "StorageClass": "GLACIER_IR" },
        { "Days": 365, "StorageClass": "DEEP_ARCHIVE" }
      ],
      "Expiration": { "Days": 2555 }
    }
  ]
}
aws s3api put-bucket-lifecycle-configuration \  --bucket acme-logs --lifecycle-configuration file://lifecycle.json
Quick check
You keep invoices for 7 years for legal reasons. They are almost never read, and when an auditor asks, a 12-hour wait is fine. Cheapest class?
Need a nudge? A hint rules out a wrong answer.

Versioning and encryption

Versioning keeps every version of an object. Overwrite report.pdf and the old one is still there; delete it and S3 adds a delete marker instead of destroying data. Turn it on for anything you would cry about losing, and add a lifecycle rule to expire old noncurrent versions so storage does not grow forever.

Encryption at rest is on by default: since 2023, every new object is encrypted with S3-managed keys (SSE-S3). If you need control over the key (who can use it, audit logs of its use), choose SSE-KMS with a key in AWS KMS. Encryption in transit means HTTPS, which you can enforce with a bucket policy condition on aws:SecureTransport.

Who can read it: Block Public Access and bucket policies

S3 permissions combine IAM policies (on the caller) with an optional bucket policy (on the bucket). On top of both sits Block Public Access, a set of switches that override any policy that would make the bucket public. It is on by default for new buckets. Leave it on unless the bucket is a deliberately public website, and even then prefer CloudFront in front (below).

bucket policy: only the app role can read and write
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": { "AWS": "arn:aws:iam::123456789012:role/api-task-role" },
      "Action": ["s3:GetObject", "s3:PutObject"],
      "Resource": "arn:aws:s3:::acme-uploads-prod/*"
    },
    {
      "Effect": "Deny",
      "Principal": "*",
      "Action": "s3:*",
      "Resource": ["arn:aws:s3:::acme-uploads-prod", "arn:aws:s3:::acme-uploads-prod/*"],
      "Condition": { "Bool": { "aws:SecureTransport": "false" } }
    }
  ]
}

Presigned URLs: let the browser talk to S3 directly

Users uploading a 200 MB video should not stream it through your API server. Instead your API creates a presigned URL: a normal S3 URL with a signature and expiry in the query string, signed with your app's credentials. Whoever holds it can do exactly one thing (PUT this key, or GET that key) until it expires.

Direct upload with a presigned URL
BrowserAPIS3POST /uploads {name, type}sign URL (5 min)200 {url}PUT video (200 MB)200 OK

The browser asks your API for permission to upload.

1/5
api/uploads.py
import boto3
 
s3 = boto3.client("s3")
 
def create_upload_url(user_id: int, file_id: str) -> str:
    return s3.generate_presigned_url(
        "put_object",
        Params={"Bucket": "acme-uploads-prod", "Key": f"users/{user_id}/{file_id}.mp4"},
        ExpiresIn=300,
    )
Pythonwhat a signature check does
import hashlib, hmac, time SECRET = b"server-side-secret" def sign(method, key, expires_at): msg = f"{method}\n{key}\n{expires_at}".encode() return hmac.new(SECRET, msg, hashlib.sha256).hexdigest()[:16] def verify(method, key, expires_at, sig, now): if now > expires_at: return "expired" return "ok" if hmac.compare_digest(sig, sign(method, key, expires_at)) else "bad signature" now = int(time.time())exp = now + 300sig = sign("PUT", "users/42/abc.mp4", exp) print(verify("PUT", "users/42/abc.mp4", exp, sig, now))print(verify("PUT", "users/7/abc.mp4", exp, sig, now))print(verify("PUT", "users/42/abc.mp4", exp, sig, now + 600))
Output
Press Run (⌘ Enter) to see what happens.

Real SigV4 is more involved, but the idea is the same: change the key, the method or the expiry, and the signature no longer matches.

Quick check
Your presigned PUT URL for users/42/abc.mp4 leaks in a log. What can someone do with it?
Need a nudge? A hint rules out a wrong answer.

Static websites and event notifications

S3 can host a static site (your React or Next.js export), but the modern setup keeps the bucket private and puts CloudFront in front, using Origin Access Control so only CloudFront can read the bucket. You get HTTPS, a custom domain and edge caching. Lesson 10 builds it.

S3 can also emit events. When an object is created, S3 can invoke a Lambda function, send to an SQS queue or SNS topic, or publish to EventBridge. The classic example: a user uploads photo.jpg, a Lambda makes a thumbnail.

Upload triggers processing
BrowserBrowseruploads bucket: users/*uploads bucketusers/*make-thumbnail: Lambdamake-thumbnailLambdathumbs bucketthumbs bucketCloudFrontCloudFrontpresigned PUTObjectCreatedPutObjectOAC readGET image

The browser uploads straight to S3 with a presigned URL.

1/4
Match the pairs0/5 matched

Match each need to the S3 feature.

Choose an item, then its match on the other side.
ChallengeEasy

Which storage class is this object in?

An S3 lifecycle configuration moves objects to cheaper storage classes as they age. You get an object's age in days and a list of transition rules like {"days": 30, "storage_class": "STANDARD_IA"}. Rules may come in any order.

Return the storage class the object is in now: the class of the rule with the largest days that is less than or equal to the age. If no rule has kicked in yet, the object is still in "STANDARD".

rules = [{"days": 90, "storage_class": "GLACIER_IR"},
         {"days": 30, "storage_class": "STANDARD_IA"},
         {"days": 365, "storage_class": "DEEP_ARCHIVE"}]
current_class(10, rules)   →  "STANDARD"
current_class(45, rules)   →  "STANDARD_IA"
current_class(400, rules)  →  "DEEP_ARCHIVE"
def current_class(age_days: int, rules: list[dict]) -> str: pass
Key terms
object key
The full name of an object in a bucket, like users/42/avatar.png. Folders are just shared prefixes.
storage class
Price and access tier for an object: Standard, IA, Intelligent-Tiering, Glacier classes.
lifecycle rule
Automatic transitions to cheaper classes or deletion as objects age.
Block Public Access
Bucket and account switches that override any policy or ACL that would make data public.
presigned URL
A time-limited URL signed by your credentials that allows one specific GET or PUT.
versioning
Keeps every version of an object; deletes add a delete marker instead of destroying data.