AWS Learning
Storage

Amazon S3 (Simple Storage Service)

Simple Storage Service, Storage Classes, Lifecycle, Security

Amazon S3 (Simple Storage Service)

Mục lục


Tổng quan

Amazon S3 là dịch vụ object storage với khả năng mở rộng không giới hạn, độ bền dữ liệu cao (99.999999999% - 11 nines), và hiệu suất tốt. S3 là một trong những dịch vụ cốt lõi và phổ biến nhất của AWS.

Durability 11 nines là gì?

99.999999999% durability có nghĩa: nếu lưu 10 triệu objects, thống kê bạn sẽ mất 1 object mỗi 10,000 năm.

AWS đạt được điều này bằng cách tự động replicate mỗi object sang ≥3 Availability Zones trong cùng Region - bạn không cần cấu hình gì.

Erasure Coding - Kỹ thuật đằng sau 11 nines

AWS sử dụng Erasure Coding thay vì replicate 3 bản copy đầy đủ, giúp tiết kiệm storage và vẫn đạt durability cao.

Cách hoạt động (ví dụ cấu hình 5+4):

Original file: 1 GB

┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐
│ D1  │ D2  │ D3  │ D4  │ D5  │ P1  │ P2  │ P3  │ P4  │
└─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘
  5 data chunks        +      4 parity chunks

Total: 9 chunks phân tán qua ≥3 AZs
Storage overhead: 180% (thay vì 300% với 3x replication)

Fault Tolerance:

Mất chunksChunks còn lạiKết quả
0-45-9✅ Recover được
5+< 5Mất data

Cần ít nhất 5 chunks bất kỳ để rebuild data gốc.

Tại sao vẫn đạt 11 nines?

  • Chunks phân tán cross-AZ → mất cả 1 AZ vẫn OK
  • Auto-healing: AWS liên tục check và rebuild chunks bị corrupt
  • Xác suất mất 5+ chunks đồng thời: ~10^-15

⚠️ Lưu ý: AWS không công bố chính xác cấu hình erasure coding. 5+4 là thông tin từ nguồn phân tích bên ngoài.

Các kỹ thuật Internal khác của S3

1. Checksums & Data Integrity

S3 sử dụng checksums để đảm bảo data không bị corrupt:

UPLOAD:
  Client tính checksum (MD5, SHA-256, CRC32...)

  Gửi file + checksum lên S3

  S3 tính lại checksum trên server

  So sánh: khớp → store | không khớp → reject ❌

DATA AT REST (liên tục):
  Background job quét storage

  Phát hiện "bit rot" (data corrupt theo thời gian)

  Tự động repair từ chunk ở AZ khác

2. Shuffle Sharding - Giảm "Blast Radius"

Thay vì assign cố định buckets vào drives, AWS random assign:

FIXED (bad):                    SHUFFLE SHARDING (good):
─────────────                   ─────────────────────────
Bucket A → Drives {1, 2}        Bucket A → Drives {1, 5} (random)
Bucket B → Drives {1, 2}        Bucket B → Drives {2, 7} (random)
                               
Nếu Drive 1,2 chết:             Nếu Drive 1,2 chết:
→ A,B mất 100% ❌               → A mất 50%, B mất 50%
                                → Không ai mất hoàn toàn ✅

Lợi ích:

  • Fault isolation: Lỗi không lan rộng
  • Giảm blast radius: Mỗi bucket chỉ bị ảnh hưởng một phần

3. Cell-based Architecture

S3 được chia thành các "cells" độc lập:

AWS Region = "Supercell"
  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐
  │   Cell 1    │  │   Cell 2    │  │   Cell 3    │
  │  (S3 subset)│  │  (S3 subset)│  │  (S3 subset)│
  └─────────────┘  └─────────────┘  └─────────────┘
        │                │                │
        └────────────────┴────────────────┘

              Cells KHÔNG share state
              Lỗi Cell 1 không ảnh hưởng Cell 2,3

4. Two Random Choices (Load Balancing)

Khi cần lưu object vào drive:

Step 1: Random chọn 2 drives (A và B)
Step 2: Check utilization (% đã dùng) của cả 2
Step 3: Chọn drive có utilization THẤP hơn

Ví dụ:
  Drive A: 75% full ████████░░░
  Drive B: 30% full ███░░░░░░░░
  → Chọn Drive B (còn trống nhiều hơn)

Tại sao chỉ cần 2?

  • Random 1: Có thể chọn trúng drive đã full
  • Check tất cả: Quá chậm (hàng nghìn drives)
  • Two Random Choices: Nhanh + load khá đều (toán học chứng minh!)

Tổng kết các kỹ thuật

Kỹ thuậtMục đích
Erasure CodingDurability với ít storage overhead
ChecksumsPhát hiện và sửa data corruption
Shuffle ShardingFault isolation, giảm blast radius
Cell ArchitectureIsolate failures giữa các cells
Two Random ChoicesLoad balancing storage

Ngoại lệ (chỉ lưu trong 1 AZ, durability thấp hơn nếu AZ gặp sự cố):

  • S3 One Zone-IA
  • S3 Express One Zone

Lưu ý: Durability ≠ Availability. S3 Standard có 99.99% availability (có thể unavailable ~52 phút/năm), nhưng data vẫn không bị mất.

Use cases phổ biến:

  • Data lakes và big data analytics
  • Backup và disaster recovery
  • Static website hosting
  • Archive và long-term storage
  • Media hosting (images, videos)
  • Application data storage

Nguồn: What is Amazon S3?


Các khái niệm cơ bản

Buckets

  • Container chứa các objects
  • Tên bucket phải globally unique trên toàn bộ AWS
  • Bucket được tạo trong một Region cụ thể
  • 4 loại bucket:
    • General purpose buckets - bucket thông thường
    • Directory buckets - cho S3 Express One Zone (high performance)
    • Table buckets - cho tabular data
    • Vector buckets - cho vector storage (ML workloads)

Objects

  • Đơn vị lưu trữ cơ bản trong S3
  • Bao gồm: data + key (tên) + metadata
  • Kích thước tối đa: 5 TB per object
  • Upload > 5GB phải dùng multipart upload

Keys & Flat Structure

S3 không có folder/directory thật — nó là flat key-value store:

┌──────────────────────────────────────────────────────────────┐
│          S3 = FLAT KEY-VALUE STORE                           │
├──────────────────────────────────────────────────────────────┤
│                                                              │
│  Bạn TƯỞNG S3 có cấu trúc thư mục:                           │
│  ═══════════════════════════════════                         │
│  📁 photos/                                                  │
│  ├── 📁 2024/                                                │
│  │   ├── 📄 jan/vacation.jpg                                 │
│  │   └── 📄 feb/birthday.jpg                                 │
│  └── 📁 2025/                                                │
│      └── 📄 mar/concert.jpg                                  │
│                                                              │
│  Thực tế S3 lưu như thế này:                                 │
│  ═══════════════════════════                                 │
│  KEY (string)                          → VALUE (object data) │
│  "photos/2024/jan/vacation.jpg"        → [binary data]       │
│  "photos/2024/feb/birthday.jpg"        → [binary data]       │
│  "photos/2025/mar/concert.jpg"         → [binary data]       │
│                                                              │
│  "/" chỉ là KÝ TỰ THƯỜNG trong key — không có ý nghĩa đặc    │
│  biệt với S3. Console hiển thị nó như folder cho dễ nhìn.    │
│                                                              │
└──────────────────────────────────────────────────────────────┘

Key = unique identifier cho object trong bucket, bao gồm toàn bộ "path":

Thành phầnVí dụ
Bucketmy-bucket
Keyphotos/2024/jan/vacation.jpg
Full paths3://my-bucket/photos/2024/jan/vacation.jpg
Prefixphotos/2024/jan/ (phần trước object name)
Object namevacation.jpg

"Folder" trong S3 Console

Khi bạn tạo "folder" trong Console, S3 thực sự tạo một zero-byte object với key kết thúc bằng /:

# Tạo "folder" trong console = tạo object 0 byte
# Key = "photos/2024/"   Size = 0 bytes
 
