Skip to content

Object Storage, Distributed File Systems, Presigned URLs & Content-Addressable Storage ​

"Amazon S3 provides strong read-after-write consistency for PUT and DELETE requests of objects in your Amazon S3 bucket in all AWS Regions." — Amazon S3 User Guide, What is Amazon S3?

Summary: Data you cannot keep in a database row comes in three storage models. Block storage is a raw disk for one machine. File storage is a shared directory tree with POSIX rules. Object storage is a flat map from a key to an immutable blob over HTTP, and it is where uploads, backups, media and data lakes live today. Around the object store sit four patterns that every web system ends up using: presigned URLs (the browser talks to the store, not to your servers), multipart and range requests (big objects in pieces), content-addressable storage (the key is the hash of the bytes) and a CDN in front of it all. Focus: block vs file vs object storage; POSIX, NFS, EFS, CephFS; GFS and HDFS (chunk servers, one metadata master), Lustre; the S3 model (bucket, key, prefix, flat namespace, metadata, versioning, Object Lock, lifecycle, storage classes, retrieval cost, strong read-after-write consistency, listing, erasure coding, durability, cross-region replication, event notifications); multipart upload and range GET; presigned URLs and POST policies; content-addressable storage (Git objects, IPFS, OCI registries); serving files (CDN, signed cookies, byte ranges); resumable uploads (tus, chunking); metadata in a database vs object metadata; encryption (SSE-S3, SSE-KMS, SSE-C, client side); IAM policy, bucket policy, public access block, ACLs; cost modelling; data lakes, Parquet and Iceberg; GCS, Azure Blob, MinIO and Ceph RGW; antipatterns; Go (AWS SDK for Go v2) and Laravel 13 code with tests. Learning goal: Given a feature that stores or serves files, choose the storage model, design the key layout and the metadata table, let browsers upload and download directly with short-lived signed requests that also bound size and type, serve through a CDN with correct range and cache behaviour, estimate the monthly bill from storage, request and egress volumes, and name the failure each decision removes.

This chapter owns the system-level decision: where the bytes live, how they get there and back, and what it costs. Siblings own the mechanics. CDN owns edge caching and cache hierarchy, Caching owns cache policies, Replication Topologies owns leader/follower and quorum replication, Consistency Models owns the definitions of linearizability and read-your-writes, Merkle Trees, Read Repair, Anti-Entropy owns the hash-tree machinery that content addressing reuses, and Cryptography, TLS, PKI & Secrets owns key management and envelope encryption. Hash functions and checksums themselves are in Checksums & Hashing. Query engines on top of object storage are in Big Data Architectures. Persian version: /fa/system-design/object-storage-file-systems.

Page map ​

If you are looking forGo to
The whole page in four tablesEverything in one minute
Why files do not belong in a database rowWhy it exists
GFS, HDFS, S3, Git, tus originsWhere it comes from
Raw disks, EBS, iSCSIBlock storage
NFS, EFS, CephFS, POSIXFile storage
GFS, HDFS, Lustre, chunk servers, metadata masterDistributed file systems
Bucket, key, prefix, flat namespaceThe object model
Read-after-write, LIST, other providersConsistency and listing
Versioning, delete markers, Object Lock, WORMVersioning and immutability
Storage classes, lifecycle, retrieval feesStorage classes and lifecycle
Eleven nines, erasure coding, replication, eventsDurability and replication
Big files, parallel parts, partial readsMultipart upload and range GET
Browser uploads straight to the storePresigned URLs
Size and type limits on uploadsPOST policies
Hash as key, dedup, Git, IPFS, registriesContent-addressable storage
CDN, signed cookies, video seekingServing files
Flaky mobile uploadsResumable uploads: tus and chunking
Where to keep names, owners, sizesMetadata: database vs object
SSE-S3, SSE-KMS, SSE-C, client sideEncryption
IAM, bucket policy, public access block, ACLAccess control
The monthly billCost modelling
Parquet, Iceberg, data lakesData lakes
GCS, Azure Blob, MinIO, Ceph RGWOther implementations
Mistakes seen in reviewsAntipatterns
Knobs, limits, error codesMechanics
CodeGo, Laravel
Failures and their fixesSolving the classic problems
Which storage for which jobChoosing
Monolith to multi-regionIn architecture
Commands and expected outputLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

Three storage models. Same bytes, three contracts.

Block storageFile storageObject storage
UnitFixed-size block addressed by numberFile in a directory treeWhole object under a key
InterfaceSCSI or NVMe commands, iSCSI over a networkPOSIX calls (open, seek, rename, flock) over NFS, SMB or a native clientHTTP: PUT, GET, DELETE, LIST, HEAD
SharingOne host at a time (usually)Many hosts mount the same treeAny client with credentials, anywhere
In-place editYes, any blockYes, any byte rangeNo: replace the whole object
ProductsAWS EBS, iSCSI SAN, local NVMeNFS, AWS EFS, CephFS, HDFS (not POSIX), LustreAWS S3, Google Cloud Storage, Azure Blob Storage, MinIO, Ceph RGW
Typical useDatabase data directory, boot diskShared home directories, legacy apps, ML scratchUploads, media, backups, logs, data lake
Scale limitOne volume, one hostMetadata serverPractically none for capacity; request rate per prefix

The five S3 facts to memorise.

FactValueSource
ConsistencyStrong read-after-write for PUT and DELETE, in all RegionsS3 User Guide
MultipartParts 1 to 10,000; part size 5 MiB to 5 GiB (last part may be smaller); max object 48.8 TiBS3 quotas page
Single request rateAt least 3,500 PUT/COPY/POST/DELETE or 11,000 GET/HEAD per second per partitioned prefixS3 performance guideline
Durability designMore than 99.999999999% (11 nines), data across at least 3 Availability Zones by defaultS3 storage classes page
Presigned URL lifetimeUp to 7 days with SigV4 and IAM-user credentials; never longer than temporary credentialsS3 presigned URL page

How a file gets from a browser into the store. Three designs, one right default.

DesignBytes pass through your app?Size and type enforcementWhen
App receives the upload, then writes to the storeYes, twice (in and out)Anywhere in your codeSmall files, need to inspect or transform
Presigned PUT URLNoOne exact size and content type, signed into the URLDefault for direct upload of one object
Presigned POST policyNoRange of sizes, key prefix, content type patternBrowser form uploads with limits

The one-line model of content addressing. key = SHA-256(bytes): same bytes give the same key (deduplication), a key can never point at different bytes (immutability), and every read can be verified against its own key (integrity).

Why it exists ​

A relational database is excellent at small, structured, transactional rows and bad at big blobs: a 20 MB image in a row bloats the heap and the WAL, evicts hot pages from the buffer cache, makes backups and replicas heavier, and ties file bandwidth to your most expensive tier. A local disk on an application server is cheap and fast but is lost with the server, cannot be shared by ten replicas, and caps out at one disk. Storage systems exist to give you capacity, durability and sharing without those couplings.

ChoiceGives youCosts you
Bytes in the database rowOne transaction covers metadata and bytesBloated backups, replica lag, expensive bandwidth
Bytes on the server's local diskFastest reads, no network hopLost on failure, not shared, sticky sessions
Bytes on a shared file system (NFS, EFS)POSIX semantics, many readers and writersMetadata server limit, per-operation latency, higher price per GB
Bytes in an object storeNear-unbounded capacity, high durability, cheap per GB, HTTP from anywhereNo in-place edit, per-request pricing, first-byte latency, listing is not a database

An everyday picture. A warehouse with a claim ticket system. A block device is the empty floor: you place pallets anywhere, but only your forklift is allowed in. A file system is an office archive with drawers and folders that several clerks use at once and one filing clerk who knows where everything is. An object store is a left-luggage counter: hand over a bag, get a ticket number (the key), later hand the ticket back to receive exactly that bag. You cannot open the bag and change one sock at the counter; you hand in a new bag. The counter can serve a million people because it never needs to know what is in the bags.

Three common misunderstandings, up front ​

  1. "S3 is a file system in the cloud." It is not. There are no directories (only key prefixes), no rename (copy then delete), no append, no partial overwrite and no locks. Tools that mount a bucket as a drive hide those gaps and pay for it in latency and surprises.
  2. "S3 is eventually consistent." It was, for overwrites and deletes, before December 2020. The User Guide now states strong read-after-write consistency for PUT and DELETE in all Regions, and listing after a write is consistent too. Many old blog posts and many interview answers are stale.
  3. "A presigned URL is a secret that makes the file private." It is a bearer token: anybody holding the URL can use it until it expires. It bounds time, key and method, nothing else (not who holds it). It does not replace authorisation checks before you issue it.

Where it comes from ​

DateMilestoneSource
2003The Google File System (SOSP 2003): "a single master and multiple chunkservers", 64 MB chunks, three replicas by default, the master keeps all metadata in memory and logs mutations; designed for large streaming reads and record appends, not POSIXGhemawat, Gobioff, Leung, GFS paper
Mid 2000sHDFS copies the GFS shape: "a single NameNode, a master server that manages the file system namespace" plus DataNodes, write-once-read-many semantics, 128 MB typical blockApache Hadoop, HDFS Architecture
Mid 2000sAmazon S3 introduces the bucket and key model over HTTP and becomes the template for every later object storeS3 User Guide (launch year not re-verified here)
2005 onwardGit stores everything as objects whose id is the hash of their content: "Git is a content-addressable filesystem"Pro Git, chapter 10
Dec 2020S3 moves from eventual consistency for overwrites and deletes to strong read-after-write consistencyS3 User Guide states the current behaviour; the date is from the AWS announcement, not re-fetched
2023S3 applies SSE-S3 encryption to every new object upload by default (January 5, 2023)S3 encryption page
LaterOpen table formats (Apache Iceberg) give object stores snapshot semantics and atomic table commitsIceberg specification (dates not researched)

The through-line is the same each time: separate the small, fast, coordinated metadata path from the large, parallel, replicated data path. GFS did it with a master and chunk servers, S3 does it with an index plus erasure-coded storage nodes, Git does it with ids derived from the data itself.

The concept catalogue ​

Block storage Important ​

In plain words: A block device is a disk that looks like a long array of equal-sized blocks. Whatever is on top (ext4, XFS, a database) decides what the blocks mean. A cloud block volume is the same thing delivered over the network.

Common misunderstanding: "A network volume is shared storage." A block volume such as AWS EBS is normally attached to one instance at a time. Two servers writing to the same raw volume with an ordinary file system corrupt it, because neither knows about the other's cached metadata. Sharing needs a file system layer (NFS, EFS, CephFS, a cluster file system).

Definition: Storage addressed by block number (typically 512 bytes to 4 KiB per block), accessed with SCSI or NVMe semantics, locally or over a network protocol (iSCSI, NVMe over Fabrics, Fibre Channel, AWS EBS). The consumer owns the file system and all consistency above the block.

 1  database   -> filesystem  write(fd, page 8 KiB)
 2  filesystem -> block layer  write blocks 91002..91003 (journal first, then data)
 3  block layer-> EBS / iSCSI  network round trip to the volume
 4  volume     -> replicas     the provider replicates inside one Availability Zone
 5  volume     -> database     ack after the write is durable

Real scenario: PostgreSQL or MySQL data directories sit on EBS gp3 or io2 volumes. A Kafka broker uses a volume per broker. Boot disks of virtual machines are block volumes. Snapshots of a volume go to object storage behind the scenes, which is why block storage is often "a cache in front of an object store" from the provider's point of view.

ProductWhat it isSharingNotes
AWS EBSNetwork block volume in one AZOne instance (Multi-Attach only for specific volume types with a cluster-aware file system)Snapshots to S3-backed storage
iSCSI target (LIO, TrueNAS)SCSI over TCPOne initiator at a time unless cluster-awareOn-prem SANs
Local NVMe (instance store)Disk in the hostOne hostLost with the instance
Ceph RBDBlock image on a Ceph clusterOne client by defaultSame cluster can serve CephFS and RGW

Fix / how to use it: keep databases and queues on block volumes, not on object stores; keep the unstructured payloads those databases refer to in objects. Back up the volume with snapshots and the data with the database's own tooling. In code, the only thing that changes is the mount path.

sql
-- PostgreSQL: keep big blobs out of the heap; the row keeps only the pointer
SELECT pg_size_pretty(pg_total_relation_size('files'));   -- stays small
SELECT pg_size_pretty(pg_database_size(current_database()));

File storage: POSIX, NFS, EFS, CephFS Important ​

In plain words: A file system gives you folders, file names, permissions and the right to change part of a file. A network file system lets many machines see the same folders.

Common misunderstanding: "NFS behaves like a local disk." Close, not equal. Locking, caching and rename atomicity depend on the protocol version and mount options; a program that relies on local-disk guarantees (SQLite on NFS, lock files, O_APPEND from many hosts) fails in ways that are hard to reproduce.

