Storage: S3, EBS & EFS

System Design · Cloud Building Blocks · Basics · 20 min

Choose between block, file and object storage, and use S3 well: keys, storage classes, lifecycle rules, versioning and presigned URLs.

A giant coat check: you hand over any bag (object), get a ticket (key), and the attendant keeps several copies in different buildings; old bags are slowly moved to cheaper back rooms, and you can give a friend a ticket that only works for ten minutes.

The idea in everyday words

EBS is your laptop's own hard drive: fast, but plugged into one machine. EFS is a shared network drive the whole office can open at once. S3 is a self-storage warehouse with numbered lockers: you can't edit a box inside it, you swap the whole box, but it holds unlimited boxes and practically never loses one.

Block, file and object storage

Block (EBS) File (EFS) Object (S3)
What you see A raw disk you format A folder tree (NFS) Buckets of objects by key
Attached to One EC2 instance, same AZ (with rare multi-attach exceptions) Many instances across AZs Anything over HTTPS
Change part of a file? Yes, any block Yes No, you replace the whole object
Scales to Size you provision Grows automatically Practically unlimited
Typical use Boot volumes, databases on EC2 Shared content, home dirs, lift-and-shift apps Images, videos, backups, data lakes, static sites
  • EBS volumes come in SSD types (gp3 for general use, io2 for high IOPS) and HDD types. Snapshots are point-in-time backups stored in S3 behind the scenes.
  • Instance store is a disk physically on the host: very fast, but gone when the instance stops.
  • FSx offers managed Windows File Server, Lustre (HPC), NetApp ONTAP and OpenZFS when you need those exact file systems.

Rule of thumb: database on an instance → EBS. Many servers share files → EFS. Everything else, especially user uploads → S3.

Other clouds: GCP has Persistent Disk, Filestore and Cloud Storage; Azure has Managed Disks, Azure Files and Blob Storage. Open source: MinIO or Ceph give you S3-compatible object storage.

S3 basics: buckets, keys, prefixes

  • A bucket has a globally unique name and lives in one Region.
  • An object is bytes plus metadata, up to 5 TB. Use multipart upload for big files (parallel, resumable).
  • The key is the object's full name: photos/2025/06/cat.jpg. There are no real folders. photos/2025/ is just a prefix, and the console draws it as a folder.
  • Since 2020, S3 gives strong read-after-write consistency: after a successful PUT, every GET sees the new object.
  • Prefixes also matter for speed: S3 scales request rates per prefix, so spreading hot keys across prefixes helps at very high request rates.

Secure by default today: new buckets have Block Public Access on, ACLs disabled (the bucket owner owns every object), and objects are encrypted at rest by default (SSE-S3). Use SSE-KMS when you need key-level audit and control.

# S3 keys are flat strings. "Folders" are just a common prefix.
keys = ["photos/2025/cat.jpg", "photos/2025/dog.jpg", "photos/2024/sun.jpg", "logs/app.log"]
prefix = "photos/2025/"
print([k for k in keys if k.startswith(prefix)])
folders = sorted({k.split("/")[0] + "/" for k in keys})
print("top-level 'folders':", folders)

Durability vs availability, and storage classes

  • Durability = the chance your data survives. S3 is designed for 99.999999999% (11 nines) by storing copies across multiple AZs. Store 10 million objects and you'd expect to lose one about every 10,000 years.
  • Availability = the chance you can read it right now. S3 Standard is designed for 99.99%. A short outage doesn't lose data.

Storage classes trade storage price against access price and speed:

Class Best for Read speed Catch
Standard Hot data Milliseconds Highest storage price
Intelligent-Tiering Unknown or changing access Milliseconds (archive tiers optional) Small monitoring fee per object
Standard-IA Rarely read, needed fast Milliseconds Retrieval fee, minimum storage duration
One Zone-IA Re-creatable data Milliseconds Only one AZ
Glacier Instant Retrieval Archive read a few times a year Milliseconds Higher retrieval fee
Glacier Flexible Retrieval Archives, backups Minutes to hours (restore first) Restore step
Glacier Deep Archive Compliance, 'just in case' Hours Slowest, cheapest
Express One Zone Very low latency, one AZ Single-digit ms One AZ, different bucket type

How to think: cheaper storage = more expensive or slower reads. Pick by how often and how fast you read. Check the S3 pricing page for current prices.

Lifecycle rules and versioning

A lifecycle rule says "for objects under this prefix (or tag), move them to class X after N days, and delete them after M days". S3 applies it for you in the background, so you never write a cleanup job.

{
  "Rules": [{
    "ID": "logs-tiering",
    "Filter": { "Prefix": "logs/" },
    "Status": "Enabled",
    "Transitions": [
      { "Days": 30, "StorageClass": "STANDARD_IA" },
      { "Days": 90, "StorageClass": "GLACIER" }
    ],
    "Expiration": { "Days": 365 }
  }]
}

When several rules match one object, S3 resolves conflicts in a safe, cheap direction: expiration wins over transition, and between two transitions the cheaper (colder) class wins.

Versioning keeps every version of an object. A DELETE just adds a delete marker (the object looks gone, but older versions remain). That protects against accidents and ransomware, but old versions cost money, so add a noncurrent version expiration rule. Object Lock adds write-once-read-many retention for compliance.

Watch out for minimum storage durations in the IA and Glacier classes: moving tiny or short-lived objects there can cost more, not less.

The 30-day rule for lifecycle. A lifecycle rule can only move an object from Standard to Standard-IA or One Zone-IA once it is at least 30 days old. A rule that says "after 1 day" to an IA class is rejected. (You can upload straight into Standard-IA with a PUT; the 30-day limit is only for lifecycle transitions.) See S3 lifecycle transition limits.