# Bạn hoàn toàn có thể upload KHÔNG cần "tạo folder" trước:
aws s3 cp photo.jpg s3://my-bucket/photos/2024/jan/photo.jpg
# → S3 tự hiểu "photos/2024/jan/" là prefix, KHÔNG cần tạo trước

Prefix & Delimiter

S3 dùng prefixdelimiter để giả lập hierarchy khi list objects:

# List "root level" — delimiter="/"
aws s3api list-objects-v2 --bucket my-bucket --delimiter "/"
 
# Kết quả:
# CommonPrefixes: ["photos/", "videos/", "docs/"]    ← "folders"
# Contents: ["readme.txt"]                            ← files ở root
 
# List bên trong "photos/" — prefix="photos/", delimiter="/"
aws s3api list-objects-v2 --bucket my-bucket --prefix "photos/" --delimiter "/"
 
# Kết quả:
# CommonPrefixes: ["photos/2024/", "photos/2025/"]   ← "subfolders"
# Contents: []                                        ← không có file trực tiếp

⚠️ Delimiter không bắt buộc phải là /. Bạn có thể dùng bất kỳ ký tự nào, nhưng / là convention phổ biến nhất.

Object Key Naming Rules

RuleChi tiết
Max length1,024 bytes (UTF-8)
Case sensitivePhoto.jpgphoto.jpg
Safe charactersa-z, 0-9, !, -, _, ., *, ', (, )
Cần URL encode&, $, @, =, ;, /, :, +, , ,, ?
Nên tránh\, {, }, ^, %, `, ]

Tại sao flat structure quan trọng?

1. Performance — S3 scale theo PREFIX

S3 tự động phân tán dữ liệu theo prefix. Mỗi prefix được xử lý bởi partition riêng:

┌──────────────────────────────────────────────────────────────┐
│           S3 PARTITIONING THEO PREFIX                        │
├──────────────────────────────────────────────────────────────┤
│                                                              │
│  Mỗi prefix = 1 partition riêng với rate limit riêng:        │
│                                                              │
│  s3://bucket/images/   → Partition A → 5,500 GET + 3,500 PUT │
│  s3://bucket/videos/   → Partition B → 5,500 GET + 3,500 PUT │
│  s3://bucket/logs/     → Partition C → 5,500 GET + 3,500 PUT │
│                                                              │
│  Tổng bucket = 16,500 GET/s + 10,500 PUT/s                   │
│  (3 prefixes × rate mỗi prefix)                              │
│                                                              │
│  Không giới hạn số prefixes → scale gần như vô hạn!          │
│                                                              │
└──────────────────────────────────────────────────────────────┘
MetricPer Prefix
GET/HEAD5,500 requests/second
PUT/COPY/POST/DELETE3,500 requests/second

Prefix là gì trong context performance?

Prefix = phần key trước object name, tính đến dấu / cuối cùng:

Key: "images/2024/jan/photo.jpg"

Các prefix levels:
├── "images/"                ← level 1
├── "images/2024/"           ← level 2
└── "images/2024/jan/"       ← level 3 (S3 partition tại level này)

⚠️ S3 tự quyết định partition ở level nào — bạn không control trực tiếp. Nhưng thiết kế key name hợp lý giúp S3 phân tán hiệu quả hơn.

Ví dụ: Thiết kế key name ảnh hưởng throughput

❌ BAD — tất cả objects chung 1 prefix:
═══════════════════════════════════════
s3://bucket/data/file1.csv
s3://bucket/data/file2.csv
s3://bucket/data/file3.csv
...1 triệu files cùng prefix "data/"
→ Bị bottleneck: chỉ 5,500 GET/s cho TẤT CẢ files

✅ GOOD — phân tán theo nhiều prefixes:
═══════════════════════════════════════
s3://bucket/data/2024/01/file1.csv     ← prefix "data/2024/01/"
s3://bucket/data/2024/02/file2.csv     ← prefix "data/2024/02/"
s3://bucket/data/2024/03/file3.csv     ← prefix "data/2024/03/"
...mỗi tháng 1 prefix riêng
→ 12 prefixes × 5,500 = 66,000 GET/s tổng cộng

Scale reads với parallelization:

10 prefixes đọc song song:
  Prefix 1 ──► 5,500 GET/s ──┐
  Prefix 2 ──► 5,500 GET/s ──┤
  Prefix 3 ──► 5,500 GET/s ──┤
  ...                        ├──► Tổng: 55,000 GET/s
  Prefix 10 ──► 5,500 GET/s ──┘

Khi vượt limit → HTTP 503 Slow Down:

App gửi 8,000 GET/s đến 1 prefix


S3 xử lý 5,500 → OK ✅
S3 từ chối 2,500 → 503 Slow Down ⚠️


S3 tự auto-scale partition (dần dần)


Sau vài phút → S3 handle được 8,000 GET/s

S3 auto-scales gradually — không tức thì. Nếu traffic tăng đột ngột, bạn sẽ nhận 503 errors trong lúc S3 đang scale. Dùng retry with exponential backoff để xử lý.

"Partitioned prefix" — bạn không control được S3 partition ở đâu:

Key: "a/b/c/d/photo.jpg"

Các prefix có thể:  "a/"  "a/b/"  "a/b/c/"  "a/b/c/d/"

    ❌ KHÔNG PHẢI mỗi cái đều có rate limit riêng
    ✅ S3 TỰ CHỌN partition ở 1 level nào đó — bạn không biết

S3 quyết định dựa trên:
  • Key distribution (keys phân bổ thế nào)
  • Access pattern (traffic tập trung ở đâu)
  • Tự động chia nhỏ partition khi traffic tăng

Cái bạn biết chắc: 5,500 GET/s + 3,500 PUT/smức tối thiểu được đảm bảo cho mỗi partition — dù S3 partition kiểu gì.

Trong thực tế, bạn chỉ cần:

  1. Thiết kế key phân tán — spread ra nhiều prefixes → S3 dễ tạo nhiều partition
  2. Monitor 503 Slow Down — nếu có nhiều 503 → key design quá tập trung vào 1 prefix

Lưu ý quan trọng: Trước 2018, AWS khuyến nghị thêm random prefix (hash) vào key để phân tán partition. Bây giờ không cần nữa — S3 đã tự động xử lý, bạn có thể dùng sequential date-based naming bình thường.

2. Không có "rename folder"

"Rename" photos/ → images/ = COPY từng object + DELETE bản cũ
1 triệu objects = 1 triệu COPY + 1 triệu DELETE operations
→ Tốn thời gian + tốn tiền (mỗi COPY/DELETE = 1 request)

3. List performance

ListObjectsV2 trả về max 1,000 keys/request
Bucket có 10 triệu objects → 10,000 API calls để list hết
→ Dùng prefix để thu hẹp scope, tránh list toàn bộ bucket

📖 Nguồn: Object Keys · Using Prefixes · Optimizing Performance

Versioning

  • Lưu giữ nhiều versions của cùng một object
  • Bảo vệ khỏi xóa nhầm và overwrite
  • Bật ở bucket level
  • Mỗi version có Version ID riêng

Storage Classes

S3 cung cấp nhiều storage classes cho các use cases khác nhau. Tất cả đều có durability 99.999999999% (11 nines).

Storage Class được chọn ở đâu?

Lưu ý: Storage class được chọn ở object level, không phải bucket level!

  • Khi upload object → chọn storage class cho object đó (Properties → Storage class)
  • Hoặc dùng Lifecycle rules để tự động chuyển objects giữa các classes
  • Ngoại lệ: S3 Express One Zone dùng Directory buckets - loại bucket riêng, phải chọn khi tạo bucket

Bảng so sánh tổng quan

Storage ClassAZsAvailabilityMin DurationMin Billable SizeStandard RetrievalBulk RetrievalRetrieval Fee
S3 Standard≥399.99%NoneNoneMillisecondsN/ANone
S3 Express One Zone199.95%NoneNoneSingle-digit millisecondsN/ANone
S3 Intelligent-Tiering≥399.9%NoneNoneMilliseconds***N/A***None
S3 Standard-IA≥399.9%30 days128 KB*MillisecondsN/A
S3 One Zone-IA199.5%30 days128 KB*MillisecondsN/A
S3 Glacier Instant Retrieval≥399.9%90 days128 KB*MillisecondsN/A
S3 Glacier Flexible Retrieval≥399.99%**90 days+40 KB metadata3-5 hours5-12 hours
S3 Glacier Deep Archive≥399.99%**180 days+40 KB metadataWithin 12 hoursWithin 48 hours

*Min billable size: Bạn vẫn upload được file nhỏ hơn, nhưng bị charge như 128 KB **Sau khi restore ***Với S3 Intelligent-Tiering, Frequent/Infrequent/Archive Instant Access = millisecond access. Nếu bật optional Archive Access/Deep Archive Access thì object phải restore trước: Standard = 3-5 giờ / within 12 giờ, Bulk = 5-12 giờ / within 48 giờ.

Standard retrieval vs Bulk retrieval:

  • Standard retrieval: lựa chọn mặc định khi restore archived objects, cân bằng giữa tốc độ và chi phí.
  • Bulk retrieval: rẻ hơn cho khối lượng restore lớn, nhưng chậm hơn; phù hợp khi không cần lấy dữ liệu gấp.
  • Lưu ý: Retrieval tier chỉ áp dụng cho S3 Glacier Flexible Retrieval, S3 Glacier Deep Archive, và optional archive tiers của S3 Intelligent-Tiering; các storage class còn lại đọc trực tiếp bằng GET nên ghi N/A.

1. S3 Standard

Use case: Frequently accessed data (truy cập > 1 lần/tháng)

  • Storage class mặc định
  • Millisecond access
  • Không có retrieval fee, min duration, min size
  • Replicate across ≥3 AZs

Phù hợp cho: Websites, mobile apps, gaming, big data analytics


2. S3 Express One Zone

Use case: Ultra-low latency applications (single-digit milliseconds)

  • Nhanh nhất - latency thấp hơn S3 Standard tới 10x
  • Rẻ hơn 50% request costs so với S3 Standard
  • Chỉ lưu trong 1 AZ (bạn chọn AZ nào)
  • Dùng với Directory buckets (không phải general purpose buckets)

Tại sao nhanh hơn?

  • Co-location - chọn cùng AZ với EC2/EKS/Lambda → không có network latency cross-AZ
  • Custom hardware & software - AWS thiết kế riêng cho low-latency
  • Directory buckets - kiến trúc mới, hỗ trợ 2 triệu reads + 200K writes/giây
  • Session-based authorization - giảm overhead authentication mỗi request

Tại sao chỉ 1 AZ?

Đây là trade-off có chủ đích:

S3 Standard:  Write → Replicate to AZ1, AZ2, AZ3 → Confirm (slower, more durable)
S3 Express:   Write → Replicate trong 1 AZ only → Confirm (faster, less resilient)

Cross-AZ replication thêm network latency (vài ms). Để đạt single-digit ms, phải bỏ cross-AZ replication.

Phù hợp cho: ML training, real-time analytics, high-performance computing, cache/temporary data

Trade-off: Không resilient nếu AZ gặp sự cố - chỉ dùng cho data có thể tái tạo hoặc đã có backup ở nơi khác


3. S3 Intelligent-Tiering

Use case: Data có access patterns không biết trước hoặc thay đổi

"Access patterns không biết trước" là gì?

Ví dụ 1: E-commerce product images
- Sản phẩm mới upload → access nhiều (hot)
- 3 tháng sau → có thể vẫn hot, có thể không ai xem
- Bạn KHÔNG BIẾT TRƯỚC sản phẩm nào sẽ bán chạy

Ví dụ 2: User-generated content (YouTube, TikTok)
- Video mới → có thể viral (millions views) hoặc flop (10 views)
- Video cũ → có thể bỗng viral lại sau 1 năm
- Access pattern THAY ĐỔI liên tục, không dự đoán được

Đặc điểm:

  • Tự động di chuyển objects giữa các tiers - không cần quản lý
  • Không có retrieval fees (3 tiers đầu)
  • monitoring fee nhỏ per object (~$0.0025/1000 objects/month)
  • Objects < 128 KB không được monitor, luôn ở Frequent Access tier

5 Access Tiers (bên trong Intelligent-Tiering, không phải storage classes khác):

┌─────────────────────────────────────────────────────┐
│           S3 Intelligent-Tiering (1 storage class)  │
│  ┌───────────────────────────────────────────────┐  │
│  │  Frequent Access tier      ← upload vào đây   │  │
│  │  Infrequent Access tier    ← sau 30 ngày      │  │
│  │  Archive Instant Access    ← sau 90 ngày      │  │
│  │  Archive Access (optional) ← sau 90+ ngày     │  │
│  │  Deep Archive (optional)   ← sau 180+ ngày    │  │
│  └───────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────┘
TierKhi nào chuyểnRetrieval
Frequent AccessDefault khi uploadMilliseconds
Infrequent AccessSau 30 ngày không accessMilliseconds
Archive Instant AccessSau 90 ngày không accessMilliseconds
Archive Access (optional)Sau 90+ ngày, cần activate3-5 hours
Deep Archive Access (optional)Sau 180+ ngày, cần activate12 hours

Lưu ý: Archive Access và Deep Archive Access tiers cần restore trước khi access.

So sánh Intelligent-Tiering vs Lifecycle Rules:

Intelligent-TieringLifecycle Rules
Monitoring fee~$0.0025/1000 objects/thángKhông
Retrieval feeKhông (3 tiers đầu) (từ IA, Glacier)
Cấu hìnhKhông cầnPhải tự định nghĩa rules
Di chuyểnTự động theo access thực tếTheo thời gian cố định
Khi nào Intelligent-Tiering rẻ hơn:
- File có thể bị access bất ngờ
- Lifecycle: Standard → Standard-IA → access → trả retrieval fee mỗi lần
- Intelligent-Tiering: access → KHÔNG fee, tự chuyển tier phù hợp

Khi nào Lifecycle rẻ hơn:
- Biết chắc 100% không access (vd: logs cũ)
- Lifecycle: Standard → Glacier → không trả monitoring fee

Tóm lại:

  • Biết chắc access pattern → Lifecycle rules (tiết kiệm monitoring fee)
  • Không biết / thay đổi → Intelligent-Tiering (tiết kiệm retrieval fee)

4. S3 Standard-IA (Infrequent Access)

Use case: Long-lived data, truy cập không thường xuyên (~1 lần/tháng), cần millisecond access

  • Giá storage rẻ hơn S3 Standard
  • retrieval fee per GB
  • Min storage duration: 30 ngày (xóa sớm vẫn bị charge 30 ngày)
  • Min billable size: 128 KB (object nhỏ hơn vẫn bị charge 128 KB)
  • Replicate across ≥3 AZs

Phù hợp cho: Backups, disaster recovery, older data cần truy cập nhanh

Khi nào dùng: Dữ liệu không thể tái tạo được


5. S3 One Zone-IA

Use case: Giống Standard-IA nhưng chấp nhận risk mất data nếu AZ fail

  • Rẻ hơn ~20% so với Standard-IA
  • Chỉ lưu trong 1 AZ
  • Min storage duration: 30 ngày
  • Min billable size: 128 KB

Phù hợp cho:

  • Secondary backup copies
  • Data có thể tái tạo được
  • Cross-Region Replication destination

Trade-off: Mất data nếu AZ bị destroy (động đất, lũ lụt)


6. S3 Glacier Instant Retrieval

Use case: Archive data, hiếm khi access (~1 lần/quý), nhưng cần millisecond retrieval

  • Storage cost thấp hơn Standard-IA 68%
  • Millisecond access - không cần restore
  • Min storage duration: 90 ngày
  • Min billable size: 128 KB
  • Retrieval fee cao hơn Standard-IA

Phù hợp cho: Medical images, news media assets, user-generated content archives


"Restore" là gì?

Một số storage classes (Glacier Flexible, Deep Archive) lưu data trên cold storage (có thể là tape) để giảm giá. Khi cần access, phải "restore" trước:

Millisecond access (Standard, IA, Glacier Instant):
  GET object → nhận data ngay lập tức

Cần restore (Glacier Flexible, Deep Archive):
  GET object → Error 403 (phải restore trước!)
  
  Bước 1: POST restore request
  Bước 2: Chờ 1 phút → 48 giờ (tuỳ option và storage class)
  Bước 3: AWS copy object tạm sang tier có thể access
  Bước 4: GET object → nhận data
  Bước 5: Sau X ngày (bạn chọn), bản copy tạm bị xóa

Tại sao thiết kế vậy? Đổi lại thời gian chờ → giá storage rẻ hơn rất nhiều.


7. S3 Glacier Flexible Retrieval

Use case: Archive data, access ~1 lần/năm, không cần immediate access

  • Storage cost rất thấp
  • Min storage duration: 90 ngày
  • Phải restore trước khi access (không real-time)

Retrieval options:

OptionThời gianCost
Expedited1-5 minutesCao nhất
Standard3-5 hoursTrung bình
Bulk5-12 hoursThấp nhất

⚠️ Expedited không phải lúc nào cũng guaranteed! AWS chỉ nói "typically 1–5 minutes" — khi hệ thống bận, capacity có thể không có sẵn.

Provisioned Retrieval Capacity

Nếu cần Expedited Retrieval luôn sẵn sàng trong mọi tình huống (ví dụ: audit bất ngờ, compliance yêu cầu), phải mua thêm Provisioned Retrieval Capacity.

Không có Provisioned Capacity:
  Expedited request → "Thường" 1-5 phút ✅
                    → Khi hệ thống bận: bị từ chối ❌

Có Provisioned Capacity:
  Expedited request → Luôn được đảm bảo ✅ (under all circumstances)
Thông sốGiá trị
Throughput mỗi unitTối đa 150 MB/s
Số lượng retrieval≥3 Expedited retrievals mỗi 5 phút
MuaTheo unit, tính phí hàng giờ

AWS phát biểu trực tiếp:

"If you require access to Expedited retrievals under all circumstances, you must purchase provisioned retrieval capacity."

→ Nếu cần Expedited retrieval trong mọi tình huống, bắt buộc phải mua provisioned retrieval capacity.

Khi nào cần Provisioned Capacity?

  • Dữ liệu phục vụ compliance audit bất ngờ (financial, healthcare)
  • SLA yêu cầu thời gian retrieval được đảm bảo (không phải "thường")
  • Throughput yêu cầu cụ thể 150 MB/s

Phù hợp cho: Backup, disaster recovery, compliance archives


8. S3 Glacier Deep Archive

Use case: Long-term archive, access < 1 lần/năm, lưu trữ 7-10+ năm

  • Rẻ nhất trong tất cả storage classes
  • Min storage duration: 180 ngày
  • Phải restore trước khi access

Retrieval options:

OptionThời gian
Standard12 hours
Bulk48 hours

Phù hợp cho: Compliance archives (financial, healthcare), magnetic tape replacement


Lưu ý quan trọng về Min Duration và Min Size

Ví dụ với S3 Standard-IA (min 30 days, min 128 KB):

1. Upload file 50 KB → bị charge như 128 KB
2. Upload file, xóa sau 10 ngày → vẫn bị charge 30 ngày storage
3. Upload file, transition sang Glacier sau 15 ngày → charge 30 ngày Standard-IA + Glacier

Nguồn: Understanding and managing Amazon S3 storage classes


Storage Management

S3 Lifecycle

Tự động chuyển objects giữa storage classes hoặc xóa sau một thời gian:

Lifecycle Rule Example:
- Transition to Standard-IA after 30 days
- Transition to Glacier after 90 days
- Delete after 365 days

Rule 30 ngày khi transition sang IA

2 khái niệm 30 ngày rất dễ nhầm:

Khái niệmÁp dụng choÝ nghĩa
Lifecycle transition constraintChuyển sang S3 Standard-IA hoặc S3 One Zone-IA bằng LifecycleObject phải tồn tại trong S3 ít nhất 30 ngày trước khi được transition sang IA
Minimum storage durationKhi object đã nằm trong S3 Standard-IA hoặc S3 One Zone-IANếu xóa/chuyển tiếp trước 30 ngày, vẫn bị tính phí như lưu đủ 30 ngày

Ví dụ trong đề thi:

Day 0  → Upload object vào S3 Standard
Day 7  → Transition sang S3 Standard-IA   ❌ Không hợp lệ
Day 30 → Transition sang S3 Standard-IA   ✅ Hợp lệ

Dù dữ liệu bắt đầu ít truy cập sau 7 ngày, AWS vẫn không hỗ trợ Lifecycle transition sang Standard-IA hoặc One Zone-IA trong 30 ngày đầu.

Nguồn AWS: “Before you transition objects to S3 Standard-IA or S3 One Zone-IA, you must store them for at least 30 days in Amazon S3.”

Các rule Lifecycle quan trọng theo storage class

Ngoài rule 30 ngày của IA, S3 Lifecycle còn có các rule hay gặp sau:

Storage class / caseRule Lifecycle cần nhớVí dụ / ghi chú
S3 StandardCó thể transition xuống nhiều lớp rẻ/lạnh hơnStandard → Standard-IA / Intelligent-Tiering / One Zone-IA / Glacier Instant / Glacier Flexible / Deep Archive
S3 Standard-IACó thể đi tiếp xuống lớp lạnh hơn, nhưng không quay về Standard bằng LifecycleStandard-IA → One Zone-IA / Glacier Instant / Glacier Flexible / Deep Archive
S3 One Zone-IAChỉ đi tiếp xuống archive classOne Zone-IA → Glacier Flexible / Deep Archive; không transition ngược lên Standard-IA
S3 Glacier Instant RetrievalAccess milliseconds, nhưng nếu transition tiếp thì chỉ đi xuống archive lạnh hơnGlacier Instant → Glacier Flexible / Deep Archive; minimum storage duration 90 ngày
S3 Glacier Flexible RetrievalCần restore trước khi đọc; Lifecycle chỉ có thể đi tiếp xuống Deep ArchiveGlacier Flexible → Deep Archive; minimum storage duration 90 ngày
S3 Glacier Deep ArchiveGần như điểm cuối của Lifecycle waterfallKhông transition ngược lên lớp nóng hơn bằng Lifecycle; minimum storage duration 180 ngày
S3 Intelligent-TieringCó tier nội bộ tự động theo access pattern; không giống Standard-IAFrequent → Infrequent sau 30 ngày không access; Archive Instant sau 90 ngày; optional Archive/Deep Archive tiers
Object < 128 KBMặc định không được Lifecycle transition sang bất kỳ storage class nàoCó thể override bằng object size filter hoặc header/API phù hợp, nhưng mặc định AWS chặn để tránh transition cost lớn hơn storage saving

Cách nhớ: Lifecycle chủ yếu đi theo kiểu waterfall — từ lớp nóng/đắt hơn xuống lớp lạnh/rẻ hơn. Nếu muốn “đưa object nóng lại” từ Glacier/Deep Archive, thường phải restore/copy object, không phải Lifecycle transition ngược.

Minimum storage duration khác với transition direction:

Storage classMinimum storage duration
S3 StandardKhông có
S3 Intelligent-TieringKhông có
S3 Standard-IA30 ngày
S3 One Zone-IA30 ngày
S3 Glacier Instant Retrieval90 ngày
S3 Glacier Flexible Retrieval90 ngày
S3 Glacier Deep Archive180 ngày

Nếu object đã vào một storage class có minimum duration rồi bị xóa hoặc transition tiếp quá sớm, bạn vẫn có thể bị tính phí phần thời gian còn lại. Ví dụ: object vào Glacier Instant Retrieval rồi chuyển tiếp sang Deep Archive sau 20 ngày → vẫn chịu minimum duration 90 ngày của Glacier Instant Retrieval.

Matrix transition storage class (Lifecycle)

S3 Lifecycle hỗ trợ transition theo mô hình "waterfall" (đi xuống lớp rẻ hơn), không phải mọi cặp source/destination đều hợp lệ.

Từ storage classCó thể transition sang (qua Lifecycle)
S3 StandardStandard-IA, Intelligent-Tiering, One Zone-IA, Glacier Instant Retrieval, Glacier Flexible Retrieval, Glacier Deep Archive
S3 Standard-IAIntelligent-Tiering, One Zone-IA, Glacier Instant Retrieval, Glacier Flexible Retrieval, Glacier Deep Archive
S3 Intelligent-TieringPhụ thuộc access tier; có thể sang One Zone-IA hoặc các lớp Glacier tương ứng
S3 One Zone-IAGlacier Flexible Retrieval, Glacier Deep Archive
S3 Glacier Instant RetrievalGlacier Flexible Retrieval, Glacier Deep Archive
S3 Glacier Flexible RetrievalGlacier Deep Archive

Các transition hay nhầm trong đề thi:

  • S3 Intelligent-Tiering => S3 Standard (không được hỗ trợ bởi Lifecycle)
  • S3 One Zone-IA => S3 Standard-IA (không được hỗ trợ bởi Lifecycle)
  • S3 Standard-IA => S3 One Zone-IA (được hỗ trợ)

Nguồn: Transitioning objects using Amazon S3 Lifecycle, Using S3 Intelligent-Tiering

S3 Replication

Lưu ý: Đây là tính năng bạn tự cấu hình, khác với việc AWS tự động replicate sang 3 AZs!

2 loại replication khác nhau:

Automatic (3 AZs)S3 Replication (CRR/SRR)
Cấu hìnhAWS tự động làmBạn phải tự setup
ScopeTrong cùng 1 bucket, cùng RegionSang bucket khác
Mục đíchDurability 11 ninesDR, compliance, latency
ControlKhông control đượcBạn chọn destination
Automatic 3 AZs (bạn không thấy, không control):
┌─────────────────────────────────────┐
│  Bucket A (us-east-1)               │
│  ┌─────┐  ┌─────┐  ┌─────┐          │
│  │ AZ1 │  │ AZ2 │  │ AZ3 │  ← AWS tự động
│  └─────┘  └─────┘  └─────┘          │
└─────────────────────────────────────┘

S3 Replication (bạn cấu hình):
┌──────────────────┐     ┌──────────────────┐
│ Bucket A         │ ──► │ Bucket B         │
│ (us-east-1)      │     │ (eu-west-1)      │  ← bạn setup
└──────────────────┘     └──────────────────┘

Các loại S3 Replication:

  • Cross-Region Replication (CRR) - replicate sang Region khác
  • Same-Region Replication (SRR) - replicate trong cùng Region

Yêu cầu: Versioning phải enabled ở cả source và destination bucket

Use cases:

  • CRR: Disaster recovery, compliance (data phải ở EU), giảm latency cho users ở region khác
  • SRR: Aggregate logs từ nhiều buckets, copy giữa dev/prod accounts

Xem thêm: AWS Overview - Regions và AZs để hiểu về Region, AZ

S3 Object Lock

Chống xóa/overwrite objects theo mô hình WORM (Write Once Read Many) - thường dùng cho compliance.

2 cách bảo vệ:

Retention PeriodLegal Hold
Thời hạnCố định (vd: 365 ngày)Không có, cho đến khi tắt
Use caseCompliance, regulatoryLitigation, điều tra, audit
Kết thúcTự động hết hạnPhải manually remove

2 Retention Modes:

┌─────────────────────────────────────────────────────────────┐
│                    GOVERNANCE MODE                          │
│  - Users thường KHÔNG THỂ xóa/overwrite                     │
│  - Users có permission s3:BypassGovernanceRetention CÓ THỂ  │
│  - Có thể extend hoặc shorten retention                     │
│  - Use case: Test, flexible WORM                            │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│                    COMPLIANCE MODE                          │
│  - KHÔNG AI có thể xóa, kể cả root user                     │
│  - KHÔNG THỂ shorten retention period                       │
│  - Cách duy nhất xóa sớm: XÓA CẢ AWS ACCOUNT                │
│  - Use case: Regulatory compliance (SEC, FINRA, HIPAA)      │
└─────────────────────────────────────────────────────────────┘

Ví dụ thực tế:

Scenario: Ngân hàng cần giữ records 7 năm (compliance)

1. Enable Object Lock trên bucket (khi tạo bucket)
2. Set default retention: 7 years, Compliance mode
3. Upload transaction records

→ Không ai có thể xóa records trong 7 năm
→ Kể cả CEO, kể cả root account
→ Đáp ứng audit requirements

Yêu cầu & lưu ý:

  • Versioning phải enabled
  • Có thể enable Object Lock khi tạo bucket hoặc trên existing general purpose bucket
  • Sau khi enable Object Lock trên bucket, không thể disable Object Lock hoặc suspend versioning cho bucket đó

Nguồn: S3 Object Lock, Configuring S3 Object Lock

Amazon Glacier Vault Lock

Dễ nhầm: Đây là feature của Amazon Glacier vault-based service (dịch vụ Glacier standalone dùng vault/API cũ), không phải một storage class như S3 Glacier Flexible Retrieval hay S3 Glacier Deep Archive.

Amazon Glacier Vault Lock dùng để enforce compliance controls trên Glacier vault bằng một Vault Lock policy. Policy này có thể đặt rule kiểu WORM (Write Once Read Many), ví dụ deny delete archive cho đến khi archive đủ 10 năm tuổi.

Archived compliance data

Amazon Glacier Vault

Vault Lock policy
- Deny delete trước 10 năm
- Lock policy khỏi future edits

Điểm quan trọng: sau khi Vault Lock policy đã locked, policy không thể thay đổi hoặc xóa. Vì vậy nó phù hợp với archived compliance data cần giữ lâu dài theo yêu cầu pháp lý.

Nhu cầuDùng gì?Vì sao
Records cần audit ngay, không xóa/overwrite 7 nămS3 Object Lock - Compliance modeObject vẫn ở S3 để đọc ngay; Compliance mode không cho xóa/overwrite kể cả root
Archived compliance data, lưu rẻ lâu dài, khóa ≥10 nămAmazon Glacier Vault LockVault policy enforce WORM và bị lock khỏi sửa đổi
Chỉ giảm chi phí archive trong S3S3 Glacier Flexible / Deep ArchiveLà storage class; không tự nó tạo compliance lock

So sánh nhanh với S3 Object Lock:

Tiêu chíS3 Object LockAmazon Glacier Vault Lock
Áp dụng lênS3 object version trong bucketAmazon Glacier vault policy
Mục tiêuChống delete/overwrite object trong S3Enforce compliance rule trên archive vault
Đọc ngay?Có, nếu object ở storage class đọc tức thì như S3 StandardKhông phải mục tiêu chính; dùng cho archive
ModeGovernance / ComplianceIAM-style Vault Lock policy
Use case examTransaction records, audit ngay, WORM 7 nămArchived compliance data, low-cost long-term retention

Lưu ý hiện tại: AWS khuyến nghị khách hàng mới dùng Amazon S3 Glacier storage classes cho long-term archive. Tuy nhiên trong các câu hỏi exam/legacy architecture, Glacier Vault Lock vẫn xuất hiện như cơ chế compliance lock cho Glacier vaults.

Nguồn: Amazon Glacier Vault Lock, Vault Lock Policies

S3 Batch Operations

  • Thực hiện operations trên hàng triệu/tỷ objects
  • Operations: Copy, Invoke Lambda, Restore, Tagging, etc.

Access Management & Security

Default Security

  • Buckets và objects mặc định là private
  • Chỉ owner/account administrator có access

Access Control Methods

MethodScopeUse Case
IAM PoliciesUser/Role levelControl user access to S3
Bucket PoliciesBucket levelCross-account, public access
Access PointsNamed endpointsSimplified access for shared datasets
ACLsObject/Bucket levelLegacy, không khuyến khích
S3 Block Public AccessAccount/Bucket levelPrevent public access

Bucket Policy Example

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowGetObject",
      "Effect": "Allow",
      "Principal": "*",
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::my-bucket/*"
    }
  ]
}

Encryption

Server-Side Encryption (SSE):

  • SSE-S3 - AWS managed keys (default từ Jan 2023)
  • SSE-KMS - Customer managed keys via KMS
  • SSE-C - Customer-provided keys
  • DSSE-KMS - Dual-layer encryption

Client-Side Encryption:

  • Encrypt trước khi upload

S3 Object Ownership

  • Bucket owner enforced (recommended) - disable ACLs, bucket owner owns all objects
  • Bucket owner preferred - bucket owner owns objects nếu upload với bucket-owner-full-control
  • Object writer - uploader owns the object

Xem chi tiết: S3 Security - Access Control, Encryption, Block Public Access, Pre-signed URLs, VPC Endpoints

Nguồn: Amazon S3 Security Features


S3 Performance

Baseline Performance

S3 có khả năng xử lý rất cao out-of-the-box:

MetricPer Prefix
GET/HEAD requests5,500 requests/second
PUT/COPY/POST/DELETE3,500 requests/second

Prefix = phần path trước object name. Ví dụ: bucket/folder1/subfolder/ là 1 prefix.

Ví dụ: Bucket với nhiều prefixes

s3://my-bucket/images/2024/   ← 5,500 GET/s + 3,500 PUT/s
s3://my-bucket/images/2025/   ← 5,500 GET/s + 3,500 PUT/s  
s3://my-bucket/videos/        ← 5,500 GET/s + 3,500 PUT/s

→ Dùng nhiều prefixes = Scale gần như vô hạn!

Tối ưu Performance

1. Multi-Part Upload

Bắt buộc cho files > 5GB, khuyến nghị cho files > 100MB.

┌─────────────────────────────────────────────────────────────────┐
│                    MULTI-PART UPLOAD                            │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  File 1GB                                                       │
│  ┌─────────────────────────────────────────────────────────┐    │
│  │ Part 1 │ Part 2 │ Part 3 │ Part 4 │ ... │ Part 10       │    │
│  │ 100MB  │ 100MB  │ 100MB  │ 100MB  │     │ 100MB         │    │
│  └───┬────┴───┬────┴───┬────┴───┬────┴─────┴───┬───────────┘    │
│      │        │        │        │              │                │
│      ▼        ▼        ▼        ▼              ▼                │
│   Upload   Upload   Upload   Upload         Upload              │
│   song song (parallel) → NHANH HƠN!                             │
│      │        │        │        │              │                │
│      └────────┴────────┴────────┴──────────────┘                │
│                        │                                        │
│                         ▼                                       │
│                  S3 ghép lại thành 1 file                       │
│                                                                 │
│  ✅ Upload song song nhiều parts                                │
│  ✅ Retry chỉ parts failed (không retry cả file)                │
│  ✅ Bắt đầu upload khi vẫn đang generate file                   │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

2. S3 Transfer Acceleration

Upload/download qua AWS Edge Locations thay vì public internet.

WITHOUT Acceleration:        WITH Acceleration:
User ──► Internet ──► S3     User ──► Edge ══► AWS Backbone ══► S3
         (slow)                       (fast)    (optimized)
  • Endpoint: bucket-name.s3-accelerate.amazonaws.com
  • Chỉ charge khi thực sự nhanh hơn
  • Tốt cho: long-distance transfers, large files

3. Byte-Range Fetches (Parallel Downloads)

Download một phần file hoặc download song song nhiều phần.

┌─────────────────────────────────────────────────────────────────┐
│                    BYTE-RANGE FETCHES                           │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  File 1GB trên S3                                               │
│  ┌─────────────────────────────────────────────────────────┐    │
│  │ 0-100MB │ 100-200MB │ 200-300MB │ ... │ 900MB-1GB       │    │
│  └───┬─────┴─────┬─────┴──────┬────┴─────┴───────┬─────────┘    │
│      │           │            │                  │              │
│      ▼           ▼            ▼                   ▼             │
│  GET byte=0-100MB  GET byte=100-200MB  ...  GET byte=900-1GB    │
│      │           │            │                  │              │
│      └───────────┴────────────┴───────────────────┘             │
│                         │                                       │
│                          ▼                                      │
│                   Ghép lại ở client                             │
│                                                                 │
│  ✅ Download song song (parallel) → NHANH HƠN                   │
│  ✅ Retry chỉ phần failed                                       │
│  ✅ Download chỉ phần cần thiết (vd: header của video)          │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

Use cases:

  • Parallel download để tăng tốc
  • Download chỉ metadata/header của file
  • Resume download bị gián đoạn

4. S3 Select / Glacier Select

Query data trực tiếp trong S3 mà không cần download toàn bộ file.

Truyền thống:
Download 1GB CSV → Filter ở client → Chỉ cần 10MB data
→ Tốn bandwidth, chậm

S3 Select:
Query trực tiếp trên S3 → Chỉ trả về 10MB data cần
→ Tiết kiệm bandwidth, nhanh hơn
-- S3 Select query (SQL-like)
SELECT s.name, s.age FROM S3Object s WHERE s.age > 25

Hỗ trợ formats: CSV, JSON, Parquet

Tóm tắt Performance Optimizations

TechniqueUse CaseBenefit
Multi-Part UploadFiles > 100MBParallel upload, retry parts
Transfer AccelerationLong distanceFaster via Edge Locations
Byte-Range FetchesLarge downloadsParallel download, partial fetch
S3 SelectQuery large filesReduce data transfer
Multiple PrefixesHigh throughputScale requests linearly

Nguồn: S3 Performance Guidelines


Data Processing

S3 Object Lambda

S3 Object Lambda cho phép thêm code để transform data on-the-fly khi GET object, mà không cần sửa object gốc.

┌─────────────────────────────────────────────────────────────────┐
│                    S3 OBJECT LAMBDA                             │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  Truyền thống (không có Object Lambda):                         │
│                                                                 │
│  App ──► GET object ──► S3 ──► Raw data                         │
│  App ──► Transform locally (tốn CPU, memory)                    │
│                                                                 │
│  HOẶC: Store nhiều versions (original + transformed)            │
│        → Tốn storage, phải sync                                 │
│                                                                 │
│  ────────────────────────────────────────────────────────────── │
│                                                                 │
│  Với S3 Object Lambda:                                          │
│                                                                 │
│  App ──► Object Lambda ──► Lambda Function ──► S3               │
│          Access Point        (transform)        (raw data)      │
│               │                  │                              │
│               └─────► Trả về transformed data                   │
│                                                                 │
│  → Chỉ lưu 1 bản gốc, transform khi cần                         │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

Cách hoạt động

┌───────────┐    ┌─────────────────────┐    ┌──────────────┐    ┌──────────┐
│    App    │───►│ Object Lambda       │───►│    Lambda    │───►│    S3    │
│           │    │ Access Point        │    │   Function   │    │  Bucket  │
└───────────┘    └─────────────────────┘    └──────────────┘    └──────────┘
      │                                            │
      │◄───────── Transformed Response ────────────┘
  1. App gọi Object Lambda Access Point (không gọi trực tiếp S3)
  2. Object Lambda Access Point invoke Lambda function
  3. Lambda lấy object gốc từ S3, transform, trả về cho app

Use Cases phổ biến

Use CaseMô tả
Resize imagesTrả về thumbnail thay vì image gốc
Redact PIIChe thông tin nhạy cảm (SSN, email...)
Convert formatsXML → JSON, PNG → WebP
DecompressGunzip on-the-fly
Add watermarkThêm watermark vào images
Filter dataTrả về subset của data dựa trên user role
Enrich dataThêm metadata từ external source

Ví dụ: Redact PII

┌─────────────────────────────────────────────────────────────────┐
│  Original JSON in S3:                                           │
│  {                                                              │
│    "name": "John Doe",                                          │
│    "email": "john@example.com",    ← PII                        │
│    "ssn": "123-45-6789",           ← PII                        │
│    "department": "Engineering"                                  │
│  }                                                              │
│                                                                 │
│  After Object Lambda (redact):                                  │
│  {                                                              │
│    "name": "John Doe",                                          │
│    "email": "***REDACTED***",      ← Đã che                     │
│    "ssn": "***REDACTED***",        ← Đã che                     │
│    "department": "Engineering"                                  │
│  }                                                              │
└─────────────────────────────────────────────────────────────────┘

Lambda Function Example (Node.js)

const { S3 } = require('@aws-sdk/client-s3');
 
exports.handler = async (event) => {
  // Get object từ S3
  const s3Client = new S3();
  const response = await s3Client.getObject({
    Bucket: event.getObjectContext.inputS3Url,
  });
  
  // Transform data
  const originalData = await response.Body.transformToString();
  const jsonData = JSON.parse(originalData);
  
  // Redact PII
  jsonData.email = "***REDACTED***";
  jsonData.ssn = "***REDACTED***";
  
  // Return transformed data
  await s3Client.writeGetObjectResponse({
    RequestRoute: event.getObjectContext.outputRoute,
    RequestToken: event.getObjectContext.outputToken,
    Body: JSON.stringify(jsonData),
  });
  
  return { statusCode: 200 };
};

So sánh với các giải pháp khác

ApproachStoragePerformanceFlexibility
Store multiple versions❌ Nhiều✅ Nhanh❌ Phải sync
Transform on client✅ 1 bản❌ Chậm✅ Linh hoạt
S3 Object Lambda✅ 1 bản⚡ Tốt✅ Linh hoạt

Pricing

  • Lambda invocation: Tính như Lambda bình thường
  • Data transfer: Từ S3 → Lambda → Client
  • No additional Object Lambda fee

💡 Khi nào dùng: Khi cần transform data nhưng không muốn lưu nhiều versions, hoặc transformation phụ thuộc vào context (user role, request params...).

Event Notifications

Trigger workflows khi có changes trong S3.

Cách hoạt động

┌─────────────────────────────────────────────────────────────────┐
│                    S3 EVENT NOTIFICATIONS                       │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│   S3 Bucket                                                     │
│   ┌─────────────────────────────────────────────────────────┐   │
│   │  Object Created (PUT, POST, COPY, MultiPart)            │   │
│   │  Object Removed (DELETE, DeleteMarkerCreated)           │   │
│   │  Object Restore (Glacier restore completed)             │   │
│   │  Replication Events                                     │   │
│   │  ...                                                    │   │
│   └─────────────────────────────────────────────────────────┘   │
│                             │                                   │
│                              ▼                                  │
│   ┌─────────────────────────────────────────────────────────┐   │
│   │                   DESTINATIONS                          │   │
│   │                                                         │   │
│   │   ┌─────────┐  ┌─────────┐  ┌─────────┐  ┌───────────┐  │   │
│   │   │   SNS   │  │   SQS   │  │ Lambda  │  │EventBridge│  │   │
│   │   └─────────┘  └─────────┘  └─────────┘  └───────────┘  │   │
│   └─────────────────────────────────────────────────────────┘   │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

Các loại Events

Event TypeTrigger khi
s3:ObjectCreated:*PUT, POST, COPY, MultipartUpload complete
s3:ObjectRemoved:*DELETE hoặc DeleteMarkerCreated
s3:ObjectRestore:*Glacier restore bắt đầu/hoàn thành
s3:Replication:*Replication failed/completed
s3:LifecycleExpiration:*Object bị xóa bởi lifecycle
s3:LifecycleTransitionObject chuyển storage class
s3:IntelligentTieringObject chuyển tier trong IT

Destinations

DestinationUse CaseĐặc điểm
Amazon SNSFan-out (gửi đến nhiều subscribers)Push notifications, email, SMS
Amazon SQSQueue xử lý tuần tựDecoupling, retry, batch processing
AWS LambdaServerless processingReal-time, custom code
EventBridgeComplex routing, filteringRules, cross-account, archive

So sánh Destinations

SNS (Fan-out):
┌─────┐
│ S3  │──► SNS ──┬──► SQS Queue 1
└─────┘          ├──► SQS Queue 2  
                 ├──► Lambda
                 └──► Email

SQS (Queue):
┌─────┐          ┌─────────┐
│ S3  │──► SQS ──► Workers │  (xử lý tuần tự)
└─────┘          └─────────┘

Lambda (Direct):
┌─────┐    ┌──────────────────────────────┐
│ S3  │──► Lambda (resize image, process) │
└─────┘    └──────────────────────────────┘

EventBridge (Advanced):
┌─────┐                   ┌─► Lambda A (*.jpg)
│ S3  │──► EventBridge ───┼─► SQS (*.pdf)
└─────┘     (filter)      └─► SNS (*.mp4)

Use Cases phổ biến

Use CaseEventDestinationAction
Image thumbnailObjectCreatedLambdaResize, save thumbnail
Video transcodingObjectCreatedSQS → MediaConvertConvert video formats
Log processingObjectCreatedLambda → ESIndex logs cho search
Backup notificationObjectCreatedSNS → EmailNotify admin
Data pipelineObjectCreatedEventBridge → Step FunctionsETL workflow
Audit trailAll eventsEventBridge → CloudWatch LogsLogging

Ví dụ: Image Processing Pipeline

┌─────────────────────────────────────────────────────────────────────┐
│                    IMAGE PROCESSING PIPELINE                        │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│   User uploads image.jpg                                            │
│              │                                                      │
│           ▼                                                         │
│   ┌───────────────┐                                                 │
│   │ S3 Bucket     │                                                 │
│   │ /uploads/     │                                                 │
│   └───────┬───────┘                                                 │
│           │ s3:ObjectCreated:Put                                    │
│           ▼                                                         │
│   ┌───────────────┐                                                 │
│   │    Lambda     │                                                 │
│   │ (resize.py)   │                                                 │
│   └───────┬───────┘                                                 │
│           │                                                         │
│     ┌─────┼─────┐                                                   │
│     ▼     ▼     ▼                                                   │
│   small  med  large                                                 │
│   100px  300px 800px                                                │
│     │     │     │                                                   │
│     ▼     ▼     ▼                                                   │
│     ┌────────────┐                                                  │
│     │ S3 Bucket  │                                                  │
│     │/thumbnails/│                                                  │
│     └────────────┘                                                  │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

Lưu ý quan trọng

[!IMPORTANT] Permissions: Destination (SNS/SQS/Lambda) phải có policy cho phép S3 gửi events.

// SQS Policy Example
{
  "Statement": [{
    "Effect": "Allow",
    "Principal": {"Service": "s3.amazonaws.com"},
    "Action": "sqs:SendMessage",
    "Resource": "arn:aws:sqs:region:account:queue",
    "Condition": {
      "ArnLike": {"aws:SourceArn": "arn:aws:s3:::bucket-name"}
    }
  }]
}

[!TIP] EventBridge vs Legacy (SNS/SQS/Lambda):

  • Legacy: Faster, simpler, direct integration
  • EventBridge: More powerful filtering, routing rules, cross-account, archive events

Monitoring & Analytics

Monitoring Tools

ToolPurpose
CloudWatch MetricsMonitor operational health
CloudTrailAPI logging và auditing
Server Access LoggingDetailed request logs
S3 Storage Lens60+ metrics, dashboards

Analytics

  • Storage Class Analysis - phân tích access patterns để tối ưu storage class
  • S3 Inventory - báo cáo objects và metadata

Data Consistency

S3 cung cấp strong read-after-write consistency:

  • PUT new object → immediately readable
  • PUT overwrite → immediately see new version
  • DELETE → immediately not found

Applies to tất cả AWS Regions.


Pricing

S3 tính phí theo:

  • Storage - GB per month
  • Requests - PUT, COPY, POST, LIST, GET, SELECT
  • Data Transfer - OUT to internet, cross-region
  • Management features - Inventory, Analytics, Object Tagging

Free Tier (12 months):

  • 5 GB S3 Standard storage
  • 20,000 GET requests
  • 2,000 PUT requests

Nguồn: Amazon S3 Pricing


Requester Pays

Requester Pays cho phép bucket owner chuyển chi phí data transfer và request sang cho người request (requester) thay vì trả tiền tất cả.

Vấn đề cần giải quyết

TÌNH HUỐNG THÔNG THƯỜNG:
┌─────────────────────────────────────────────────────────────────┐
│  Bạn có 100TB dữ liệu research để chia sẻ                       │
│                                                                 │
│  User A download 10TB ─┐                                        │
│  User B download 20TB  ├──► BẠN phải trả ~$2,700/tháng!         │
│  User C download 30TB ─┘    (data transfer out)                 │
│                                                                 │
│  → Càng nhiều người dùng, bạn càng TỐN TIỀN                     │
└─────────────────────────────────────────────────────────────────┘

VỚI REQUESTER PAYS:
┌─────────────────────────────────────────────────────────────────┐
│  Bạn chỉ trả chi phí STORAGE (~$2,300/tháng cho 100TB)          │
│                                                                 │
│  User A download 10TB ──► User A trả $900                       │
│  User B download 20TB ──► User B trả $1,800                     │
│  User C download 30TB ──► User C trả $0 (nếu cùng region)       │
│                                                                 │
│  → Công bằng: ai dùng, người đó trả                             │
└─────────────────────────────────────────────────────────────────┘

Chi phí được chuyển cho Requester

Chi phíBucket OwnerRequester
Storage✅ Trả-
Data Transfer OUT-✅ Trả
GET/PUT Requests-✅ Trả
Same-region transfer-Miễn phí

Cách hoạt động

1. Bucket owner enable "Requester Pays" trên bucket

2. Requester phải:
   ├── Có AWS account (authenticated)
   ├── Gửi request với header: x-amz-request-payer: requester
   └── Hoặc CLI: --request-payer requester

3. AWS tính phí vào account của requester, không phải bucket owner

Lưu ý quan trọng:

  • Anonymous access không hoạt động - Requester PHẢI có AWS account
  • ❌ Không thể dùng pre-signed URLs (vì cần authenticated request)
  • ✅ Bucket owner vẫn control access qua bucket policy

Use Cases

Use CaseMô tả
Public datasetsNASA, genome data, weather data - ai dùng, người đó trả
Data marketplaceBán/share data mà không lo chi phí bandwidth
Research dataUniversities share research data
Media archivesStock photos/videos, download theo nhu cầu

Ví dụ CLI

# Download từ requester pays bucket
aws s3 cp s3://requester-pays-bucket/file.txt ./file.txt --request-payer requester
 
# List objects
aws s3 ls s3://requester-pays-bucket/ --request-payer requester

Enable Requester Pays

# Enable
aws s3api put-bucket-request-payment \
  --bucket my-bucket \
  --request-payment-configuration Payer=Requester
 
# Check status
aws s3api get-bucket-request-payment --bucket my-bucket

Nguồn: Using Requester Pays buckets


Best Practices

  1. Enable versioning để bảo vệ khỏi accidental deletes
  2. Use Lifecycle policies để tối ưu costs
  3. Enable S3 Block Public Access trừ khi cần public
  4. Use SSE-KMS cho sensitive data
  5. Enable CloudTrail để audit access
  6. Use S3 Intelligent-Tiering nếu không biết access patterns
  7. Use multipart upload cho files > 100MB
  8. Use S3 Transfer Acceleration cho long-distance transfers

S3 Transfer Acceleration

Tăng tốc upload/download files qua long distances bằng AWS Edge Locations.

WITHOUT Acceleration:        WITH Acceleration:
User ──► Internet ──► S3     User ──► Edge ══► AWS Backbone ══► S3
         (slow)                       (fast)    (optimized)

Key points:

  • Dùng endpoint: bucket-name.s3-accelerate.amazonaws.com
  • Chỉ charge khi nhanh hơn (AWS tự động bypass nếu không cải thiện)
  • Pricing: ~$0.04-0.08/GB
  • Hiệu quả nhất khi: client xa bucket, file lớn

📖 Xem chi tiết: S3 Transfer Acceleration Deep Dive

S3 Transfer Acceleration vs Global Accelerator

⚠️ Câu hỏi thường gặp: Hai dịch vụ này KHÁC NHAU nhưng cùng dùng AWS Edge Locations!

S3 Transfer Acceleration:
User ──► Edge Location ──► AWS Backbone ──► S3 Bucket
• CHỈ cho S3 uploads/downloads
• URL: bucket.s3-accelerate.amazonaws.com

Global Accelerator:
User ──► Edge Location ──► AWS Backbone ──► ALB/NLB/EC2
• Cho BẤT KỲ TCP/UDP application
• KHÔNG hỗ trợ S3 trực tiếp
FeatureS3 Transfer AccelerationGlobal Accelerator
Mục đíchTăng tốc S3 upload/downloadTăng tốc any TCP/UDP app
Hỗ trợ S3?✅ Có (chính)❌ Không
Hỗ trợ ALB/EC2?❌ Không✅ Có
Static IP❌ Không✅ 2 Anycast IPs
Failover❌ Không✅ Instant failover
Cách bậtPer-bucket settingTạo Accelerator riêng

💡 Tóm lại: S3 Transfer Acceleration = "Global Accelerator cho riêng S3"


So sánh với EBS và EFS

FeatureS3EBSEFS
TypeObject storageBlock storageFile storage
AccessHTTP/HTTPS APIAttached to EC2NFS mount
ScopeRegionalSingle AZRegional
Max sizeUnlimited64 TiB/volumeUnlimited
Use caseStatic files, backupsOS, databasesShared files

Liên kết

  • EBS - Block storage cho EC2
  • EFS - Shared file storage
  • IAM - Access management
  • VPC - Network configuration

Tài liệu tham khảo

On this page

Amazon S3 (Simple Storage Service)Mục lụcTổng quanDurability 11 nines là gì?Erasure Coding - Kỹ thuật đằng sau 11 ninesCác kỹ thuật Internal khác của S31. Checksums & Data Integrity2. Shuffle Sharding - Giảm "Blast Radius"3. Cell-based Architecture4. Two Random Choices (Load Balancing)Tổng kết các kỹ thuậtCác khái niệm cơ bảnBucketsObjectsKeys & Flat Structure"Folder" trong S3 ConsolePrefix & DelimiterObject Key Naming RulesTại sao flat structure quan trọng?VersioningStorage ClassesStorage Class được chọn ở đâu?Bảng so sánh tổng quan1. S3 Standard2. S3 Express One Zone3. S3 Intelligent-Tiering4. S3 Standard-IA (Infrequent Access)5. S3 One Zone-IA6. S3 Glacier Instant Retrieval"Restore" là gì?7. S3 Glacier Flexible RetrievalProvisioned Retrieval Capacity8. S3 Glacier Deep ArchiveLưu ý quan trọng về Min Duration và Min SizeStorage ManagementS3 LifecycleRule 30 ngày khi transition sang IACác rule Lifecycle quan trọng theo storage classMatrix transition storage class (Lifecycle)S3 ReplicationS3 Object LockAmazon Glacier Vault LockS3 Batch OperationsAccess Management & SecurityDefault SecurityAccess Control MethodsBucket Policy ExampleEncryptionS3 Object OwnershipS3 PerformanceBaseline PerformanceTối ưu Performance1. Multi-Part Upload2. S3 Transfer Acceleration3. Byte-Range Fetches (Parallel Downloads)4. S3 Select / Glacier SelectTóm tắt Performance OptimizationsData ProcessingS3 Object LambdaCách hoạt độngUse Cases phổ biếnVí dụ: Redact PIILambda Function Example (Node.js)So sánh với các giải pháp khácPricingEvent NotificationsCách hoạt độngCác loại EventsDestinationsSo sánh DestinationsUse Cases phổ biếnVí dụ: Image Processing PipelineLưu ý quan trọngMonitoring & AnalyticsMonitoring ToolsAnalyticsData ConsistencyPricingRequester PaysVấn đề cần giải quyếtChi phí được chuyển cho RequesterCách hoạt độngUse CasesVí dụ CLIEnable Requester PaysBest PracticesS3 Transfer AccelerationS3 Transfer Acceleration vs Global AcceleratorSo sánh với EBS và EFSLiên kếtTài liệu tham khảo