Definition: POSIX defines the semantics most programs expect: hierarchical namespace, open/read/write/seek/rename/unlink, permission bits, fsync, advisory locks, and atomic rename within one file system. A distributed or network file system implements as much of that as it can across hosts, using a metadata service plus data servers.

 1  client A -> NFS server  OPEN /shared/report.csv   (read-write)
 2  client B -> NFS server  OPEN /shared/report.csv
 3  client A -> NFS server  WRITE offset 0, 4096 bytes
 4  server   -> client A    OK (stable if sync, else buffered)
 5  client B -> NFS server  GETATTR (close-to-open: B sees A's data only after A closes and B opens again)

Real scenario: A CMS with several web servers shares an uploads/ directory over EFS or NFS. A research cluster uses Lustre or CephFS as a fast scratch tree. A lift-and-shift of a legacy app that writes to /var/data mounts EFS because the code cannot be changed. Kubernetes ReadWriteMany volumes are backed by NFS, EFS, or CephFS.

ProductProtocolScales howKnown sharp edges
NFS (v3, v4.1)NFS over TCPOne server, or pNFS for parallel dataClose-to-open consistency; stale file handles after server failover
AWS EFSNFS v4.1 managed serviceElastic capacity, regionalHigher per-operation latency than local disk; priced per GB-month well above S3
CephFSPOSIX on Ceph (metadata servers + OSDs)Add MDS and OSD nodesMDS tuning; same Ceph cluster can also expose block and S3
SMB / CIFSSMB 3Windows ecosystemsDifferent locking model
LustreNative clientMany metadata and object storage targetsHPC; striping configuration

Fix / how to use it: if you can change the application, move uploads to object storage and keep a file system only for what truly needs POSIX. If you cannot, mount it read-only on the replicas that only serve, and write from one place.

Distributed file systems: GFS, HDFS, Lustre Important ​

In plain words: A distributed file system cuts each big file into large pieces, copies each piece to several cheap machines, and keeps one small, smart index that remembers which pieces live where. Clients ask the index once, then pull the data straight from the machines.

Common misunderstanding: "The master is a bottleneck, so this design cannot scale." The master only handles metadata. The GFS paper states the point directly: the client asks the master which chunkservers hold a chunk, caches the answer, and "interacts with the chunkservers directly" for data. The master's real limit is the RAM that holds the namespace, not bandwidth.

Definition: A cluster file system with (a) a metadata service that holds the namespace and the file-to-chunk map, and (b) many chunk servers (GFS) or DataNodes (HDFS) that store replicated, fixed-size chunks as local files. GFS: "a single master and multiple chunkservers", 64 MB chunks, three replicas by default, metadata in master memory with an operation log. HDFS: "a single NameNode" plus DataNodes, "write-once-read-many" access, "a typical block size used by HDFS is 128 MB", an EditLog for persistence, rack-aware replica placement.

 1  client -> master        open("/logs/2026-11-25"), chunk index 7
 2  master -> client        chunk handle H, replicas on cs3, cs9, cs14 (primary cs9)
 3  client -> cs3           read H, offset 0, 1 MiB   (nearest replica, no master involved)
 4  cs3    -> client        1 MiB (checksum verified before returning)
 5  cs3    -> master        heartbeat: I hold chunks {H, ...}   (master learns locations this way)

Real scenario: Hadoop and Spark jobs read huge files from HDFS and ship computation to the node that holds the block. GFS (and its successor Colossus) stores Google's internal data. Lustre serves supercomputer scratch space, striping one file over many object storage targets. Ceph's CephFS separates metadata servers from object storage daemons in the same way.

ConcernGFSHDFSCephFS / Lustre
MetadataSingle master, namespace in RAM, operation log, checkpointsSingle active NameNode (HA pair and Federation exist), EditLog and imageMetadata server cluster (MDS / MDT)
Data unit64 MB chunk128 MB block (typical)Object / stripe
Durability3 replicas default, checksums per blockReplication factor 3 default, erasure coding availableReplication or erasure coding in the underlying store
WritesRecord append for concurrent producersWrite once, append onlyPOSIX writes
FitsLarge sequential reads and appendsBatch analyticsShared POSIX tree at scale

Fix / how to use it: do not use a DFS for web uploads. Use it when the compute framework wants data locality; otherwise object storage plus a query engine has replaced most HDFS clusters (see Data lakes). The design lesson carries over to your own systems: keep a small authoritative index, push bulk bytes through a parallel data path.

The object model: bucket, key, prefix, metadata Must-know ​

In plain words: An object store holds objects. Each object has a key (its name), bytes, and some labels. Objects live in buckets. You store, fetch, delete and list objects; you do not edit them.

Common misunderstanding: "photos/2026/a.jpg means there is a folder photos/2026/." The namespace is flat. A key is one string; / is only a character. The console and LIST with Delimiter=/ group keys by prefix so they look like folders. Consequence: "renaming a folder" means copying and deleting every key beneath it, one request each.

Definition: In S3 terms: a bucket is a container with a globally unique name in a Region; an object is a key, a value (up to 48.8 TiB), system metadata (Content-Type, Content-Length, ETag, Last-Modified), user metadata (x-amz-meta-* headers) and optionally tags and a version id. The API verbs are PutObject, GetObject, HeadObject, DeleteObject, CopyObject, ListObjectsV2, plus multipart operations. Objects are immutable once written: a new PutObject on the same key replaces the previous object atomically.

 1  client -> store  PUT /uploads/u/42/ab/cd01.png   Content-Type: image/png   x-amz-meta-owner: 42
 2  store  -> client 200 OK, ETag: "9b2cf535f27731c974343645a3985328", x-amz-version-id: 3HL4...   (if versioning is on)
 3  client -> store  LIST /uploads?prefix=u/42/&delimiter=/    -> keys and "common prefixes" under u/42/
 4  client -> store  COPY u/42/ab/cd01.png -> u/42/archive/cd01.png   then   DELETE the old key

Real scenario: User avatars at avatars/{userId}.jpg. Build artifacts at ci/{repo}/{sha}/app.tar.gz. Logs partitioned as logs/dt=2026-11-25/hour=09/part-0001.parquet. Terraform state in one object per workspace. Container image layers in a registry backed by an object store.

PropertyS3Google Cloud StorageAzure Blob StorageMinIO / Ceph RGW
ContainerBucketBucketContainer inside a storage accountBucket
NamespaceFlat, prefix by conventionFlat; optional hierarchical namespace bucketsFlat, optional hierarchical namespace (ADLS Gen2)Flat
RenameCopy and deleteCopy and delete (rename for hierarchical buckets)Rename for hierarchical namespaceCopy and delete
APIS3JSON and XML (S3-interoperable)Blob RESTS3-compatible

Fix / how to use it: generate keys yourself (UUIDs or hashes), never reuse user file names as keys, keep display names in the database, and spread keys so a single hot tenant does not become a single hot prefix (see Access patterns and hot prefixes).

sql
-- the database holds meaning; the key holds location
SELECT object_key FROM files WHERE id = '5f8e2c4a-7d1b-4a6e-9c3f-0b2d7e1a4c58' AND owner_id = 42;

Consistency and listing Must-know ​

In plain words: "Strong read-after-write consistency" means: once your upload call returns success, any read you or anyone else makes afterwards sees that upload. No "wait a few seconds and retry".

Common misunderstanding: "Strong consistency means I can use the bucket as a database or a lock." It makes each single-key operation predictable. It does not give you transactions across keys, atomic rename, or a unique-name guarantee for concurrent writers (last writer wins, unless you use conditional writes).

Definition: S3 provides strong read-after-write consistency for PUT and DELETE of objects, for both new keys and overwrites, and its list, metadata and ACL reads reflect those writes. Conditional writes (If-None-Match: *, If-Match on PutObject) let a writer say "create only if absent" or "replace only if the ETag is what I read". Before December 2020 overwrites, deletes and a LIST right after a PUT could return stale results.

 1  A -> S3  PUT key k = v1               200 OK
 2  B -> S3  GET key k                    v1        (strong: always)
 3  A -> S3  PUT key k = v2               200 OK
 4  B -> S3  GET key k                    v2        (before 2020 this could still be v1)
 5  A -> S3  DELETE key k                 204
 6  B -> S3  LIST prefix                  k absent  (strong list since 2020)

Real scenario: A deploy script uploads config.json then immediately starts workers that read it: safe on S3 today. A job writes part-0001..part-0200 then writes a _SUCCESS marker; readers wait for the marker. A lock built on "create object if absent" using If-None-Match: * works as a coarse mutex, not as a fenced lease (see Distributed Locking).

StoreRead-after-write for objectsListing after writesSource
Amazon S3Strong (PUT and DELETE, all Regions)StrongS3 User Guide
Google Cloud StorageStrong global consistency for object read-after-write, metadata update, delete and object listingStrongGCS consistency page
Azure Blob StorageStrong consistency for blob operations within a storage account (not re-verified here)Strong (not re-verified)Microsoft docs, not fetched
MinIOStrong for single objects in a single deployment (distributed mode uses erasure sets)StrongMinIO docs (not re-verified for listing)
Ceph RGWStrong within a zone; multi-site replication between zones is asynchronous and eventually consistentStrong within a zoneCeph docs (multi-site detail not re-verified)

Fix / how to use it: never poll to see whether your own write is visible; trust the return value. Use If-None-Match: * for create-once and If-Match plus ETag for compare-and-swap. For multi-region reads you still have replication lag (see Durability and replication).

sql
-- Idempotent registration: the DB row is created before the object, so a retry cannot double-count
INSERT INTO files (id, owner_id, object_key, original_name, content_type, size_bytes, status)
VALUES ('5f8e2c4a-7d1b-4a6e-9c3f-0b2d7e1a4c58', 42, 'u/42/5f/5f8e2c4a', 'a.png', 'image/png', 1234, 'pending')
ON CONFLICT (id) DO NOTHING;

Versioning and immutability: delete markers, Object Lock, WORM Important ​

In plain words: Turn versioning on and a delete does not erase anything: the store puts a "deleted" note on top and keeps the old bytes. Turn Object Lock on and nobody, including you, can erase or overwrite a version until its time is up.

Common misunderstanding: "Versioning is a backup." It protects from overwrite and accidental delete inside the same bucket, account and Region. It does not protect from a compromised account that holds s3:DeleteObjectVersion, from a bucket deleted with its versions, or from a regional outage. Object Lock in compliance mode and cross-account replication are the protections that survive that.

Definition: With S3 Versioning each overwrite creates a new version and each DELETE without a version id inserts a delete marker, which becomes the current version; "you can always restore the previous version". Object Lock uses a write-once-read-many (WORM) model with two retention modes: governance (privileged users can bypass) and compliance ("a protected object version can't be overwritten or deleted by any user, including the root user in your AWS account"), plus legal holds (no expiry, set and removed explicitly). Lock needs versioning.

 1  PUT   k  ->  version v1                      current = v1
 2  PUT   k  ->  version v2                      current = v2   (v1 kept, noncurrent)
 3  DELETE k ->  delete marker m                 current = m    GET k -> 404, versions still there
 4  DELETE k?versionId=m  -> marker removed      current = v2   (this is the "undelete")
 5  with Object Lock (compliance, 7 years): DELETE k?versionId=v2  -> 403 AccessDenied until retain-until-date

Real scenario: Audit logs and financial exports under SEC 17a-4 style retention use Object Lock in compliance mode (AWS states Object Lock has been assessed by Cohasset Associates for SEC 17a-4, CFTC and FINRA requirements). Ransomware recovery relies on versioning plus a lifecycle rule that expires noncurrent versions after N days. A legal hold freezes evidence while a case runs.

FeatureProtects fromDoes not protect fromCost note
VersioningOverwrite, plain deleteAccount compromise, bucket deletion, region lossEvery version bills as storage
Object Lock governanceDelete by ordinary usersUsers with bypass permissionSame as versioning
Object Lock complianceEveryone, including root, until retain-untilNothing in scope, but you also cannot fix a mistakeCannot shorten retention
Legal holdDelete while hold is onWhoever may remove the holdNone extra
Cross-Region or cross-account replicationRegion loss, account compromise (with separate account)Logical corruption replicated as a new versionStorage + requests + transfer

Fix / how to use it: enable versioning on every bucket that holds user data; add a lifecycle rule for noncurrent versions (see lifecycle.json); use compliance mode only after testing in governance mode, because it cannot be undone.

Storage classes, lifecycle policies and retrieval cost Must-know ​

In plain words: Data you read every day should sit in the fast, pricier tier. Data you read once a year can sit in a much cheaper tier that charges you when you fetch it. A lifecycle rule moves objects between tiers by age and deletes them at the end.

Common misunderstanding: "Moving to Glacier always saves money." Cheaper classes have minimum storage durations and retrieval fees, and tiny objects are rounded up (S3 charges for 128 KB minimum in the infrequent-access classes). Transitions are billed as requests. A bucket of millions of 5 KB files can cost more in Glacier than in Standard.

Definition: Storage classes in S3 include Standard, Intelligent-Tiering (INTELLIGENT_TIERING, no retrieval fees, small monitoring fee), Standard-IA and One Zone-IA (STANDARD_IA, ONEZONE_IA), Glacier Instant Retrieval (GLACIER_IR), Glacier Flexible Retrieval (GLACIER), Glacier Deep Archive (DEEP_ARCHIVE) and Express One Zone. The IA and Glacier classes "require minimum storage durations and retrieval fees" (the User Guide gives 30 days for Standard-IA, and "if you delete an object before the end of the 30-day minimum storage duration period, you are charged for 30 days"). A lifecycle configuration is a set of rules with transition actions (to another class after N days) and expiration actions (delete after N days), filtered by prefix or tag, plus AbortIncompleteMultipartUpload and noncurrent-version rules.

 1  day 0     PUT logs/a.gz                 class STANDARD
 2  day 30    lifecycle transition          -> STANDARD_IA     (transition request billed)
 3  day 90    lifecycle transition          -> GLACIER         (minimum 90 days there, retrieval takes minutes to hours)
 4  day 200   GET logs/a.gz                 -> 403 InvalidObjectState until RestoreObject is requested
 5  day 365   lifecycle expiration          -> object deleted

Real scenario: Application logs: Standard for 30 days (debugging), Glacier for a year (audit), then gone. Media originals: Intelligent-Tiering because nobody can predict which videos stay popular. Compliance archives: Deep Archive with Object Lock. A cleanup rule that aborts multipart uploads left unfinished after 7 days, a classic silent cost.

ClassIntended forRetrievalMinimum durationRetrieval fee
StandardFrequently accessedMillisecondsNoneNo
Intelligent-TieringUnknown or changing accessMilliseconds (optional archive tiers: minutes to hours)NoneNo
Standard-IA / One Zone-IARarely accessed, needs fast accessMilliseconds30 days (128 KB minimum billed size)Yes, per GB
Glacier Instant RetrievalArchive read about once a quarterMilliseconds90 daysYes
Glacier Flexible RetrievalArchiveMinutes to hours90 daysYes
Glacier Deep ArchiveLong-term archiveHours180 daysYes

Fix / how to use it: start from the lifecycle file in config/lifecycle.json that aborts incomplete multipart uploads, tiers logs and expires old versions. Re-measure with S3 Storage Class Analysis before applying to user-facing data.

sql
-- Which of my objects are cold? (daily inventory loaded into a table)
SELECT date_trunc('month', last_modified) AS month, storage_class, count(*), sum(size_bytes) / 1e9 AS gb
FROM s3_inventory
WHERE bucket = 'example-uploads'
GROUP BY 1, 2
ORDER BY 1, 2;

Durability, erasure coding and replication Important ​

In plain words: Durability is "will my bytes still exist next year". An object store gets very high durability by spreading each object over many disks and several data centres, using maths (erasure coding) so that it needs fewer extra copies than plain replication.

Common misunderstanding: "Eleven nines durability means 99.999999999% availability." Durability is about not losing the object; availability is about being able to read it right now. S3 Standard is designed for 11 nines durability and a lower availability figure, and neither number protects you from deleting the object yourself.

Definition: Erasure coding splits an object into K data shards and M parity shards (Reed-Solomon); any K of the K+M shards rebuild the object. MinIO documents it directly: objects are partitioned across an erasure set, for example 16 drives with parity EC:4, so it survives the loss of four drives in the set. Replication copies whole objects. S3 states it is "designed to exceed 99.999999999% (11 nines) data durability" and stores data "redundantly across a minimum of 3 Availability Zones by default" (One Zone classes use one). Cross-Region Replication (CRR) and Same-Region Replication (SRR) copy new objects asynchronously between buckets and need versioning on both sides.

 1  PUT 12 MB object -> front end splits into K=8 data shards + M=4 parity shards (illustrative K,M)
 2  shards -> 12 disks on distinct failure domains (different servers, racks, AZs)
 3  disk 3 and disk 9 die
 4  GET -> any 8 surviving shards -> Reed-Solomon decode -> original bytes (checksum verified)
 5  background repair rebuilds shards 3 and 9 on new disks
 6  storage overhead = (K+M)/K = 1.5x, versus 3x for three replicas, while tolerating 4 losses instead of 2

Real scenario: MinIO on commodity servers uses erasure sets to give S3-like durability on-premises. Ceph RGW pools can be replicated (size 3) or erasure coded (k+m). A SaaS replicates uploads from eu-west-1 to eu-central-1 with CRR for disaster recovery; a data-sovereignty rule keeps EU customer data in two EU Regions only. A s3:ObjectCreated:* event notification triggers thumbnailing (events are "designed to be delivered at least once", typically in seconds, so handlers must be idempotent).

MechanismOverheadFailures toleratedRepair costUsed by
3 replicas3.0x2 copies lostCopy one replicaGFS, HDFS default, Ceph replicated pools
Reed-Solomon K+M(K+M)/KM shards lostRead K shards to rebuild oneS3 (internal), MinIO, Ceph EC pools, HDFS erasure coding policies
Cross-Region replication2x storage + transferWhole-Region lossAsynchronous copyS3 CRR, GCS dual-region, Azure GRS

Fix / how to use it: pick replication scope by failure you must survive (disk, AZ, Region, account), not by habit. CRR is asynchronous: the recovery point is "whatever had replicated". Event notifications go to Amazon SQS, SNS, Lambda or EventBridge; design the handler to be idempotent and to tolerate reordering (see Messaging for outbox and idempotent consumers).

Multipart upload and range GET Must-know ​

In plain words: Upload a big file as numbered pieces that can travel in parallel and be retried one by one, then ask the store to glue them together. Download part of an object by asking for a byte range.

Common misunderstanding: "I can just PUT a 10 GB file." A single PutObject is capped far below the maximum object size (5 GB per the AWS API reference, not re-verified here) and, more importantly, restarts from zero on any failure and uses a single connection. Also: an unfinished multipart upload is invisible in listings but still billed until you complete or abort it.

Definition: Three steps: CreateMultipartUpload returns an upload id; UploadPart sends parts numbered 1 to 10,000 (5 MiB to 5 GiB each, last part may be smaller) and returns an ETag for each; CompleteMultipartUpload lists the part numbers and ETags and the store assembles the object. AbortMultipartUpload frees the parts. A range GET sends Range: bytes=start-end (inclusive) and receives 206 Partial Content; GetObject also accepts partNumber to fetch one original part.

 1  client -> S3  CreateMultipartUpload key=big.bin            -> UploadId = U1
 2  client -> S3  UploadPart U1, part 1 (16 MiB)               -> ETag e1   \
 3  client -> S3  UploadPart U1, part 2 (16 MiB)               -> ETag e2    >  parallel, retry per part
 4  client -> S3  UploadPart U1, part 3 (3 MiB, last)          -> ETag e3   /
 5  client -> S3  CompleteMultipartUpload U1 [(1,e1),(2,e2),(3,e3)]   -> object big.bin exists atomically
 6  reader -> S3  GET big.bin  Range: bytes=16777216-33554431  -> 206 Partial Content (part 2 only)

Real scenario: A backup tool uploads a 2 TB database dump with 64 parallel parts of 256 MiB (2 TB / 10,000 parts = 200 MB minimum part size). A video player seeks to minute 40 with a range request instead of downloading the file. A Parquet reader fetches only the footer and the needed column chunks of a 1 GB file using ranges. A parallel downloader opens N range requests to saturate a fast link.

ClientBehaviourKnob
AWS SDK for Go v2 manager.UploaderSplits into parts, uploads concurrently, aborts on failure unless LeavePartsOnErrorPartSize, Concurrency, MaxUploadParts
AWS CLI s3 cpMultipart over a threshold, parallelmultipart_threshold, multipart_chunksize, max_concurrent_requests
Laravel putFileAs (Flysystem S3)Streams the file; large streams use multipart in the SDKDisk options
MinIOSame API, same limitsServer side

Fix / how to use it: always add a lifecycle rule AbortIncompleteMultipartUpload after 7 days. Pick a part size from the arithmetic: max(5 MiB, size / 10,000) (the Go multipart.Plan below does exactly this). Verify integrity with a checksum header (SHA-256, CRC32C) per part when the data matters.

Presigned URLs Must-know ​

In plain words: Your server signs a link that says "whoever has this link may upload this one object, or download that one object, for the next five minutes". The browser uses the link and talks to the store directly. Your servers never carry the bytes.

Common misunderstanding: "The link is private because it is long and random." The signature authenticates the request parameters, not the holder. Anyone who sees the URL (browser history, proxy logs, a chat message, a Referer header) can use it until it expires. Short expiry and narrow scope are the only protections.

Definition: A presigned URL carries an AWS Signature Version 4 in query parameters: X-Amz-Algorithm, X-Amz-Credential, X-Amz-Date, X-Amz-Expires (seconds), X-Amz-SignedHeaders, X-Amz-Signature. It is computed locally from the secret key; the store recomputes it when the request arrives. Validity is capped: "valid up to 7 days when you're using AWS Signature Version 4" for IAM-user credentials, and "can't be valid for longer than the credentials themselves" for temporary credentials (an IAM role session ends the URL when the session ends). Headers listed in X-Amz-SignedHeaders (for example content-type, host) must be sent exactly as signed.

 1  browser -> app     POST /uploads {name: "a.png", type: "image/png", size: 1234}
 2  app                authorise user, INSERT files(status='pending'), sign PUT for key u/42/ab/uuid, ttl 10 min
 3  app     -> browser {url: https://bucket.s3.../u/42/ab/uuid?X-Amz-Expires=600&X-Amz-SignedHeaders=content-type;host&X-Amz-Signature=...}
 4  browser -> S3      PUT url   Content-Type: image/png   (body: 1234 bytes)
 5  S3                 recompute signature; headers match? not expired? -> store
 6  S3      -> browser 200 OK   ETag
 7  browser -> app     POST /uploads/uuid/done      app HEADs the key, checks size, status='ready'

Real scenario: Any web app with user uploads: profile pictures, invoices, attachments, video originals. Download links to private reports with a two-minute expiry and response-content-disposition=attachment; filename=.... A mobile client uploads a 200 MB video straight to S3 over an unreliable link.

VariantWhat is signedLimits it can enforceUse
Presigned GETMethod, key, expiry, optional response header overridesTime, keyPrivate download
Presigned PUTMethod, key, expiry, signed headers (Content-Type, Content-Length, x-amz-*)Exactly one content type and, if signed, one lengthDirect upload of one object
Presigned UploadPartOne part of one multipart uploadUpload id, part numberBrowser-side multipart
Presigned POST (policy)A JSON policySize range, key prefix, content type pattern, metadataForm-based browser upload (POST policies)

Fix / how to use it: in Go use s3.NewPresignClient(client).PresignPutObject(...), in Laravel Storage::temporaryUploadUrl() (see Go and Laravel). Rules: ttl of minutes; generate the key on the server; sign Content-Type; record a pending row first; confirm with HEAD; never log the full URL; sign with a role with write access only to the upload prefix, because the URL inherits the signer's permissions (and dies with its session).

sql
-- Sweep uploads that were presigned but never completed
UPDATE files SET status = 'deleted'
WHERE status = 'pending' AND created_at < now() - interval '1 day';

POST policies: size and type constraints Important ​

In plain words: A presigned PUT can fix one exact size. A POST policy is a signed rulebook: "the key must start with u/42/, the type must be image/png, the size must be between 1 byte and 5 MiB". The browser submits an HTML form with the policy and the file.

Common misunderstanding: "I validate size in JavaScript, so uploads are bounded." The browser is the attacker's tool. Only a constraint signed into the URL or policy is enforced by the store.

Definition: A POST policy is a base64-encoded JSON document with an expiration and conditions ({"bucket": "..."}, ["starts-with", "$key", "u/42/"], {"Content-Type": "image/png"}, ["content-length-range", 1, 5242880]), signed with SigV4. The form posts the policy, signature and fields as multipart/form-data; the file field must come last. A violation returns 403 AccessDenied ("Policy Condition failed") or EntityTooLarge / EntityTooSmall for the length range.

 1  app     -> browser  {url, fields: key, policy, X-Amz-Algorithm, X-Amz-Credential, X-Amz-Date, X-Amz-Signature}
 2  browser -> S3       POST url  multipart/form-data  fields... then file=@a.png
 3  S3                  verify signature, expiration, each condition
 4  S3      -> browser  204 No Content  (or 403 with the failed condition)

Real scenario: A public form where users attach up to 5 MiB images, with the key forced under a per-user prefix. A CMS that must refuse anything other than application/pdf. Go's AWS SDK v2 exposes PresignPostObject with PresignPostOptions.Conditions; Laravel has no first-party POST-policy helper, so you drop to the AWS SDK for PHP's PostObjectV4.

ConstraintPresigned PUTPOST policy
Exact sizeYes, sign Content-LengthYes (min = max)
Size rangeNoYes: content-length-range
Content typeExact valueExact or starts-with
KeyFixedFixed or starts-with prefix
Clientfetch/XHR with PUTHTML form or FormData

Fix / how to use it: prefer a presigned PUT with a signed exact Content-Length when your client knows the size; use a POST policy when you need a range or a prefix. Always re-check with HEAD after the upload and run a content sniff (magic bytes) in an async job: a policy checks the declared type, not the content.

Content-addressable storage Must-know ​

In plain words: Instead of choosing a name for a file, name it by what is in it: the SHA-256 of its bytes. Two identical files then have the same name and are stored once, and you can always check that a file is intact by hashing it again.

Common misunderstanding: "Content-addressed means encrypted or unguessable." The key is a public function of the content. Anyone who has the same file can compute the key and, if your store answers "exists" to unauthenticated probes, learn that you hold it. Hashing is for identity and integrity, not secrecy. Also: it is not magic dedup of "similar" files; one flipped byte is a new object (chunking schemes fix that, see below).

Definition: A store whose key is a cryptographic digest of the value. Properties: deterministic naming, free deduplication, immutability (changing the content changes the key), self-verifying reads, and trivial caching (a digest URL can be cached forever). Git: "Git is a content-addressable filesystem… at the core of Git is a simple key-value data store"; objects (blob, tree, commit) are named by the SHA-1 of their content plus header, and a tree contains the ids of its children, which forms a Merkle DAG. IPFS: a Content Identifier (CID) "is a label used to point to material in IPFS… based on the content's cryptographic hash"; "the same content added to two different IPFS nodes using the same settings will produce the same CID", and IPFS uses SHA-256 by default. OCI registries: a blob is "addressable by a digest" such as sha256:... and a manifest references blobs by descriptor.

 1  client  sha256("hello") = 2cf24dba...                         (compute the key locally)
 2  client -> store  HEAD /blobs/sha256/2c/f2/2cf24dba...         404: not present
 3  client -> store  PUT  /blobs/sha256/2c/f2/2cf24dba...         body "hello"
 4  other client uploads the same bytes -> HEAD returns 200 -> skips the upload (deduplicated)
 5  reader -> store  GET key; sha256(body) must equal the key      mismatch => corruption, refuse and refetch
 6  garbage collection: a blob is deleted only when no manifest or tree references it (mark and sweep)

Real scenario: Docker Hub, GHCR and ECR store image layers as digests, so a base layer shared by 1,000 images is stored once and pulled once per host. Git repositories, restic and borg backups, Nix store paths, Bazel remote caches and package registries (npm tarball integrity, Go module sum database) all rely on it. A document-upload product stores user files by SHA-256 to deduplicate a company-wide PDF that 5,000 employees upload.

ConcernContent-addressedName-addressed
IdentityHash of bytesChosen by writer
Update in placeImpossible by designOverwrite
DedupAutomaticNeeds a separate index
Integrity checkBuilt inSeparate checksum column
Access controlNeeds a separate mapping from owner to digestNatural (per-key policy)
DeletionReference counting or GC; privacy erasure is hardDelete the key
Hash choiceSHA-256 (SHA-1 in old Git, with collision-resistant variants in newer Git)n/a

Fix / how to use it: the Go package cas below hashes, checks existence, uploads with If-None-Match: * and re-verifies on read. Keep ownership and permissions in the database (files rows point to a digest), shard the key (blobs/sha256/ab/cd/...) so prefixes spread, run mark-and-sweep GC with a grace period, and never allow users to claim a digest without proving possession (upload the bytes or a hash proof), or one user can read another's data by guessing its hash. See Checksums & Hashing for why SHA-256 and not CRC or MD5.

sql
-- Digest-indexed catalogue: who references which blob (garbage collection input)
CREATE TABLE blob_refs (
    digest   char(71) NOT NULL,                -- 'sha256:' + 64 hex
    file_id  uuid     NOT NULL REFERENCES files(id),
    PRIMARY KEY (digest, file_id)
);
SELECT digest FROM blob_refs GROUP BY digest HAVING count(*) = 0;   -- empty by construction; GC uses an anti-join against the blob inventory

Serving files: CDN, signed URLs, signed cookies, byte ranges Must-know ​

In plain words: Do not serve popular files from the bucket directly. Put a CDN in front: it keeps copies near users, takes the request load, and your origin is hit only on a miss. If the files are private, hand the CDN a signed URL or a signed cookie.

Common misunderstanding: "A presigned S3 URL works fine behind a CDN." Each presigned URL is unique (different signature, different expiry), so the CDN sees a different cache key every time unless you ignore the query string, which then strips the protection. Use CDN-native signing (CloudFront signed URLs or cookies, Cloudflare tokens) and let the CDN fetch from a private origin with its own credential (CloudFront Origin Access Control).

Definition: Delivery path: client → CDN edge → (miss) origin store. Signed URLs authorise one file; signed cookies authorise many ("use signed cookies when you don't want to change URLs, or when you want to provide access to multiple restricted files" — the CloudFront guide: the application sends three Set-Cookie headers, since a signed cookie needs three name-value pairs). Range requests (Range: bytes=..., 206 Partial Content, Accept-Ranges: bytes) let players seek and let download managers resume. HLS and DASH split video into short segments so the CDN caches each segment as an ordinary object.

 1  browser -> app          GET /videos/77            (authorise, then Set-Cookie: CloudFront-Policy, -Signature, -Key-Pair-Id)
 2  browser -> CDN edge     GET /v/77/seg-0042.ts     (cookies attached automatically)
 3  edge                    validate signature + policy; cache hit? -> serve
 4  edge    -> S3 (private) GET /v/77/seg-0042.ts     (miss; edge uses Origin Access Control)
 5  S3 -> edge -> browser   200 + Cache-Control: public, max-age=31536000, immutable
 6  browser -> edge         GET /v/77/movie.mp4  Range: bytes=52428800-    -> 206 Partial Content

Real scenario: Static assets under content-hashed names (app.3f9a1c.js) get Cache-Control: public, max-age=31536000, immutable, so a deploy never needs a cache purge. Paid video: one signed cookie per viewing session covers every segment. Private invoices: a two-minute signed URL or an app-checked 302 to a presigned URL. Large downloads: the CDN collapses concurrent misses so the origin sees one fetch.

NeedMechanismProduct
Public, cacheable, foreverContent-hashed key + Cache-Control: immutableAny CDN
One private file, short timeSigned URLCloudFront signed URL; S3 presigned URL (no CDN caching)
Many private files, one sessionSigned cookieCloudFront signed cookies
App must authorise every hitRedirect (302) to a short-lived URLLaravel temporaryUrl
Seeking and resumingRange and 206S3, CloudFront, NGINX (all support)

Fix / how to use it: CDN covers push vs pull and cache hierarchy; here the rule is: public and hashed behind a CDN, private behind signed cookies or an authorising app with short redirects, and never proxy big files through PHP workers.

Resumable uploads: tus and chunking Important ​

In plain words: On a bad connection a 500 MB upload will fail at 95%. A resumable protocol lets the client ask "how many bytes do you already have?" and continue from there.

Common misunderstanding: "Resumable means multipart." Multipart is a store-side feature for assembling parts into one object. Resumable is a client/server protocol that survives a closed tab or a changed network. They combine: a tus server can write each chunk to S3 as a multipart part.

Definition: The tus protocol (version 1.0.0) defines POST to create an upload (Upload-Length), HEAD to learn the offset (Upload-Offset in the response), and PATCH with Content-Type: application/offset+octet-stream and Upload-Offset to append bytes; servers announce capabilities with OPTIONS and Tus-Extension (for example creation, expiration, concatenation). The concatenation extension joins partial uploads, enabling parallel chunks. OCI registries have their own chunked blob upload (PATCH with Content-Range, then PUT ...?digest=). Browser uploads to S3 can use presigned UploadPart URLs per chunk.

 1  client -> server  POST /files   Upload-Length: 100  Tus-Resumable: 1.0.0       -> 201, Location: /files/24e5...
 2  client -> server  PATCH /files/24e5  Upload-Offset: 0   body: 70 bytes          -> 204, Upload-Offset: 70
 3  connection drops after 70 bytes were stored
 4  client -> server  HEAD /files/24e5                                              -> 200, Upload-Offset: 70
 5  client -> server  PATCH /files/24e5  Upload-Offset: 70  body: remaining 30      -> 204, Upload-Offset: 100 (complete)

Real scenario: Mobile video upload with Uppy or tus-js-client against tusd (writes to S3 using multipart) or a Laravel/Go tus server. A desktop sync client chunks files and uploads only chunks whose hash is new (chunking plus content addressing, as in restic or Dropbox-style sync).

ApproachResume afterServer stateBest for
Single presigned PUTNever (restart)NoneFiles under a few tens of MB
S3 multipart with presigned partsPart boundaryUpload id in your DBLarge files, browser to S3
tus (1.0.0)Any byte offsetUpload resource with offsetFlaky mobile networks, open protocol
Content-defined chunking + digestsChunkChunk indexSync, backup, dedup

Fix / how to use it: under ~100 MB use one presigned PUT; above, S3 multipart with presigned parts or tusd. Record the upload session in the database with an expiry, and lifecycle-abort the leftovers.

Metadata: database or object? Must-know ​

In plain words: The object store knows a key and a few labels. Everything you want to ask about files (whose is it, which project, is it deleted, show me the newest 20) belongs in your database.

Common misunderstanding: "I will put owner, status and title in object metadata and LIST to find them." Object metadata is returned by HEAD/GET of one key; you cannot query it. Finding objects by listing is slow and is billed per request (the S3 pricing page: LIST requests are charged at the same rate as PUT, COPY and POST, which is higher than GET).

Definition: System metadata is fixed (Content-Type, Content-Length, ETag, Last-Modified, Cache-Control, Content-Disposition). User metadata is x-amz-meta-* (a few KB total, immutable after write; changing it means a copy-in-place). Tags (key/value pairs) feed lifecycle and access policies. S3 Inventory writes a scheduled CSV or Parquet listing of a bucket for bulk analysis (not re-verified here).

DataPut it inWhy
Owner, permissions, status, display name, folder treeDatabase rowQueryable, transactional, indexable
Content-Type, Cache-Control, Content-DispositionObject system metadataNeeded at serve time by the store and CDN
Content hash, sizeBoth (object checksum, DB column)Verify on read, dedup lookups
Lifecycle bucket (retention=7y)Object tagLifecycle filters read tags
Full-text, thumbnails, derived dataSeparate objects + DB rowDerived artefacts have their own lifecycle

Fix / how to use it: the schema in sql/files.sql is the default: UUID id, generated object_key, status pending/ready/deleted, size, content type, SHA-256, owner. The key never contains personal data (keys appear in logs, URLs and events).

Encryption: SSE-S3, SSE-KMS, SSE-C and client side Important ​

In plain words: Encrypt the data on the provider's disks (server-side) or before it leaves your application (client-side). The difference is who holds the key and who can read the plaintext.

Common misunderstanding: "Default encryption means my data is protected from anyone with bucket access." Server-side encryption protects disks and backups from physical access. Any principal allowed GetObject receives plaintext. Access control, not encryption at rest, stops a leaked credential.

Definition: S3 now applies SSE-S3 (S3-managed keys, AES-256) by default to every new object upload (since January 5, 2023) at no extra cost. SSE-KMS uses an AWS KMS key you control: each use is an API call, can be audited in CloudTrail, honours key policies, and is rate limited by KMS quotas; S3 Bucket Keys reduce KMS calls (not re-verified here). DSSE-KMS applies two layers. SSE-C uses a key you send with each request (S3 does not store it; you must use HTTPS and keep the key yourself; "objects encrypted with SSE-C cannot be natively decrypted by AWS managed services"). Client-side encryption encrypts in your code (envelope encryption: a data key per object, wrapped by a master key) so the provider only stores ciphertext.

OptionWho holds the keyAuditTrade-off
SSE-S3AWS (S3-managed)LimitedDefault, zero effort, no per-request key control
SSE-KMSYou, via AWS KMS key policyCloudTrail per useKMS cost and quota; cross-account needs key policy
DSSE-KMSYou, two layersCloudTrailCompliance requirements
SSE-CYou, sent on every requestYoursCannot be used with CloudFront or most managed services
Client-sideYou (application, HSM, KMS)YoursProvider cannot index, scan or transform; key loss means data loss

Fix / how to use it: use SSE-KMS with a customer-managed key for regulated data and a bucket policy that denies unencrypted puts; use client-side encryption when the provider must not see plaintext at all. MinIO supports SSE-S3, SSE-KMS and SSE-C compatible modes with its own KMS (KES); Ceph RGW supports SSE-S3 and SSE-KMS through Vault or Barbican (not re-verified in detail). Key management itself is in Cryptography, TLS, PKI & Secrets.

Access control: IAM policy, bucket policy, public access block, ACLs Must-know ​

In plain words: Three layers decide who can touch an object: the caller's identity policy (IAM), the bucket's own policy, and a safety switch (Block Public Access) that overrides mistakes. ACLs are an old per-object mechanism you should leave off.

Common misunderstanding: "The bucket is private because I did not make it public." Public access happens through a bucket policy with Principal: "*", a public ACL, or an overly broad access point. The only reliable statement is: all four Block Public Access settings are on and the bucket policy allows only named principals.

Definition: An S3 request is allowed if an applicable policy allows it and none denies it (explicit deny wins). Identity-based IAM policies attach to users and roles; resource-based bucket policies attach to the bucket and can grant cross-account access and enforce conditions (aws:SecureTransport, s3:x-amz-server-side-encryption, aws:PrincipalOrgID). S3 Block Public Access has four settings: BlockPublicAcls, IgnorePublicAcls, BlockPublicPolicy, RestrictPublicBuckets. Object Ownership defaults to "Bucket owner enforced", so "all ACLs are disabled" and the bucket owner owns every object. Presigned URLs act with the permissions of the signer.

 1  request: role app-uploads, GetObject, key u/42/x.png
 2  evaluate: explicit Deny in any policy?                    no
 3  evaluate: IAM identity policy allows s3:GetObject?        yes (resource arn:aws:s3:::example-uploads/u/*)
 4  evaluate: Block Public Access / bucket policy conditions? SecureTransport = true -> ok
 5  result: allow

Real scenario: A bucket policy with aws:SecureTransport=false denied for all principals forces HTTPS. A CI role may write only under ci/. A data-lake bucket is shared with a partner account by a bucket policy plus a role in their account. A leaked public bucket is the classic breach; Block Public Access at the account level prevents it.

LayerScopeUse
IAM identity policyPrincipalWhat this role may do
Bucket policyBucketWho may do what here; cross-account; mandatory conditions
Block Public AccessAccount or bucketHard stop on public exposure
ACLObject or bucketLegacy; disabled by default through Bucket owner enforced
Access points, VPC endpoint policiesNetwork and per-appPer-application entry points
Presigned URLOne requestTemporary delegation

Fix / how to use it: see config/bucket-policy.json. Turn on all four Block Public Access settings at the account level, keep Object Ownership at Bucket owner enforced, and authorise inside the app before signing. Authorisation models are in Authorization Models.

Cost modelling: storage, requests, egress Must-know ​

In plain words: The bill has three parts: how many bytes you keep per month, how many requests you make, and how many bytes leave the provider. Object stores are cheap on the first, cheap-but-not-free on the second and expensive on the third.

Common misunderstanding: "Storage is cheap, so the bill is small." For hot, small-object, high-traffic workloads the request charges and egress dominate. A thumbnail service doing 10,000 GETs per second pays for 26 billion requests a month before it pays for a byte of storage; a video product pays mostly for egress.

Definition: Monthly cost is the sum of storage (GB-month by class), requests (PUT/COPY/POST/LIST are priced higher than GET/HEAD; lifecycle transitions and data retrievals also bill), data transfer out to the internet (zero to CloudFront on AWS), replication, management features, KMS calls and minimum-duration or minimum-size charges. AWS lists these components on the S3 pricing page; the unit prices below are assumptions for arithmetic only, not a quote.

 Assumed unit prices (illustrative, NOT AWS prices): storage s = 0.02 per GB-month,
 GET g = 0.0000004 per request, PUT p = 0.000005 per request, egress e = 0.08 per GB.
 Workload: 50 TB stored, 200 M GET/month, 5 M PUT/month, 20 TB/month served to users.
 1  storage  50,000 GB   x 0.02       = 1,000
 2  GET      200,000,000 x 0.0000004  =    80
 3  PUT        5,000,000 x 0.000005   =    25
 4  egress   20,000 GB   x 0.08       = 1,600     <- biggest line
 5  total                               2,705
 6  put a CDN in front: egress to the CDN is free on AWS, CDN egress is priced separately and cache hit ratio
    cuts origin GETs; revisit the line that dominates, not the one that is easiest to tune

Real scenario: A backup product tiers to Deep Archive and pays retrieval only on restores. A photo site stores 5 KB thumbnails: millions of tiny objects make lifecycle transitions expensive; they are bundled into larger objects or kept in Standard. A cross-region replica doubles storage and adds inter-region transfer. A data lake with a million small Parquet files pays for LIST and GET storms; compaction fixes it.

LeverReducesRisk
Lifecycle to colder classesStorageRetrieval fees, minimum durations
CDN in frontEgress, GETsCache invalidation cost, signed-URL design
Fewer, larger objects (compaction)Requests, per-object overheadRead amplification for small reads
Intelligent-TieringStorage with no retrieval feePer-object monitoring fee, ignores tiny objects
Abort incomplete multipartOrphan storageNone
Same-Region compute and VPC gateway endpointTransfer, NAT chargesCross-region designs lose it

Fix / how to use it: model the three terms in a spreadsheet before choosing class or region; use S3 Storage Lens and Storage Class Analysis to measure; set budgets and alarms. Back-of-envelope method: Capacity Estimation.

Data lakes, Parquet and Iceberg Good to know ​

In plain words: A data lake is object storage used as the shared disk for analytics. Files are columnar (Parquet), and a table format (Apache Iceberg) records which files belong to which table version so many engines can read and write consistently.

Common misunderstanding: "Object storage cannot do transactions, so lakes are append-only dumps." Table formats add atomic commits on top: Iceberg writes new data files and a new metadata snapshot, then swaps a pointer, so readers see either the old table or the new one.

Definition: Parquet is a columnar file format with row groups, column chunks and a footer holding statistics; engines read the footer with a range GET and then only the needed columns. The Iceberg specification describes tables as snapshots of manifest files that list data files; commits atomically replace the table metadata pointer. Other formats with the same role: Delta Lake and Apache Hudi. Query engines: Trino, Spark, DuckDB, Athena, Snowflake.

LayerRoleProduct examples
StorageImmutable filesS3, GCS, Azure Blob, MinIO, Ceph RGW
File formatColumnar dataParquet, ORC, Avro
Table formatSnapshots, schema evolution, commitsIceberg, Delta Lake, Hudi
CatalogWhere the current metadata pointer livesHive Metastore, AWS Glue, Nessie, REST catalog
EngineQueryTrino, Spark, Athena, DuckDB

Fix / how to use it: partition by what you filter on (date), compact small files, and read Big Data Architectures for lakehouse design. Do not build this for a CRUD app's uploads.

Other implementations: GCS, Azure Blob, MinIO, Ceph RGW Important ​

In plain words: Everyone speaks roughly "S3". Where they differ is the details: consistency, limits, auth, extra features.

Common misunderstanding: "S3-compatible means identical." The common verbs work; edge cases do not (presign options, conditional writes, Object Lock, versioning listing, event formats, multipart limits, bucket naming). Test your exact calls against the target.

Definition: Google Cloud Storage offers strong global consistency for object read-after-write, metadata update, delete and object listing, plus an S3-compatible XML API with HMAC keys. Azure Blob Storage has storage accounts, containers and blobs (block, append, page) and shared access signatures (SAS) as its presigned-URL equivalent. MinIO is an S3-compatible server using erasure sets (Reed-Solomon, parity such as EC:4) over local drives. Ceph RGW (RADOS Gateway) provides S3 and Swift APIs on top of a Ceph cluster, with multi-site replication between zones.

FeatureAWS S3Google Cloud StorageAzure Blob StorageMinIOCeph RGW
Signed temporary accessPresigned URL (SigV4)Signed URL (V4)SAS tokenPresigned URL (SigV4)Presigned URL (SigV4)
Strong consistencyYesYesYes (not re-verified here)Yes (single deployment)Within a zone
Object LockYesRetention policies, object holdsImmutable storage, legal holdYes (S3 API)Yes (S3 API, not re-verified)
Erasure codingInternalInternalInternalReed-Solomon setsPools (k+m)
Where it runsAWSGCPAzureAnywhereAnywhere

Fix / how to use it: keep the storage behind a small interface in your code (like the Go Backend and Laravel Storage disk) and run the same integration test against MinIO in CI as against the real provider before launch. The Go and Laravel snippets show the endpoint and path-style settings that MinIO needs.

Antipatterns Important ​

In plain words: The mistakes that show up again and again in reviews and in outages.

Common misunderstanding: "It works in development with ten files, so it works." Most of these are invisible at small scale.

Definition: A list, each with its fix.

AntipatternWhat goes wrongFix
Storing files in a database row (bytea, BLOB)Bloated WAL, backups and replicas; buffer cache churn; app memory per requestObject key in the row, bytes in the store
LIST to find a fileSlow, billed per page of 1,000 keys, grows with bucket sizeQuery the database; keep the key
User-supplied file name as keyCollisions, overwrites, path tricks (../), personal data in logsGenerate UUID or hash keys
Sequential or timestamp-prefixed keys at huge ratesConcentrates load on one prefix partition ("hot prefix"); S3 now scales prefixes automatically but a sudden spike can still see 503 Slow DownSpread keys with a hash prefix, retry with backoff
Proxying large downloads through the app serverPHP/Go workers tied up for slow clients302 to a presigned URL or CDN
Public bucket for convenienceData leakBlock Public Access + CDN with origin access control
Trusting client-declared type and sizeMalware, huge uploadsSigned constraints, server-side HEAD, content sniff
Presigned URLs with 7-day expiry, loggedBearer tokens in logs live for daysMinutes of life, never log full URLs
No lifecycle rule for incomplete multipart uploads and noncurrent versionsSilent growing billLifecycle rules from day one
Treating the bucket as a queue or lock servicePolling cost, no orderingUse a queue; use conditional writes only for coarse create-once
One object per tiny recordRequest cost, slow scansBatch into larger objects (compaction)
Overwriting objects in place that a CDN cachesStale content for TTLImmutable, content-hashed keys

Fix / how to use it: copy the table into your design review checklist. About hot prefixes: the S3 performance guidance says S3 supports at least 3,500 write and 11,000 read requests per second per partitioned prefix and scales automatically; historically AWS advised random key prefixes, which is no longer required for most workloads, but request-rate spikes on a fresh prefix still receive 503 Slow Down until partitioning catches up.

Mechanics ​

The exact knobs ​

KnobWhereMeaningTypical value
X-Amz-ExpiresPresigned URLLifetime in seconds300 to 900
X-Amz-SignedHeadersPresigned URLHeaders that must match exactlycontent-type;host
PartSize / ConcurrencyGo manager.UploaderMultipart part size and parallel parts16 MiB / 4 to 16
multipart_threshold, multipart_chunksizeAWS CLISwitch-over size and part size8 MB / 8 MB (CLI defaults, not re-verified)
Range: bytes=a-bGETInclusive byte rangeper read
Cache-ControlObject metadataCDN and browser TTLpublic, max-age=31536000, immutable for hashed keys
AbortIncompleteMultipartUpload.DaysAfterInitiationLifecycleClean orphan parts7
NoncurrentVersionExpiration.NoncurrentDaysLifecycleExpire old versions30
If-None-Match: *PutObjectCreate only if absentCAS and locks
use_path_style_endpoint / UsePathStyleLaravel / GoNeeded for MinIO and many S3-compatible storestrue
visibilityLaravel diskprivate or public object ACL behaviourprivate

Errors you will meet ​

CodeWhereMeaningAction
403 SignatureDoesNotMatchPresigned PUT/GETSigned header, region, clock or key differsSend exactly the signed headers; check clock skew and Region
403 AccessDeniedAnyPolicy, expired URL, Block Public AccessRead the policy evaluation; check expiry
403 RequestTimeTooSkewedSigned requestsClient clock too far from server time (15 minutes in AWS's documentation, not re-verified)Fix NTP
400 ExpiredToken / AccessDenied (expired)PresignedCredentials or URL expiredRequest a new URL
404 NoSuchKey / NoSuchUploadGET / multipartKey missing or upload abortedCheck key, re-initiate
409 OperationAborted, 409 BucketAlreadyOwnedByYouBucket opsConflicting concurrent changeRetry later
412 PreconditionFailedConditional PUTIf-None-Match or If-Match failedSomeone wrote first; read and decide
416 InvalidRangeRange GETRange outside the objectClamp to size
400 EntityTooSmall / EntityTooLargeMultipart or POST policyPart under 5 MiB or size outside policyFix part plan or the policy
503 SlowDownAnyRequest rate above current capacityExponential backoff with jitter (Timeouts, Retries & Jitter)
403 InvalidObjectStateGETObject is in an archive class, not restoredRestoreObject, wait

Anatomy of a presigned PUT ​

 1  PUT /uploads/u/42/ab/uuid
 2     ?X-Amz-Algorithm=AWS4-HMAC-SHA256
 3     &X-Amz-Credential=AKIDEXAMPLE%2F20261126%2Fus-east-1%2Fs3%2Faws4_request
 4     &X-Amz-Date=20261126T100000Z
 5     &X-Amz-Expires=600
 6     &X-Amz-SignedHeaders=content-type%3Bhost
 7     &X-Amz-Signature=<hex hmac>
 8  signing key = HMAC chain over (secret, date, region, service "s3", "aws4_request")
 9  string to sign = algorithm, date, scope, SHA-256 of the canonical request (method, path, sorted query, signed headers, "UNSIGNED-PAYLOAD")

Because the signature covers the canonical request, changing the key, the method, a signed header or the expiry invalidates it. Because it does not cover the holder, replay of the exact same request within the lifetime succeeds.

What a request costs in time ​

OperationFirst-byte latency (rough order of magnitude, inference)Throughput note
Local NVMe readtens of microsecondsGB/s
EBS volume readaround one millisecondProvisioned IOPS and MB/s
EFS / NFS reada few millisecondsPer-operation overhead dominates small files
S3 GET in the same Regiontens of millisecondsScale with parallel connections and range requests
S3 Glacier Flexible restoreminutes to hoursAsynchronous

These are orders of magnitude for planning, not benchmarks; measure your path. See Latency Budgets for how to spend them.

Go ​

Example: presigned URLs, multipart planning, range reads and a content-addressable store ​

The Go module academy/object-storage-file-systems (go 1.24, AWS SDK for Go v2) has four packages. s3cfg builds a client for AWS or MinIO (endpoint, path style). presign creates a presigned PUT with signed Content-Type, a presigned GET with a download name, and a POST policy with content-length-range; all of them run offline in tests because signing is local. multipart plans parts within the 10,000-part and 5 MiB to 5 GiB limits, uploads with manager.Uploader and reads byte ranges. cas is the SHA-256 content-addressable store with a pluggable backend, an in-memory backend for tests and an S3/MinIO backend that uses If-None-Match: *.

go
// Package s3cfg builds an S3 client that works against AWS S3 and against
// S3-compatible servers such as MinIO or Ceph RGW. It is configuration only.
package s3cfg

import (
	"context"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/credentials"
	"github.com/aws/aws-sdk-go-v2/service/s3"
)

// Config holds the few knobs that differ between AWS and a self-hosted store.
type Config struct {
	Region    string // "us-east-1" is accepted by MinIO
	Endpoint  string // empty for AWS; "http://127.0.0.1:9000" style for MinIO
	AccessKey string
	SecretKey string
	PathStyle bool // MinIO and most self-hosted stores need path-style addressing
}

// New returns a client. Static credentials keep the example self-contained;
// in production prefer the default credential chain (role, SSO, env).
func New(_ context.Context, c Config) *s3.Client {
	opts := s3.Options{
		Region:       c.Region,
		Credentials:  aws.NewCredentialsCache(credentials.NewStaticCredentialsProvider(c.AccessKey, c.SecretKey, "")),
		UsePathStyle: c.PathStyle,
	}
	if c.Endpoint != "" {
		opts.BaseEndpoint = aws.String(c.Endpoint)
	}
	return s3.New(opts)
}
go
// Package presign shows direct-to-S3 uploads and downloads with presigned URLs
// and with a POST policy. Presigning is a local computation: no network call
// is made, so everything here is testable offline.
package presign

import (
	"context"
	"errors"
	"fmt"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/s3"
)

// MaxExpiry is the longest lifetime we ever hand out. SigV4 allows 7 days for
// IAM-user credentials, but a role session shortens it further; keep it short.
const MaxExpiry = 15 * time.Minute

// Signer wraps the SDK presign client.
type Signer struct {
	Bucket string
	pc     *s3.PresignClient
}

func New(c *s3.Client, bucket string) *Signer {
	return &Signer{Bucket: bucket, pc: s3.NewPresignClient(c)}
}

func clamp(d time.Duration) (time.Duration, error) {
	if d <= 0 {
		return 0, errors.New("presign: expiry must be positive")
	}
	if d > MaxExpiry {
		return MaxExpiry, nil
	}
	return d, nil
}

// Upload is what the browser needs: a URL, the method, and the headers it MUST
// send because they are part of the signature.
type Upload struct {
	URL     string
	Method  string
	Headers map[string]string
}

// PutURL signs a PUT for one exact key, content type and size. Signing
// ContentType and ContentLength means S3 rejects a request that differs
// (403 SignatureDoesNotMatch).
func (s *Signer) PutURL(ctx context.Context, key, contentType string, size int64, ttl time.Duration) (Upload, error) {
	ttl, err := clamp(ttl)
	if err != nil {
		return Upload{}, err
	}
	if size <= 0 {
		return Upload{}, errors.New("presign: size must be positive")
	}
	req, err := s.pc.PresignPutObject(ctx, &s3.PutObjectInput{
		Bucket:        aws.String(s.Bucket),
		Key:           aws.String(key),
		ContentType:   aws.String(contentType),
		ContentLength: aws.Int64(size),
	}, s3.WithPresignExpires(ttl))
	if err != nil {
		return Upload{}, fmt.Errorf("presign put: %w", err)
	}
	h := map[string]string{}
	for k, v := range req.SignedHeader {
		if len(v) > 0 {
			h[k] = v[0]
		}
	}
	return Upload{URL: req.URL, Method: req.Method, Headers: h}, nil
}

// GetURL signs a download. The response-content-disposition override makes the
// browser save the file under a friendly name without touching object metadata.
func (s *Signer) GetURL(ctx context.Context, key, filename string, ttl time.Duration) (string, error) {
	ttl, err := clamp(ttl)
	if err != nil {
		return "", err
	}
	req, err := s.pc.PresignGetObject(ctx, &s3.GetObjectInput{
		Bucket:                     aws.String(s.Bucket),
		Key:                        aws.String(key),
		ResponseContentDisposition: aws.String(fmt.Sprintf("attachment; filename=%q", filename)),
	}, s3.WithPresignExpires(ttl))
	if err != nil {
		return "", fmt.Errorf("presign get: %w", err)
	}
	return req.URL, nil
}

// Form is a browser-ready POST policy: POST the Values as multipart fields,
// then the file as the LAST field.
type Form struct {
	URL    string
	Values map[string]string
}

// PostForm signs a POST policy that fixes the key prefix, the size range and
// the content type. Unlike a presigned PUT URL, a policy can express a RANGE of
// sizes (content-length-range) and a prefix (starts-with).
func (s *Signer) PostForm(ctx context.Context, key, contentType string, minBytes, maxBytes int64, ttl time.Duration) (Form, error) {
	ttl, err := clamp(ttl)
	if err != nil {
		return Form{}, err
	}
	p, err := s.pc.PresignPostObject(ctx, &s3.PutObjectInput{
		Bucket:      aws.String(s.Bucket),
		Key:         aws.String(key),
		ContentType: aws.String(contentType),
	}, func(o *s3.PresignPostOptions) {
		o.Expires = ttl
		o.Conditions = []any{
			[]any{"content-length-range", minBytes, maxBytes},
			map[string]string{"Content-Type": contentType},
		}
	})
	if err != nil {
		return Form{}, fmt.Errorf("presign post: %w", err)
	}
	return Form{URL: p.URL, Values: p.Values}, nil
}
go
package presign

import (
	"context"
	"encoding/base64"
	"net/url"
	"strings"
	"testing"
	"time"

	"academy/object-storage-file-systems/s3cfg"
)

func newSigner(t *testing.T) *Signer {
	t.Helper()
	c := s3cfg.New(context.Background(), s3cfg.Config{
		Region: "us-east-1", Endpoint: "http://minio.example.test:9000",
		AccessKey: "AKIDEXAMPLE", SecretKey: "secret-example", PathStyle: true,
	})
	return New(c, "uploads")
}

func TestPutURLSignsContentTypeAndLength(t *testing.T) {
	up, err := newSigner(t).PutURL(context.Background(), "u/42/a.png", "image/png", 1234, 5*time.Minute)
	if err != nil {
		t.Fatal(err)
	}
	u, err := url.Parse(up.URL)
	if err != nil {
		t.Fatal(err)
	}
	q := u.Query()
	if q.Get("X-Amz-Expires") != "300" {
		t.Fatalf("expires = %q, want 300", q.Get("X-Amz-Expires"))
	}
	signed := q.Get("X-Amz-SignedHeaders")
	for _, h := range []string{"content-type", "host"} {
		if !strings.Contains(signed, h) {
			t.Fatalf("signed headers %q miss %s", signed, h)
		}
	}
	if up.Method != "PUT" || u.Path != "/uploads/u/42/a.png" {
		t.Fatalf("method %s path %s", up.Method, u.Path)
	}
}

func TestExpiryIsClamped(t *testing.T) {
	up, err := newSigner(t).PutURL(context.Background(), "k", "text/plain", 1, 7*24*time.Hour)
	if err != nil {
		t.Fatal(err)
	}
	u, _ := url.Parse(up.URL)
	if got := u.Query().Get("X-Amz-Expires"); got != "900" {
		t.Fatalf("expires = %s, want 900 (MaxExpiry)", got)
	}
	if _, err := newSigner(t).PutURL(context.Background(), "k", "text/plain", 1, 0); err == nil {
		t.Fatal("zero expiry must be rejected")
	}
}

func TestGetURLCarriesDisposition(t *testing.T) {
	raw, err := newSigner(t).GetURL(context.Background(), "r/report.pdf", "Q3 report.pdf", time.Minute)
	if err != nil {
		t.Fatal(err)
	}
	u, _ := url.Parse(raw)
	if !strings.Contains(u.Query().Get("response-content-disposition"), "Q3 report.pdf") {
		t.Fatalf("missing disposition in %s", raw)
	}
	if u.Query().Get("X-Amz-Signature") == "" {
		t.Fatal("no signature")
	}
}

func TestPostPolicyHasSizeRange(t *testing.T) {
	f, err := newSigner(t).PostForm(context.Background(), "u/42/a.png", "image/png", 1, 5<<20, time.Minute)
	if err != nil {
		t.Fatal(err)
	}
	pol, ok := f.Values["policy"]
	if !ok {
		t.Fatalf("no policy field in %v", f.Values)
	}
	raw, err := base64.StdEncoding.DecodeString(pol)
	if err != nil {
		t.Fatal(err)
	}
	if !strings.Contains(string(raw), "content-length-range") {
		t.Fatalf("policy lacks size range: %s", raw)
	}
}
go
// Package multipart holds the arithmetic and the SDK calls for large uploads
// and for byte-range reads.
package multipart

import (
	"context"
	"errors"
	"fmt"
	"io"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
	"github.com/aws/aws-sdk-go-v2/service/s3"
)

// S3 limits (Amazon S3 User Guide, "Amazon S3 multipart upload limits").
const (
	MinPartSize = 5 << 20 // 5 MiB, except the last part
	MaxPartSize = 5 << 30 // 5 GiB
	MaxParts    = 10000
)

// Part is one slice of the object: number is 1-based, [Start, End) in bytes.
type Part struct {
	Number     int
	Start, End int64
}

// Plan splits size bytes into parts of at least want bytes, growing the part
// size when needed so the count stays within MaxParts.
func Plan(size, want int64) ([]Part, error) {
	if size <= 0 {
		return nil, errors.New("multipart: size must be positive")
	}
	ps := want
	if ps < MinPartSize {
		ps = MinPartSize
	}
	if need := (size + MaxParts - 1) / MaxParts; need > ps {
		ps = need
	}
	if ps > MaxPartSize {
		return nil, fmt.Errorf("multipart: %d bytes needs parts above 5 GiB", size)
	}
	var parts []Part
	for off, n := int64(0), 1; off < size; off, n = off+ps, n+1 {
		end := off + ps
		if end > size {
			end = size
		}
		parts = append(parts, Part{Number: n, Start: off, End: end})
	}
	return parts, nil
}

// Upload streams r to S3 with the SDK upload manager: it switches to a
// multipart upload by itself, uploads parts concurrently and aborts the upload
// on error unless LeavePartsOnError is set.
func Upload(ctx context.Context, c *s3.Client, bucket, key string, r io.Reader) error {
	u := manager.NewUploader(c, func(u *manager.Uploader) {
		u.PartSize = 16 << 20
		u.Concurrency = 4
	})
	_, err := u.Upload(ctx, &s3.PutObjectInput{Bucket: aws.String(bucket), Key: aws.String(key), Body: r})
	return err
}

// RangeHeader formats an inclusive HTTP Range value for [start, end).
func RangeHeader(start, end int64) string {
	return fmt.Sprintf("bytes=%d-%d", start, end-1)
}

// ReadRange fetches only [start, end) with a range GET (HTTP 206).
func ReadRange(ctx context.Context, c *s3.Client, bucket, key string, start, end int64) ([]byte, error) {
	out, err := c.GetObject(ctx, &s3.GetObjectInput{
		Bucket: aws.String(bucket), Key: aws.String(key), Range: aws.String(RangeHeader(start, end)),
	})
	if err != nil {
		return nil, err
	}
	defer out.Body.Close()
	return io.ReadAll(out.Body)
}
go
package multipart

import "testing"

func TestPlanSmall(t *testing.T) {
	p, err := Plan(12<<20, 5<<20)
	if err != nil {
		t.Fatal(err)
	}
	if len(p) != 3 || p[2].End != 12<<20 || p[2].End-p[2].Start != 2<<20 {
		t.Fatalf("unexpected plan %+v", p)
	}
}

func TestPlanGrowsPartSizeToStayUnderMaxParts(t *testing.T) {
	size := int64(1) << 40 // 1 TiB
	p, err := Plan(size, MinPartSize)
	if err != nil {
		t.Fatal(err)
	}
	if len(p) > MaxParts {
		t.Fatalf("%d parts exceeds %d", len(p), MaxParts)
	}
	var sum int64
	for i, x := range p {
		sum += x.End - x.Start
		if x.Number != i+1 {
			t.Fatalf("part %d numbered %d", i, x.Number)
		}
	}
	if sum != size {
		t.Fatalf("parts cover %d of %d", sum, size)
	}
}

func TestPlanRejectsImpossible(t *testing.T) {
	if _, err := Plan(MaxParts*int64(MaxPartSize)+1, MinPartSize); err == nil {
		t.Fatal("expected error above 10000 x 5 GiB")
	}
	if _, err := Plan(0, MinPartSize); err == nil {
		t.Fatal("expected error for zero size")
	}
}

func TestRangeHeaderIsInclusive(t *testing.T) {
	if got := RangeHeader(0, 100); got != "bytes=0-99" {
		t.Fatal(got)
	}
}
go
// Package cas is a content-addressable store: the key of a blob is the SHA-256
// of its bytes. Same bytes, same key, stored once; a blob can never change
// under its key; every read can be verified.
package cas

import (
	"bytes"
	"context"
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"fmt"
	"io"
)

// ErrNotFound is returned by a Backend for a missing key.
var ErrNotFound = errors.New("cas: not found")

// ErrCorrupt means the bytes read back do not hash to the key.
var ErrCorrupt = errors.New("cas: content does not match digest")

// Backend is the tiny object-store surface the CAS needs. An S3 or MinIO
// implementation is in s3backend.go; Memory is used by tests.
type Backend interface {
	Exists(ctx context.Context, key string) (bool, error)
	Put(ctx context.Context, key string, data []byte) error
	Get(ctx context.Context, key string) ([]byte, error)
}

// Store maps digests to blobs on top of a Backend.
type Store struct {
	B Backend
}

// Digest is "sha256:<hex>", the same notation OCI registries use.
type Digest string

func sum(b []byte) Digest {
	h := sha256.Sum256(b)
	return Digest("sha256:" + hex.EncodeToString(h[:]))
}

// Key shards the object key by the first two hex bytes so that keys spread over
// prefixes: blobs/sha256/ab/cd/abcd....
func Key(d Digest) string {
	hex := string(d)[len("sha256:"):]
	return fmt.Sprintf("blobs/sha256/%s/%s/%s", hex[0:2], hex[2:4], hex)
}

// Put stores the bytes and returns their digest. If the blob already exists it
// is NOT uploaded again (deduplication) and stored is false.
func (s *Store) Put(ctx context.Context, r io.Reader) (d Digest, stored bool, err error) {
	data, err := io.ReadAll(r) // a real service would spool large input to disk
	if err != nil {
		return "", false, err
	}
	d = sum(data)
	ok, err := s.B.Exists(ctx, Key(d))
	if err != nil {
		return "", false, err
	}
	if ok {
		return d, false, nil
	}
	if err := s.B.Put(ctx, Key(d), data); err != nil {
		return "", false, err
	}
	return d, true, nil
}

// Get returns the bytes and re-hashes them: a flipped bit anywhere between the
// disks and this process becomes ErrCorrupt instead of silent bad data.
func (s *Store) Get(ctx context.Context, d Digest) ([]byte, error) {
	data, err := s.B.Get(ctx, Key(d))
	if err != nil {
		return nil, err
	}
	if sum(data) != d {
		return nil, ErrCorrupt
	}
	return data, nil
}

// Memory is an in-process Backend for tests and local runs.
type Memory struct {
	M    map[string][]byte
	Puts int
}

func NewMemory() *Memory { return &Memory{M: map[string][]byte{}} }

func (m *Memory) Exists(_ context.Context, k string) (bool, error) { _, ok := m.M[k]; return ok, nil }

func (m *Memory) Put(_ context.Context, k string, b []byte) error {
	m.Puts++
	m.M[k] = bytes.Clone(b)
	return nil
}

func (m *Memory) Get(_ context.Context, k string) ([]byte, error) {
	b, ok := m.M[k]
	if !ok {
		return nil, ErrNotFound
	}
	return bytes.Clone(b), nil
}
go
package cas

import (
	"bytes"
	"context"
	"errors"
	"io"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
)

// S3 implements Backend on AWS S3 or any S3-compatible server (MinIO config in
// package s3cfg). Not exercised by unit tests: it needs a server.
type S3 struct {
	C      *s3.Client
	Bucket string
}

func (b S3) Exists(ctx context.Context, key string) (bool, error) {
	_, err := b.C.HeadObject(ctx, &s3.HeadObjectInput{Bucket: aws.String(b.Bucket), Key: aws.String(key)})
	var nf *types.NotFound
	if errors.As(err, &nf) {
		return false, nil
	}
	return err == nil, err
}

// Put uses If-None-Match: * so two writers racing on the same digest cannot
// overwrite each other (the loser gets 412, which is fine: same bytes anyway).
func (b S3) Put(ctx context.Context, key string, data []byte) error {
	_, err := b.C.PutObject(ctx, &s3.PutObjectInput{
		Bucket: aws.String(b.Bucket), Key: aws.String(key), Body: bytes.NewReader(data),
		IfNoneMatch: aws.String("*"),
	})
	return err
}

func (b S3) Get(ctx context.Context, key string) ([]byte, error) {
	out, err := b.C.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(b.Bucket), Key: aws.String(key)})
	var nk *types.NoSuchKey
	if errors.As(err, &nk) {
		return nil, ErrNotFound
	}
	if err != nil {
		return nil, err
	}
	defer out.Body.Close()
	return io.ReadAll(out.Body)
}
go
package cas

import (
	"bytes"
	"context"
	"errors"
	"strings"
	"testing"
)

func TestKnownDigest(t *testing.T) {
	// SHA-256 of the empty string is a published constant.
	want := Digest("sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
	if got := sum(nil); got != want {
		t.Fatalf("got %s", got)
	}
}

func TestDedup(t *testing.T) {
	m := NewMemory()
	s := Store{B: m}
	ctx := context.Background()
	d1, stored1, err := s.Put(ctx, strings.NewReader("hello"))
	if err != nil || !stored1 {
		t.Fatal(err, stored1)
	}
	d2, stored2, err := s.Put(ctx, strings.NewReader("hello"))
	if err != nil || stored2 || d1 != d2 {
		t.Fatalf("second put should dedup: %v %v %s %s", err, stored2, d1, d2)
	}
	if m.Puts != 1 {
		t.Fatalf("backend saw %d puts, want 1", m.Puts)
	}
}

func TestRoundTrip(t *testing.T) {
	s := Store{B: NewMemory()}
	ctx := context.Background()
	d, _, _ := s.Put(ctx, bytes.NewReader([]byte("payload")))
	got, err := s.Get(ctx, d)
	if err != nil || string(got) != "payload" {
		t.Fatal(err, string(got))
	}
}

func TestCorruptionDetected(t *testing.T) {
	m := NewMemory()
	s := Store{B: m}
	ctx := context.Background()
	d, _, _ := s.Put(ctx, strings.NewReader("payload"))
	m.M[Key(d)][0] ^= 0x01 // flip one bit on "disk"
	if _, err := s.Get(ctx, d); !errors.Is(err, ErrCorrupt) {
		t.Fatalf("want ErrCorrupt, got %v", err)
	}
}

func TestMissing(t *testing.T) {
	s := Store{B: NewMemory()}
	if _, err := s.Get(context.Background(), sum([]byte("nope"))); !errors.Is(err, ErrNotFound) {
		t.Fatal(err)
	}
}

func TestKeyIsSharded(t *testing.T) {
	k := Key(sum([]byte("x")))
	if !strings.HasPrefix(k, "blobs/sha256/2d/71/2d711642b726b04401627ca9fbac32f5c8530fb1903cc4db02258717921a4881") {
		t.Fatal(k)
	}
}

The Go angle ​

  • Presigning is local: s3.NewPresignClient(client) signs with the client's credentials and Region and makes no network call, so you can unit-test URLs (expiry, signed headers) without a server. PresignPutObject, PresignGetObject, PresignUploadPart and PresignPostObject are the four entry points; the options function s3.WithPresignExpires sets the lifetime.
  • To make the store enforce a header, it must be part of the PutObjectInput you sign; the returned PresignedHTTPRequest has SignedHeader, and the browser must send those headers verbatim.
  • manager.Uploader (package feature/s3/manager) buffers PartSize bytes per part and uploads Concurrency parts at once; memory use is roughly PartSize x Concurrency. It aborts the multipart upload on failure unless LeavePartsOnError is true. MaxUploadParts defaults to 10,000.
  • Reading: GetObject returns a stream; always defer out.Body.Close() and prefer io.Copy to a destination over io.ReadAll for big objects. Range reads use Range: bytes=a-b.
  • Errors are typed: use errors.As with *types.NoSuchKey, *types.NotFound (HEAD) and smithy.APIError (ErrorCode() for SlowDown, PreconditionFailed). The SDK's retryer already backs off on 503; set RetryMaxAttempts deliberately.
  • Credentials: use the default chain (config.LoadDefaultConfig) in production. The s3cfg helper uses static keys to stay self-contained; for MinIO set BaseEndpoint and UsePathStyle.
  • crypto/sha256 plus io.TeeReader hashes while streaming; cas.Put reads into memory for clarity, and a production version would spool to a temporary file to bound memory. Always compare the digest on read.
  • If-None-Match: * on PutObject is the SDK field IfNoneMatch; check your target (AWS S3 supports it; MinIO and Ceph versions differ) before relying on it.

Laravel ​

Example: S3 and MinIO disks, direct uploads, authorised downloads, streaming ​

Laravel 13's Storage facade is a Flysystem wrapper. The uploads disk is a private S3 bucket; minio is the same driver pointed at a local server. AttachmentStore is the server-side path (putFileAs streams the file, metadata goes to the files table). DirectUploadController implements the two-call direct upload with temporaryUploadUrl, then confirms with exists and size. DownloadController shows both patterns: a 302 to a short-lived temporaryUrl with response header overrides, and Storage::download when bytes must pass through PHP.

php
<?php

// config/filesystems.php (excerpt). One disk for AWS S3 and one for MinIO.
return [
    'default' => env('FILESYSTEM_DISK', 'local'),

    'disks' => [
        // Private bucket: never public. Access goes through temporaryUrl()
        // and temporaryUploadUrl().
        'uploads' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
            'bucket' => env('AWS_BUCKET'),
            'url' => env('AWS_URL'),
            'endpoint' => env('AWS_ENDPOINT'),             // empty on AWS
            'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
            'visibility' => 'private',
            'throw' => true,                               // do not swallow S3 errors
        ],

        // Same driver pointed at a MinIO server (local development, CI).
        'minio' => [
            'driver' => 's3',
            'key' => 'minioadmin',
            'secret' => 'minioadmin',
            'region' => 'us-east-1',
            'bucket' => 'uploads',
            'endpoint' => 'http://127.0.0.1:9000',
            'use_path_style_endpoint' => true,
            'throw' => true,
        ],
    ],
];
php
<?php

namespace App\Services;

use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

/**
 * Server-side upload path: stream the file to the object store, keep the
 * metadata in the database. The object key is generated, never user input.
 */
final class AttachmentStore
{
    public function __construct(private readonly string $disk = 'uploads')
    {
    }

    /** @return array{id:string,key:string,sha256:string} */
    public function store(UploadedFile $file, int $ownerId): array
    {
        $id = (string) Str::uuid();
        // Hash-prefixed layout spreads keys over prefixes and survives renames.
        $key = sprintf('u/%d/%s/%s', $ownerId, substr($id, 0, 2), $id);

        // putFileAs streams the file; it does not load it into memory.
        Storage::disk($this->disk)->putFileAs(
            dirname($key),
            $file,
            basename($key),
            ['visibility' => 'private', 'ContentType' => $file->getMimeType()],
        );

        $sha256 = hash_file('sha256', $file->getRealPath());

        DB::table('files')->insert([
            'id' => $id,
            'owner_id' => $ownerId,
            'object_key' => $key,
            'original_name' => $file->getClientOriginalName(),
            'content_type' => $file->getMimeType(),
            'size_bytes' => $file->getSize(),
            'sha256' => $sha256,
            'status' => 'ready',
            'created_at' => now(),
        ]);

        return ['id' => $id, 'key' => $key, 'sha256' => $sha256];
    }
}
php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

/**
 * Direct-to-S3 upload in two calls:
 *   1. POST /uploads         -> row in `files` with status "pending" + a presigned PUT
 *   2. POST /uploads/{id}/done -> HEAD the object, check size, flip to "ready"
 */
final class DirectUploadController
{
    private const MAX_BYTES = 50 * 1024 * 1024;

    public function create(Request $request): JsonResponse
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'content_type' => ['required', 'in:image/png,image/jpeg,application/pdf'],
            'size' => ['required', 'integer', 'min:1', 'max:'.self::MAX_BYTES],
        ]);

        $id = (string) Str::uuid();
        $key = sprintf('u/%d/%s/%s', $request->user()->id, substr($id, 0, 2), $id);

        DB::table('files')->insert([
            'id' => $id,
            'owner_id' => $request->user()->id,
            'object_key' => $key,
            'original_name' => $data['name'],
            'content_type' => $data['content_type'],
            'size_bytes' => $data['size'],
            'status' => 'pending',
            'created_at' => now(),
        ]);

        // Returns ['url' => ..., 'headers' => [...]]; the browser must send
        // exactly those headers with its PUT.
        ['url' => $url, 'headers' => $headers] = Storage::disk('uploads')->temporaryUploadUrl(
            $key,
            now()->plus(minutes: 10),
            ['ContentType' => $data['content_type']],
        );

        return response()->json(['id' => $id, 'url' => $url, 'headers' => $headers], 201);
    }

    public function done(Request $request, string $id): JsonResponse
    {
        $row = DB::table('files')->where('id', $id)->where('owner_id', $request->user()->id)->first();
        abort_if($row === null, 404);

        $disk = Storage::disk('uploads');
        // The browser says "done"; the store is the source of truth.
        abort_unless($disk->exists($row->object_key), 409, 'object not uploaded');
        abort_unless($disk->size($row->object_key) === (int) $row->size_bytes, 422, 'size mismatch');

        DB::table('files')->where('id', $id)->update(['status' => 'ready']);

        return response()->json(['id' => $id, 'status' => 'ready']);
    }
}
php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;

