Overview and What You Will Learn
Amazon S3 is AWS's object storage service. You store files, called objects, in containers called buckets and reach them over an HTTPS API, not a mounted disk. In this lab you create a versioned bucket, recover a deleted file, add a lifecycle rule and share a file with a pre-signed URL.
By the end you will be able to:
- Explain how S3 differs from a file system and a database
- Name buckets correctly and understand keys and prefixes
- Combine IAM policies, bucket policies and Block Public Access to control access
- Use versioning and delete markers to recover files
- Set up Cross-Region and Same-Region Replication
- Choose a storage class and automate transitions with lifecycle rules
- Speed up transfers with multipart upload, Transfer Acceleration and byte-range fetches
- Pick the right encryption method and share private objects with pre-signed URLs
- Protect records with Object Lock and simplify team access with Access Points
Why This Matters in Production
S3 is the integration point for most AWS services, and it is behind some of the most common cloud security incidents: buckets that were made public by accident. A streaming service such as Hotstar keeps thumbnails and metadata in S3 behind CloudFront. A payments company such as Razorpay can use Object Lock to keep compliance documents unmodifiable for a legal retention period. A food delivery company such as Swiggy can send logs from hundreds of services into one bucket and query them with Athena, and a broker such as Zerodha can keep long-term records in Glacier Deep Archive at a fraction of database cost.
Understanding S3 means knowing both its power and its traps: public access, forgotten multipart uploads, minimum storage durations and KMS throttling.
Core Principles
What Is Amazon S3 and How Is It Different From a File System?
S3 is flat object storage. A bucket holds objects, and what looks like a folder path is just part of the object's key. There is no schema and no query language, and you read and write objects through the API. S3 offers 11 nines of durability, effectively unlimited capacity, objects up to 5 TB, and strong read-after-write consistency for new and overwritten objects.
File system: /var/app/uploads/user123/photo.jpg (real directory tree)S3: s3://my-bucket/uploads/user123/photo.jpg (key is the whole path)What Are the S3 Bucket Naming Rules?
Bucket names must be globally unique across all AWS accounts. They are 3 to 63 characters, use only lowercase letters, numbers and hyphens, start with a letter or number, and cannot look like an IP address. Each bucket lives in one Region, and data stays there unless you replicate it.
- Valid: razorpay-payment-logs-2024, hotstar-thumbnails-prod
- Invalid: Hotstar-Thumbnails (uppercase), my_bucket (underscore), ab (too short)
What Are S3 Objects, Keys, and Prefixes?
The key is the full name of an object in the bucket, and the prefix is the part before the final name. For invoices/2024/january/INV-001.pdf, the prefix is invoices/2024/january/ and the object name is INV-001.pdf. A single PUT can upload up to 5 GB, and larger files need multipart upload.
RememberThere are no real folders in S3. Request rates are counted per prefix, so spreading objects across many prefixes raises total throughput.
Who Can Access an S3 Bucket: IAM Policies vs Bucket Policies?
Access is decided by combining identity-based IAM policies and resource-based bucket policies, and an explicit Deny always wins. Within one account, a request is allowed if either the IAM policy or the bucket policy allows it. For cross-account access, both sides must allow it.
- Use an IAM role for your own workloads, such as an EC2 role with S3 read permission
- Use a bucket policy for anonymous public access, other accounts and AWS services
A bucket policy for a public static website has one statement with these elements:
| Element | Value |
|---|---|
| Effect | Allow |
| Principal | * |
| Action | s3:GetObject |
| Resource | arn:aws:s3:::my-static-website/* |
Save the policy as policy.json and attach it:
aws s3api put-bucket-policy \ --bucket my-static-website \ --policy file://policy.jsonRememberThe bucket ARN (arn:aws:s3:::my-bucket) covers bucket-level actions such as listing, and the ARN with /* covers the objects inside. Many access errors come from using the wrong one, and often you need both.
What Does S3 Block Public Access Do?
Block Public Access is a safety switch that overrides bucket policies and ACLs that would make a bucket or its objects public. It has four settings, all on by default for new buckets, and it can also be applied at account level. New buckets also have ACLs disabled by default (bucket owner enforced), so use policies instead of ACLs.
Turn Block Public Access off only for a bucket that must be public, and even then prefer keeping the bucket private behind CloudFront with Origin Access Control.
SecurityTreat any bucket with Block Public Access disabled as a security exception that needs review. Accidentally public buckets have caused many major data leaks.
How Does S3 Versioning Work?
Versioning keeps every version of an object. Uploading the same key creates a new version instead of overwriting, and each version gets its own version ID. Objects uploaded before versioning was enabled have a version ID of null, and suspending versioning stops new versions but keeps existing ones.
A normal delete on a versioned bucket does not remove data. S3 adds a delete marker that hides the object, and deleting that marker brings the object back. Deleting a specific version ID removes that version permanently.
TipEnable versioning on any bucket holding data you cannot lose. Pair it with a lifecycle rule for noncurrent versions so old versions do not pile up forever.
How Does S3 Replication Work (CRR and SRR)?
Replication copies new objects from a source bucket to a destination bucket in the background. Cross-Region Replication (CRR) copies to another Region for disaster recovery or lower latency, and Same-Region Replication (SRR) copies within a Region, for example to combine logs. Both need versioning on source and destination and an IAM role S3 can use.
- Only objects created after the rule exists are replicated, and S3 Batch Replication copies existing objects
- Delete markers can be replicated if you choose, but deleting a specific version ID is never replicated
- Replication does not chain: A to B and B to C does not copy A to C
Which S3 Storage Class Should You Choose?
All storage classes have the same 11 nines of durability, so you choose on access pattern, retrieval time and cost. Use Standard for active data, the Infrequent Access classes for rarely read data, the Glacier classes for archives, and Intelligent-Tiering when you cannot predict access.
| Class | Best for | Minimum duration |
|---|---|---|
| Standard | Frequent access | None |
| Standard-IA | Backups, DR copies | 30 days |
| One Zone-IA | Re-creatable data | 30 days |
| Glacier Instant Retrieval | Archives needing milliseconds | 90 days |
| Glacier Flexible Retrieval | Archives, hours to retrieve | 90 days |
| Glacier Deep Archive | 7 to 10 year retention | 180 days |
| Intelligent-Tiering | Unknown or changing access | None |
Intelligent-Tiering moves each object between tiers by observed use, with no retrieval fee and a small per-object monitoring fee. The IA classes also bill for a minimum object size of 128 KB.
Common MistakePutting short-lived files in Glacier. An object deleted after one day is still billed for the full minimum duration, which is 90 days for Glacier Flexible and 180 days for Deep Archive.
How Do S3 Lifecycle Rules Cut Storage Costs?
A lifecycle rule moves objects to cheaper classes and deletes them after set numbers of days, with no manual work. Rules can apply to the whole bucket or to a prefix, and they can also expire old noncurrent versions and clean up failed uploads.
Day 0: logs/ uploaded to StandardDay 30: move to Standard-IADay 90: move to Glacier Flexible RetrievalDay 365: deleteRememberAlways add a rule that aborts incomplete multipart uploads after 7 days. Orphaned parts are billed but never become an object.
How Can You Improve S3 Upload and Download Performance?
S3 supports at least 3,500 write requests and 5,500 read requests per second per prefix, so more prefixes means more throughput. For big files use multipart upload, which uploads parts in parallel and lets you retry only a failed part. It is required above 5 GB and recommended above 100 MB.
- Transfer Acceleration: Uploads enter at the nearest AWS edge location and travel over the AWS network, which helps long-distance uploads for a small per-GB fee
- Byte-range fetches: Request only the bytes you need, or download several ranges in parallel for speed
Which S3 Encryption Method Should You Use?
Every new object is encrypted at rest by default with SSE-S3, so choose another method only when you need key control or an audit trail. Use SSE-KMS when you must prove who used a key, SSE-C when you supply your own keys on each request, and client-side encryption when AWS must never see plaintext.
| Method | Who manages the key |
|---|---|
| SSE-S3 | AWS, fully (default) |
| SSE-KMS | AWS KMS, with your key policy |
| SSE-C | You send the key per request over HTTPS |
| Client-side | You, before upload |
SSE-KMS calls KMS on every upload and download, and KMS request quotas are shared and vary by Region. High request rates can throttle. Turn on S3 Bucket Keys to cut KMS calls sharply, or use SSE-S3 when you do not need the audit trail.
How Do Pre-Signed URLs Share a Private S3 Object?
A pre-signed URL gives temporary access to one private object without making the bucket public. It embeds the object, the operation, an expiry time and a signature made with your credentials, and it stops working when the time is up or when the signing credentials expire.
aws s3 presign s3://razorpay-invoices/INV-2024-001.pdf \ --expires-in 3600 \ --region ap-south-1The CLI presign command creates download URLs. To let a user upload, generate an upload URL from an SDK.
How Do S3 Event Notifications Work?
S3 can notify other services when an object is created, deleted or restored, so you do not need to poll. Destinations are Lambda for immediate processing, SQS for queued workers, SNS for fan-out and EventBridge for filtering and routing to many targets. Delivery is at least once, so consumers must tolerate duplicates.
What Is S3 Object Lock?
Object Lock gives WORM (write once, read many) storage so objects cannot be changed or deleted until a retention period ends. In Governance mode, users with special permission can override the lock. In Compliance mode, nobody can, including the root user, and the retention cannot be shortened. A Legal Hold keeps an object locked until you remove it, with no expiry.
Object Lock requires versioning, and it can be enabled on an existing versioned bucket as well as at creation. Once enabled it cannot be turned off, so plan before enabling it on compliance buckets.
What Are S3 Access Points?
An access point is a named endpoint with its own policy that points at a shared bucket, so each team gets its own scoped access without one huge bucket policy. For example, a finance access point can allow only the finance/ prefix. S3 Object Lambda can transform data on the way out, for example to redact PII, but AWS has restricted it for new customers, so confirm availability before designing around it.
How Do You Host a Static Website on S3 and Configure CORS?
S3 can serve static files, but the website endpoint supports HTTP only, so put CloudFront in front for HTTPS, caching and a custom domain. CORS is needed when a browser page on one origin, such as https://myapp.in, fetches objects from your bucket on another origin. The bucket must return CORS headers that allow that origin.
aws s3api put-bucket-cors --bucket devops-lab-2024-rahul \ --cors-configuration 'CORSRules=[{AllowedOrigins=[https://myapp.in],AllowedMethods=[GET],AllowedHeaders=[*],MaxAgeSeconds=3600}]'Detailed Step-by-Step Practical Lab
This lab uses the AWS CLI in ap-south-1. Bucket names are global, so replace the suffix with your own.
Step 1: Create a versioned bucket
aws s3api create-bucket \ --bucket devops-lab-2024-rahul \ --region ap-south-1 \ --create-bucket-configuration LocationConstraint=ap-south-1 aws s3api put-bucket-versioning \ --bucket devops-lab-2024-rahul \ --versioning-configuration Status=EnabledBlock Public Access stays on, which is the default.
Step 2: Upload, overwrite, and list versions
echo "Version 1" > test.txtaws s3 cp test.txt s3://devops-lab-2024-rahul/test.txtecho "Version 2" > test.txtaws s3 cp test.txt s3://devops-lab-2024-rahul/test.txt aws s3api list-object-versions --bucket devops-lab-2024-rahul --prefix test.txtYou see two versions with different version IDs.
Step 3: Delete and restore
aws s3 rm s3://devops-lab-2024-rahul/test.txtaws s3api list-object-versions --bucket devops-lab-2024-rahul --prefix test.txt # Copy the DeleteMarkers VersionId from the output, then remove itaws s3api delete-object --bucket devops-lab-2024-rahul \ --key test.txt --version-id <DELETE-MARKER-VERSION-ID>The file reappears because only the delete marker was removed.
Step 4: Create a lifecycle rule in the console
Open the bucket, then Management, then Create lifecycle rule.
- Name: archive-logs, prefix: logs/
- Transition to Standard-IA after 30 days
- Transition to Glacier Flexible Retrieval after 90 days
- Expire current versions after 365 days
- Delete noncurrent versions after 90 days
- Delete incomplete multipart uploads after 7 days
Step 5: Generate a pre-signed URL
aws s3 presign s3://devops-lab-2024-rahul/test.txt --expires-in 600 --region ap-south-1Open the URL in a browser and the file downloads without a login. After 10 minutes it returns AccessDenied.
Step 6: Clean up
# Removes current objects. A versioned bucket also needs its versions and delete markers removed, which the console Empty button does for you.aws s3 rm s3://devops-lab-2024-rahul --recursiveaws s3api delete-bucket --bucket devops-lab-2024-rahul --region ap-south-1Production Best Practices & Common Pitfalls
- Keep Block Public Access on: Disable it only for reviewed exceptions, and serve public content through CloudFront with a private bucket.
- Enable versioning on important buckets: Add noncurrent version expiry so costs stay bounded.
- Add lifecycle rules from the start: Include aborting incomplete multipart uploads after 7 days.
- Use a separate bucket for access logs: Logging into the same bucket creates a loop of log files that grows without limit.
- Prefer IAM roles over long-lived keys: Use bucket policies for cross-account and anonymous cases.
- Use SSE-S3 by default: Choose SSE-KMS for audit needs, and enable Bucket Keys.
- Match storage class to real access: Remember minimum durations before moving short-lived data to Glacier.
- Make event consumers idempotent: Notifications can arrive more than once.
- Run S3 Storage Lens occasionally: It shows unencrypted data, versioning gaps and orphaned multipart uploads.
Common MistakeTurning off Block Public Access "just to debug" and forgetting to turn it back on. It does not make the bucket public by itself, but it lets a policy do so.
Common MistakeUsing SSE-KMS on a very high request-rate bucket without checking KMS quotas. KMS throttling then slows S3 even though S3 is fine.
Quick Reference & Troubleshooting Commands
| Task | Command |
|---|---|
| List buckets | aws s3 ls |
| Copy a file up | aws s3 cp file.txt s3://<bucket>/file.txt |
| Sync a folder | aws s3 sync ./logs s3://<bucket>/logs/ |
| List versions | aws s3api list-object-versions --bucket <bucket> |
| Delete one version | aws s3api delete-object --bucket <bucket> --key <key> --version-id <id> |
| Check public access settings | aws s3api get-public-access-block --bucket <bucket> |
| Read bucket policy | aws s3api get-bucket-policy --bucket <bucket> |
| Pre-signed download URL | aws s3 presign s3://<bucket>/<key> --expires-in 3600 |
| Problem | Likely cause and fix |
|---|---|
| AccessDenied on list | Policy covers objects but not the bucket ARN. Add the bucket-level statement. |
| Bucket policy ignored for public access | Block Public Access is on. Change it only if the bucket must be public. |
| Replication not working | Versioning missing on a bucket, or the role lacks permission. |
| Unexpected storage bill | Orphaned multipart uploads or old noncurrent versions. Add lifecycle rules. |
| Throttling with SSE-KMS | KMS quota reached. Enable Bucket Keys or request a quota increase. |
| Pre-signed URL expired early | Signing credentials, such as a role session, expired before the URL. |