Presigned URLs and CloudFront in front of S3

Problem: users upload 50 MB videos. Streaming them through your API servers wastes CPU, memory and bandwidth.

Presigned URL: your backend (which has an IAM role) signs a URL that allows one action (PUT or GET) on one key until an expiry time. The client then talks to S3 directly.

  1. Client asks your API: "I want to upload".
  2. API checks the user, chooses the key (never trust a client path), and signs the URL. This is local math with the role's credentials: no call to S3.
  3. Client PUTs the bytes straight to S3.
  4. S3 recomputes the signature, checks expiry and that the signer is allowed. Change anything and you get 403.
  5. S3 emits an event (to Lambda, SQS or EventBridge) to process the file.
url = s3.generate_presigned_url(
    "put_object",
    Params={"Bucket": "uploads-bucket", "Key": "uploads/user42/7f3a.jpg", "ContentType": "image/jpeg"},
    ExpiresIn=300,   # seconds
)

A URL signed with a role's temporary credentials stops working when those credentials expire, even if ExpiresIn is longer.

Reads at scale: put CloudFront in front of the bucket. Edge locations cache popular objects near users; Origin Access Control (OAC) lets only CloudFront read the private bucket. For paid or private content, use CloudFront signed URLs or signed cookies.

Other clouds: GCP Cloud Storage has signed URLs and Autoclass; Azure Blob Storage uses SAS tokens and access tiers.

Step by step

  1. Ask:

    The browser calls POST /uploads with its login token. It never holds AWS credentials.

  2. Sign:

    A Lambda behind API Gateway picks key uploads/user42/7f3a.jpg and signs 'PUT + key + expiry 300 s' with its IAM role's credentials.

  3. Upload direct:

    The browser PUTs 4 MB straight to S3. Your API servers never touch the bytes.

  4. Verify:

    S3 recomputes the signature from the request. Same key + not expired + signer allowed s3:PutObject → 200. A changed key gives 403 SignatureDoesNotMatch; a late request gives 403 'Request has expired'.

  5. React:

    S3 sends ObjectCreated to a Lambda that makes a thumbnail. Uploads stay fast even if thumbnails lag.

  6. Age out:

    Lifecycle: logs/ objects move to Standard-IA at day 30, Glacier at day 90 and are deleted at day 365; backups/ go to Deep Archive at day 180.

Code example

import hmac, hashlib

# A tiny mock of S3: versioned bucket + presigned URLs (real S3 uses SigV4, same idea).
SECRET = b"role-temporary-secret"
bucket = {}           # key -> list of versions (newest last)

def put(key, data):
    bucket.setdefault(key, []).append(data)
    return len(bucket[key])          # version number

def delete(key):
    bucket.setdefault(key, []).append(None)   # versioning: a delete marker

def get(key):
    versions = bucket.get(key, [])
    return versions[-1] if versions else None

def presign(method, key, expires_at):
    msg = f"{method}\n{key}\n{expires_at}".encode()
    return hmac.new(SECRET, msg, hashlib.sha256).hexdigest()[:16]

def s3_check(method, key, expires_at, signature, now):
    if now > expires_at:
        return "403 Request has expired"
    if not hmac.compare_digest(presign(method, key, expires_at), signature):
        return "403 SignatureDoesNotMatch"
    return "200 OK"

sig = presign("PUT", "uploads/user42/cat.jpg", expires_at=1300)
print("signature:", sig)
print(s3_check("PUT", "uploads/user42/cat.jpg", 1300, sig, now=1010))
print(s3_check("PUT", "uploads/admin/evil.jpg", 1300, sig, now=1010))
print(s3_check("PUT", "uploads/user42/cat.jpg", 1300, sig, now=1600))

put("notes.txt", "v1"); put("notes.txt", "v2"); delete("notes.txt")
print("GET after delete:", get("notes.txt"))
print("versions kept:", bucket["notes.txt"])

Complexity

  • Time: O(n × r × t): n objects, r rules, t transitions per rule
  • Space: O(n): one result entry per object

Interview tips

  • For uploads, always say: 'The client gets a presigned URL and uploads directly to S3; S3 events trigger processing.'

  • Separate metadata from blobs: 'Photo metadata in DynamoDB, the bytes in S3, served through CloudFront.'

  • Mention lifecycle rules and storage classes whenever data grows forever (logs, media, backups).

  • Know durability (11 nines, designed) vs availability (99.99% for Standard, designed) and that they are different promises.

  • Keep buckets private: Block Public Access on, CloudFront with Origin Access Control for public reads.

Challenge: Lifecycle Rule Simulator

Simulate S3 lifecycle rules. Write apply_lifecycle(objects, rules).

  • objects: list of [key, age_days].
  • rules: list of {"prefix": str, "transitions": [[days, class], ...], "expire_days": int or null}.
  • Classes from warm to cold: STANDARD, STANDARD_IA, GLACIER_IR, GLACIER, DEEP_ARCHIVE. Every object starts in STANDARD.

A rule applies if the key starts with its prefix. A transition is reached when age >= days. Like real S3 conflict resolution:

  1. If any applying rule's expire_days is reached → "EXPIRED".
  2. Otherwise the coldest class reached by any applying rule wins.

Return a dict {key: class_or_EXPIRED}.

Example:

apply_lifecycle([["logs/a", 45], ["logs/b", 400], ["img/x", 999]],
                [{"prefix": "logs/", "transitions": [[30, "STANDARD_IA"], [90, "GLACIER"]], "expire_days": 365}])
→ {"logs/a": "STANDARD_IA", "logs/b": "EXPIRED", "img/x": "STANDARD"}

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Cloud Building Blocks

Previous: Compute on AWS: EC2, Lambda, ECS/Fargate, EKS · Next: VPC Networking