final class DownloadController
{
    /** Authorize in PHP, then let S3 serve the bytes: 302 to a short-lived URL. */
    public function redirect(Request $request, string $id): RedirectResponse
    {
        $row = $this->authorizedRow($request, $id);

        $url = Storage::disk('uploads')->temporaryUrl(
            $row->object_key,
            now()->plus(minutes: 2),
            [
                'ResponseContentType' => $row->content_type,
                'ResponseContentDisposition' => 'attachment; filename="'.addslashes($row->original_name).'"',
            ],
        );

        return redirect()->away($url);
    }

    /** When the bytes must pass through PHP (watermarking, no public S3 endpoint). */
    public function stream(Request $request, string $id): StreamedResponse
    {
        $row = $this->authorizedRow($request, $id);

        // Storage::download streams from the object store; it does not buffer the body.
        return Storage::disk('uploads')->download($row->object_key, $row->original_name, [
            'Content-Type' => $row->content_type,
        ]);
    }

    private function authorizedRow(Request $request, string $id): object
    {
        $row = DB::table('files')->where('id', $id)->where('status', 'ready')->first();
        abort_if($row === null, 404);
        abort_unless((int) $row->owner_id === $request->user()->id, 403);

        return $row;
    }
}
php
<?php

use App\Services\AttachmentStore;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

// Pest test: Storage::fake swaps the S3 disk for a temporary local one.
test('store writes the object and one metadata row', function () {
    Storage::fake('uploads');

    $file = UploadedFile::fake()->create('report.pdf', 64, 'application/pdf');
    $out = (new AttachmentStore('uploads'))->store($file, 7);

    Storage::disk('uploads')->assertExists($out['key']);
    expect($out['key'])->toStartWith('u/7/');
    expect(DB::table('files')->where('id', $out['id'])->value('status'))->toBe('ready');
});
sql
-- Metadata lives in the database; bytes live in the object store.
-- The database row is what you query, join, authorize and paginate on.
CREATE TABLE files (
    id            uuid        PRIMARY KEY,
    owner_id      bigint      NOT NULL,
    object_key    text        NOT NULL UNIQUE,
    original_name text        NOT NULL,
    content_type  text        NOT NULL,
    size_bytes    bigint      NOT NULL CHECK (size_bytes > 0),
    sha256        char(64),
    status        text        NOT NULL CHECK (status IN ('pending', 'ready', 'deleted')),
    created_at    timestamptz NOT NULL DEFAULT now()
);

-- "Show me my files": an index, not a LIST over the bucket.
CREATE INDEX files_owner_created ON files (owner_id, created_at DESC) WHERE status = 'ready';

-- Dedup lookup for content-addressed uploads.
CREATE INDEX files_sha256 ON files (sha256) WHERE sha256 IS NOT NULL;

-- Orphan sweep: uploads that were presigned but never confirmed.
SELECT id, object_key
FROM files
WHERE status = 'pending' AND created_at < now() - interval '1 day';

The Laravel angle ​

  • Install league/flysystem-aws-s3-v3 "^3.0" (the 13.x docs: composer require league/flysystem-aws-s3-v3 "^3.0" --with-all-dependencies). Configure key, secret, region, bucket, url, endpoint; for MinIO and other S3-compatible stores set endpoint and use_path_style_endpoint => true.
  • Storage::temporaryUrl($path, now()->plus(minutes: 5)) returns a presigned GET for the s3 driver (and a signed route for the local driver). The third argument takes response overrides such as ResponseContentType and ResponseContentDisposition.
  • Storage::temporaryUploadUrl($path, $expiration) returns ['url' => ..., 'headers' => [...]]; the client must send those headers. It exists for the s3 driver only.
  • putFile and putFileAs accept an UploadedFile or Illuminate\Http\File and stream it; do not file_get_contents a large upload into memory.
  • Visibility: public and private map to the object's ACL for drivers that support it; with Bucket owner enforced ACLs are disabled, so rely on bucket policy and presigned URLs instead of per-object public ACLs. getVisibility and setVisibility exist; Storage::put($path, $contents, 'public') sets it on write.
  • Storage::download($path, $name, $headers) streams from the disk to the client; Storage::fake('uploads') swaps the disk for a temporary local one in tests (assertExists, assertMissing).
  • Set 'throw' => true on the disk so failures raise exceptions instead of returning false.
  • Authorise before you sign: policies and gates decide who may call temporaryUrl. Never expose the raw key pattern to users.
  • Laravel has no first-party POST-policy or multipart-from-browser helper: use the AWS SDK for PHP (CreateMultipartUpload, presigned UploadPart) or a tus server for large browser uploads.

Solving the classic problems ​

Users upload through the app and PHP workers or pods run out ​

SolutionHowAdvantageCost or limit
Presigned PUTApp signs, browser PUTs to the storeApp bandwidth and workers freedNeed pending row and confirm step
Presigned multipart partsApp signs each UploadPartResume per part, large filesMore round trips; store upload id
tus servertusd or similar writes to S3Resume at any byteAnother service to run

Use the flow in Presigned URLs; both language snippets implement it.

Uploads that were presigned and never completed ​

A browser may abandon an upload after the app inserted the row, or complete it without telling the app. Two sweepers handle both: a SQL job marks pending rows older than a day as deleted and issues DeleteObject (idempotent), and an S3 Event Notification (s3:ObjectCreated:* to SQS or EventBridge) flips rows to ready even when the browser never called /done. Because notifications are at-least-once, the update must be idempotent (UPDATE ... WHERE status = 'pending'). Add a lifecycle AbortIncompleteMultipartUpload rule for multipart leftovers.

A hot private download link leaks ​

Rotate by design: two-minute expiry, Content-Disposition: attachment, authorise on every issue, never log query strings, and prefer 302 redirects (the URL appears only in the browser's navigation, not in your HTML). If a link leaked, you cannot revoke it individually: delete or rename the object (or rotate the signer's credentials, which invalidates every outstanding URL signed with them).

Videos stutter or seek slowly ​

Serve through a CDN, keep Accept-Ranges: bytes, use fragmented MP4 or HLS segments of 2 to 10 seconds so each is a small cacheable object, set Cache-Control: immutable on segments and short TTL on playlists. Signed cookies cover every segment of a session.

Duplicate files waste storage ​

Hash on the client (Web Crypto SHA-256) or on the server, ask the app "do you have this digest?", and skip the upload if yes. Keep per-user ownership rows in the database that point to one blob. Garbage-collect a blob only when its reference count is zero and it is older than a grace period; never trust a client-claimed digest without verifying possession (for example by requiring a challenge: hash of a random byte range).

Accidental delete or ransomware ​

Versioning plus noncurrent-version expiry covers overwrite and delete; Object Lock (compliance) plus replication to a separate account covers a compromised account. Test restore: list versions, remove the delete marker, copy a noncurrent version back.

The bill doubled ​

Find the dominant line (Cost Explorer by usage type): egress points to missing CDN or cross-region reads; request charges point to chatty small-object access or listings; storage points to missing lifecycle, versioning bloat or abandoned multipart uploads. Fix the biggest line first.

Choosing ​

WorkloadStorageExtra techniqueReason
User uploads (avatars, attachments)Object store, private bucketPresigned PUT, DB metadata, CDN for public derivativesDurable, cheap, bypasses app servers
Database data directoryBlock volumeSnapshots, replicationNeeds low latency in-place writes
Shared uploads/ for a legacy CMSEFS / NFSMigrate to objects when possiblePOSIX semantics required
Backups, archives, complianceObject store, cold classObject Lock, lifecycle, CRR to another accountCheapest durable, immutable
Analytics over logs and eventsObject store with Parquet and IcebergCompaction, partitioningEngines scan ranges in parallel
Static website and downloadsObject store + CDNHashed keys, immutableEdge serves; origin sees misses
Hadoop/Spark with data localityHDFS or object store with S3AErasure codingLocality vs elasticity
ML training dataObject store + local NVMe cache, or a parallel FS (Lustre) for HPCPrefetch, range readsThroughput vs cost
Container imagesRegistry on an object storeContent-addressed layersDedup and verification
Small structured recordsDatabase, not objectsn/aQueries, transactions

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

Start with the local disk behind Storage::disk('local') and a files table. The interface is the same as the later S3 disk, so code does not change. A single server is fine until you add a second one or a deploy that wipes the disk. The first correct move is to switch the default disk to an S3 bucket (private) and keep files as the source of truth for names and owners.

Modular monolith: boundaries without the network ​

Give each module its own key prefix (billing/, media/, exports/), its own IAM policy limited to that prefix, and its own lifecycle rules. Modules refer to files by file_id, never by key; only a small FileStorage module knows keys and signing. This is the seam that later becomes a service, and it is where quotas, scanning and audit live.

Microservices: every arrow is a decision ​

 1  mobile  -> upload-svc   POST /uploads {type,size}      authz via JWT, rate limited
 2  upload-svc -> files-db  INSERT pending
 3  upload-svc -> mobile    presigned PUT
 4  mobile  -> object store PUT bytes (direct)
 5  object store -> queue   s3:ObjectCreated event          at-least-once
 6  scan-svc  <- queue      virus scan, content sniff, thumbnail  (idempotent)
 7  scan-svc -> object store PUT derived/thumbnail.jpg      (new key)
 8  scan-svc -> files-db    UPDATE status='ready' WHERE status='pending'
 9  feed-svc <- queue       file.ready integration event (via outbox)

Services share the object store but not each other's prefixes. The event from the store is not your domain event: translate it with the outbox pattern so the database and the broker agree. Cross-service reads use short-lived URLs minted by the owning service, not shared credentials.

Distributed data: replicas, caches, regions ​

Within a Region S3 is strongly consistent; across Regions replication is asynchronous, so a reader in the second Region may not yet see an object the first Region acknowledged. Route reads for fresh uploads to the origin Region or wait for a replication-complete event (S3 can emit replication events). CDN caches add a third copy: purge or use immutable keys. Multi-region active/active uploads need a conflict story: with content-addressed keys there is none (the same bytes produce the same key everywhere); with name-addressed keys the last writer wins. Metadata in the database has its own replication lag (Replication Topologies): if the row replicates after the object, a reader sees a row pointing to a missing object; write the object first or tolerate 404 with retry.

Scaling path: 1x, 10x, 100x ​

ScaleDesignWhat breaks next
1x (thousands of files)One private bucket, presigned URLs, files tableNothing; set lifecycle and versioning early
10x (millions of files, TB)CDN, hashed keys for public assets, event-driven processing, Storage LensEgress bill, LIST-based tooling, small-object overhead
100x (billions of objects, PB)Prefix design per tenant, Inventory instead of LIST, compaction, tiering by access, multi-account guardrails, replicationMetadata table size (shard it), per-prefix request limits, cost of tiny objects

Lab: presign, upload, verify, with tests ​

Expected, not run for commands that need a server. The Go and PHP tests listed run offline.

  1. Run the offline tests (real, no server needed):
$ cd docs/snippets/system-design/object-storage-file-systems/go
$ gofmt -l . ; go vet ./... ; go test ./...
ok  	academy/object-storage-file-systems/cas
ok  	academy/object-storage-file-systems/multipart
ok  	academy/object-storage-file-systems/presign
?   	academy/object-storage-file-systems/s3cfg	[no test files]
  1. Start MinIO and create the bucket (expected, not run):
$ docker run --rm -p 9000:9000 -p 9001:9001 minio/minio server /data --console-address ":9001"
$ mc alias set local http://127.0.0.1:9000 minioadmin minioadmin
$ mc mb local/uploads
Bucket created successfully `local/uploads`.
  1. Presign and upload with curl (expected, not run). Sign the URL in Go, then send exactly the signed headers:
$ curl -i -X PUT -H 'Content-Type: image/png' --data-binary @a.png "$URL"
HTTP/1.1 200 OK
ETag: "9b2cf535f27731c974343645a3985328"
$ curl -i -X PUT -H 'Content-Type: image/jpeg' --data-binary @a.png "$URL"
HTTP/1.1 403 Forbidden
<Code>SignatureDoesNotMatch</Code>
  1. Range read (expected, not run):
$ curl -s -o /dev/null -D - -H 'Range: bytes=0-99' "$GET_URL"
HTTP/1.1 206 Partial Content
Content-Range: bytes 0-99/1234
Accept-Ranges: bytes
  1. Expiry (expected, not run): wait past X-Amz-Expires, repeat step 3, expect 403 AccessDenied with Request has expired.

  2. Content-addressed dedup (expected, not run; the in-memory test proves the logic): upload the same bytes twice through cas.Store; the second call returns stored=false and the backend counter stays at one PutObject.

  3. Apply lifecycle and policy (expected, not run):

$ aws --endpoint-url http://127.0.0.1:9000 s3api put-bucket-lifecycle-configuration \
    --bucket uploads --lifecycle-configuration file://docs/snippets/system-design/object-storage-file-systems/config/lifecycle.json
$ aws --endpoint-url http://127.0.0.1:9000 s3api put-bucket-policy --bucket uploads \
    --policy file://docs/snippets/system-design/object-storage-file-systems/config/bucket-policy.json

The two JSON files are imported below. Replace the example account id 111122223333 and bucket name with yours.

json
{
  "Rules": [
    {
      "ID": "abort-incomplete-multipart",
      "Status": "Enabled",
      "Filter": { "Prefix": "" },
      "AbortIncompleteMultipartUpload": { "DaysAfterInitiation": 7 }
    },
    {
      "ID": "tier-logs",
      "Status": "Enabled",
      "Filter": { "Prefix": "logs/" },
      "Transitions": [
        { "Days": 30, "StorageClass": "STANDARD_IA" },
        { "Days": 90, "StorageClass": "GLACIER" }
      ],
      "Expiration": { "Days": 365 }
    },
    {
      "ID": "expire-old-versions",
      "Status": "Enabled",
      "Filter": { "Prefix": "" },
      "NoncurrentVersionExpiration": { "NoncurrentDays": 30 }
    }
  ]
}
json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "DenyInsecureTransport",
      "Effect": "Deny",
      "Principal": "*",
      "Action": "s3:*",
      "Resource": ["arn:aws:s3:::example-uploads", "arn:aws:s3:::example-uploads/*"],
      "Condition": { "Bool": { "aws:SecureTransport": "false" } }
    },
    {
      "Sid": "AppRoleReadWriteOwnPrefix",
      "Effect": "Allow",
      "Principal": { "AWS": "arn:aws:iam::111122223333:role/app-uploads" },
      "Action": ["s3:GetObject", "s3:PutObject", "s3:AbortMultipartUpload"],
      "Resource": "arn:aws:s3:::example-uploads/u/*"
    }
  ]
}

Diagrams ​

The three storage models side by side:

BlockEBS, iSCSI, SAN, local NVMeunit: fixed-size block by numberserver formats it: ext4, XFSattached to ONE host at a timeuse: database data directorycost: you manage fs + capacitylatency: sub-millisecondFileNFS, EFS, CephFS, SMB, HDFSunit: file in a directory treePOSIX: open, seek, rename, lockmounted by MANY hostsuse: shared home dirs, CMS mediacost: metadata server is the limitlatency: ~1-10 ms per opObjectS3, GCS, Azure Blob, MinIO, Ceph RGWunit: whole object under a keyPUT, GET, DELETE, LIST over HTTPno rename, no in-place edituse: uploads, backups, data lakescost: cheapest per GB, pay per requestlatency: tens of ms first byteMoving right trades POSIX semantics and latency for scale, price and sharing.Object keys look like paths ("a/b/c.png") but the namespace is flat; "a/b/" is only a prefix.

The direct-upload flow with a presigned URL:

BrowserApp serverLaravel / Go + DBObject storeS3 / MinIO1 POST /uploads {name, type, size}2 {url, headers}sign locally + INSERT status=pending3 PUT bytes (signed Content-Type, Content-Length)4 200 OK + ETag (app never saw the bytes)5 POST /uploads/id/done6 HEAD key: exists? size?7 status=readyExpiry bounds step 3 only; step 6 is what makes the database row true.

The GFS / HDFS architecture: metadata master, chunk servers, direct data path:

Clientlibrary in the appMetadata master (GFS master / HDFS NameNode)namespace + file to chunk map in RAMoperation log (GFS) / EditLog (HDFS) on diskchunk locations learned from heartbeatsChunk server 1Chunk server 2Chunk server 3ABACBCLinux files, one per chunkchecksummed blocks3 replicas by defaulton different racks if possible1 open / where is chunk?2 chunk handle + replica list3 bytes: data path skips the masterSmall control plane, wide data plane: the master never carries file data, so it is not the bandwidth limit.Its RAM and its single log are the limit: tens of millions of files, not trillions of small ones.

Content addressing in Git: blobs deduplicated, trees as Merkle nodes:

commit c1id = sha(content)tree t1names + child idsblob b1a.txt "hello"blob b1 (same id)copy.txt "hello"stored ONCEdedup by constructioncommit c2parent = c1tree t2 (new)only changed path rehashedblob b2 (new)a.txt "hello!"Change one byte and the id changes; so an object under an id can never be edited, only replaced by a new id.Same shape: OCI registry blobs (sha256:...), IPFS CIDs, restic/borg chunks, Nix store paths.Untouched blobs are reused by c2: history costs only the delta.

Common misconceptions ​

BeliefReality
S3 is a file system with foldersFlat key space; / is a character; rename is copy plus delete
S3 is eventually consistentStrong read-after-write for PUT and DELETE since 2020, with consistent listing
A presigned URL is privateIt is a bearer token valid until expiry; anyone holding it can use it
Eleven nines means the data is always availableDurability is not availability, and neither protects from your own delete
Versioning is a backupSame account, bucket and Region; use Object Lock and replication to another account
The master in GFS/HDFS carries the dataIt serves metadata only; data flows between clients and chunk servers
Content-addressed means secretThe key is public maths of the content; use access control and encryption
Glacier is always cheaperMinimum durations, retrieval fees and tiny-object rounding can invert it
Client-side size checks bound uploadsOnly a signed constraint or policy is enforced by the store
LIST is a fine query engineIt is slow, paged at 1,000 keys and billed; use a database or Inventory
S3-compatible means identicalCompatibility is partial; test your exact calls on the target
Encryption at rest stops leaked credentialsAuthorised principals receive plaintext; access control does that job

Cheat sheet ​

TopicRemember
ModelsBlock = raw disk, one host. File = POSIX tree, shared. Object = flat key to immutable blob over HTTP
Metadata masterGFS/HDFS: one index in RAM, data goes client to chunk server directly
S3 consistencyStrong read-after-write for PUT/DELETE; listing consistent
MultipartParts 1 to 10,000; 5 MiB to 5 GiB; abort leftovers with lifecycle
Range GETRange: bytes=a-b inclusive, 206 Partial Content
Presigned URLBearer token, minutes of life, sign Content-Type and length, record pending row, HEAD to confirm
POST policyNeeded for size range, key prefix and type pattern
CASkey = SHA-256; dedup, immutability, verify on read; ownership lives in the DB
ServingCDN in front; signed cookies for many files; hashed keys with immutable
Resumabletus (Upload-Offset, HEAD then PATCH) or multipart parts
MetadataDB for queries, object metadata for serving headers, tags for lifecycle
EncryptionSSE-S3 default since 2023; SSE-KMS for audit; SSE-C is yours to hold; client-side for zero trust
AccessIAM + bucket policy + Block Public Access (all four) + ACLs disabled
Coststorage + requests + egress; model all three; egress usually wins
Antipatternsfiles in DB, LIST to find, user file names as keys, proxying downloads

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why is a block volume not a shared storage system, and what do you add to share it? Must-know ​

Answer

Answer: A block device exposes numbered blocks and leaves the file system and caching to the single attached host; two hosts would corrupt each other's metadata. Sharing needs a file system layer that coordinates (NFS, EFS, CephFS, a cluster file system) or an object API.

2 — In GFS and HDFS, why is the single master not the bandwidth bottleneck? Important ​

Answer

Answer: It serves only metadata. Clients ask it where a chunk lives, cache the answer, then read and write chunk servers directly. Its real limits are RAM for the namespace and the log.

3 — What does S3 strong read-after-write consistency guarantee and not guarantee? Must-know ​

Answer

Answer: After a successful PUT or DELETE, any later GET or LIST sees it. It does not give multi-key transactions, atomic rename or uniqueness among concurrent writers; use conditional writes for create-once or compare-and-swap.

4 — List what a presigned PUT can enforce and what it cannot. Important ​

Answer

Answer: It binds method, key, expiry and any signed headers (such as exact Content-Type and Content-Length). It cannot restrict to a range of sizes, authenticate the holder, or inspect the bytes; use a POST policy for ranges and server-side checks for content.

5 — Why does a presigned S3 URL behave badly behind a CDN? Good to know ​

Answer

Answer: Each URL has a unique signature and expiry, so each is a different cache key and nothing is shared. Use the CDN's own signed URLs or cookies with a private origin.

6 — How do you stop incomplete multipart uploads silently costing money? Important ​

Answer

Answer: Add a lifecycle rule AbortIncompleteMultipartUpload with DaysAfterInitiation, for example 7; the parts are billed until completed or aborted.

7 — Why is content-addressable storage immutable and self-verifying? Important ​

Answer

Answer: The key is the hash of the bytes, so changing a byte changes the key; reading the blob and hashing it must reproduce the key, otherwise the data is corrupt.

8 — A bucket has versioning on. A user deletes an object. What exactly happens and how do you undo it? Important ​

Answer

Answer: S3 inserts a delete marker as the current version and keeps the old versions; a GET returns 404. Delete the marker (DELETE with its version id) to restore the previous version.

9 — Compare SSE-S3, SSE-KMS and SSE-C by key ownership. Must-know ​

Answer

Answer: SSE-S3: AWS owns and manages the keys. SSE-KMS: you control a KMS key and get audit and key policy. SSE-C: you send the key with every request over HTTPS and S3 does not keep it.

10 — Why do metadata queries belong in a database and not in object metadata? Must-know ​

Answer

Answer: Object metadata is readable only per key via HEAD/GET and is not queryable; finding files by listing is slow and billed per request. The database offers indexes, joins, authorisation and pagination.

11 — Estimate which cost line dominates for 20 TB/month of video egress with 50 TB stored, and name the fix. Important ​

Answer

Answer: Egress dominates in the worked estimate. A CDN in front reduces origin egress and GETs; revisit the dominant line after the change.

Glossary ​

TermMeaning
Block storageRaw disk addressed by block number, attached to one host (EBS, iSCSI)
File storageShared hierarchical tree with POSIX semantics (NFS, EFS, CephFS)
Object storageFlat key to immutable blob store over HTTP (S3, GCS, Azure Blob, MinIO, Ceph RGW)
POSIXStandard file system interface: open, read, write, seek, rename, locks
NFSNetwork File System, mounts a remote tree as local
EFSAWS Elastic File System, managed NFS
CephFSPOSIX file system on a Ceph cluster using metadata servers
GFSGoogle File System: single master, chunk servers, 64 MB chunks
HDFSHadoop Distributed File System: NameNode, DataNodes, 128 MB blocks
LustreParallel file system for HPC with metadata and object storage targets
Chunk serverNode storing replicated chunks as local files (GFS), a DataNode in HDFS
NameNode / metadata serverThe index of namespace and block locations
S3Amazon Simple Storage Service
BucketNamed container of objects in a Region
KeyThe object's name within a bucket
PrefixA leading part of a key used for grouping and listing
Flat namespaceNo real directories; slashes are just characters
Object metadataSystem headers and user x-amz-meta-* labels stored with an object
VersioningKeeping every version; delete adds a delete marker
Delete markerPlaceholder version that hides earlier versions
Object LockRetention and legal hold preventing delete or overwrite
WORMWrite once, read many
Lifecycle policyRules that transition or expire objects by age or tag
Storage classPrice and performance tier (Standard, IA, Glacier, Deep Archive)
GlacierArchive storage classes with retrieval delay and fees
Retrieval costPer-GB fee to read from colder classes
Read-after-write consistencyA read after a successful write sees the write
Strong consistencyOperations observe the latest committed state
Multipart uploadUpload as numbered parts assembled by a complete call
Range GETRequest of a byte range, returns 206 Partial Content
List objectsPaged listing of keys (1,000 per page), billed per request
Request pricingPer-request charges for PUT, GET, LIST and others
EgressData leaving the provider to the internet or another Region
Erasure codingSplitting data into K data and M parity shards (Reed-Solomon)
DurabilityProbability that stored data is not lost
Eleven nines99.999999999% annual object durability design target
Cross-region replicationAsynchronous copy of new objects to another Region (CRR)
Event notificationMessage to SQS, SNS, Lambda or EventBridge on object events
Presigned URLURL carrying a signature that grants one request for a limited time
ExpiryLifetime of a signature (X-Amz-Expires)
POST policySigned JSON rulebook for browser form uploads
Content-type constraintCondition fixing or limiting the uploaded media type
Content-addressable storageStore whose key is the hash of the content
SHA-256256-bit cryptographic hash used for content addresses
DedupStoring identical content once
ImmutabilityContent under a key never changes
Git objectBlob, tree or commit identified by a hash of its content
IPFSPeer-to-peer content-addressed network using CIDs
RegistryOCI/Docker image store addressing blobs by digest
Signed cookieCDN-validated cookie authorising many private files
Resumable uploadUpload that continues after interruption
tusOpen protocol for resumable uploads over HTTP
ChunkingSplitting a file into pieces for transfer or dedup
SSE-S3Server-side encryption with S3-managed keys
SSE-KMSServer-side encryption with an AWS KMS key
SSE-CServer-side encryption with a customer-provided key per request
Client-side encryptionEncryption in the application before upload
IAM policyIdentity-based permissions document
Bucket policyResource-based policy attached to a bucket
Public access blockFour settings that stop public exposure
ACLLegacy per-object access list, disabled by default
MinIOOpen-source S3-compatible object store
Ceph RGWRADOS Gateway: S3 and Swift API on Ceph
GCSGoogle Cloud Storage
Azure BlobMicrosoft Azure Blob Storage
ParquetColumnar file format with footer statistics
IcebergOpen table format with snapshots over object storage
Data lakeObject storage used as the analytics store
Storage facadeLaravel Illuminate\Support\Facades\Storage over Flysystem disks
temporaryUrlLaravel presigned GET
temporaryUploadUrlLaravel presigned upload URL plus required headers
putFileAsLaravel streaming upload with chosen name
VisibilityLaravel public or private file setting
Hot prefixKey prefix receiving traffic beyond its current capacity

References ​

Built by Morteza Negahi