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 for | Go to |
|---|---|
| The whole page in four tables | Everything in one minute |
| Why files do not belong in a database row | Why it exists |
| GFS, HDFS, S3, Git, tus origins | Where it comes from |
| Raw disks, EBS, iSCSI | Block storage |
| NFS, EFS, CephFS, POSIX | File storage |
| GFS, HDFS, Lustre, chunk servers, metadata master | Distributed file systems |
| Bucket, key, prefix, flat namespace | The object model |
| Read-after-write, LIST, other providers | Consistency and listing |
| Versioning, delete markers, Object Lock, WORM | Versioning and immutability |
| Storage classes, lifecycle, retrieval fees | Storage classes and lifecycle |
| Eleven nines, erasure coding, replication, events | Durability and replication |
| Big files, parallel parts, partial reads | Multipart upload and range GET |
| Browser uploads straight to the store | Presigned URLs |
| Size and type limits on uploads | POST policies |
| Hash as key, dedup, Git, IPFS, registries | Content-addressable storage |
| CDN, signed cookies, video seeking | Serving files |
| Flaky mobile uploads | Resumable uploads: tus and chunking |
| Where to keep names, owners, sizes | Metadata: database vs object |
| SSE-S3, SSE-KMS, SSE-C, client side | Encryption |
| IAM, bucket policy, public access block, ACL | Access control |
| The monthly bill | Cost modelling |
| Parquet, Iceberg, data lakes | Data lakes |
| GCS, Azure Blob, MinIO, Ceph RGW | Other implementations |
| Mistakes seen in reviews | Antipatterns |
| Knobs, limits, error codes | Mechanics |
| Code | Go, Laravel |
| Failures and their fixes | Solving the classic problems |
| Which storage for which job | Choosing |
| Monolith to multi-region | In architecture |
| Commands and expected output | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
Three storage models. Same bytes, three contracts.
| Block storage | File storage | Object storage | |
|---|---|---|---|
| Unit | Fixed-size block addressed by number | File in a directory tree | Whole object under a key |
| Interface | SCSI or NVMe commands, iSCSI over a network | POSIX calls (open, seek, rename, flock) over NFS, SMB or a native client | HTTP: PUT, GET, DELETE, LIST, HEAD |
| Sharing | One host at a time (usually) | Many hosts mount the same tree | Any client with credentials, anywhere |
| In-place edit | Yes, any block | Yes, any byte range | No: replace the whole object |
| Products | AWS EBS, iSCSI SAN, local NVMe | NFS, AWS EFS, CephFS, HDFS (not POSIX), Lustre | AWS S3, Google Cloud Storage, Azure Blob Storage, MinIO, Ceph RGW |
| Typical use | Database data directory, boot disk | Shared home directories, legacy apps, ML scratch | Uploads, media, backups, logs, data lake |
| Scale limit | One volume, one host | Metadata server | Practically none for capacity; request rate per prefix |
The five S3 facts to memorise.
| Fact | Value | Source |
|---|---|---|
| Consistency | Strong read-after-write for PUT and DELETE, in all Regions | S3 User Guide |
| Multipart | Parts 1 to 10,000; part size 5 MiB to 5 GiB (last part may be smaller); max object 48.8 TiB | S3 quotas page |
| Single request rate | At least 3,500 PUT/COPY/POST/DELETE or 11,000 GET/HEAD per second per partitioned prefix | S3 performance guideline |
| Durability design | More than 99.999999999% (11 nines), data across at least 3 Availability Zones by default | S3 storage classes page |
| Presigned URL lifetime | Up to 7 days with SigV4 and IAM-user credentials; never longer than temporary credentials | S3 presigned URL page |
How a file gets from a browser into the store. Three designs, one right default.
| Design | Bytes pass through your app? | Size and type enforcement | When |
|---|---|---|---|
| App receives the upload, then writes to the store | Yes, twice (in and out) | Anywhere in your code | Small files, need to inspect or transform |
| Presigned PUT URL | No | One exact size and content type, signed into the URL | Default for direct upload of one object |
| Presigned POST policy | No | Range of sizes, key prefix, content type pattern | Browser 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.
| Choice | Gives you | Costs you |
|---|---|---|
| Bytes in the database row | One transaction covers metadata and bytes | Bloated backups, replica lag, expensive bandwidth |
| Bytes on the server's local disk | Fastest reads, no network hop | Lost on failure, not shared, sticky sessions |
| Bytes on a shared file system (NFS, EFS) | POSIX semantics, many readers and writers | Metadata server limit, per-operation latency, higher price per GB |
| Bytes in an object store | Near-unbounded capacity, high durability, cheap per GB, HTTP from anywhere | No 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
- "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.
- "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.
- "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
| Date | Milestone | Source |
|---|---|---|
| 2003 | The 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 POSIX | Ghemawat, Gobioff, Leung, GFS paper |
| Mid 2000s | HDFS 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 block | Apache Hadoop, HDFS Architecture |
| Mid 2000s | Amazon S3 introduces the bucket and key model over HTTP and becomes the template for every later object store | S3 User Guide (launch year not re-verified here) |
| 2005 onward | Git stores everything as objects whose id is the hash of their content: "Git is a content-addressable filesystem" | Pro Git, chapter 10 |
| Dec 2020 | S3 moves from eventual consistency for overwrites and deletes to strong read-after-write consistency | S3 User Guide states the current behaviour; the date is from the AWS announcement, not re-fetched |
| 2023 | S3 applies SSE-S3 encryption to every new object upload by default (January 5, 2023) | S3 encryption page |
| Later | Open table formats (Apache Iceberg) give object stores snapshot semantics and atomic table commits | Iceberg 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 durableReal 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.
| Product | What it is | Sharing | Notes |
|---|---|---|---|
| AWS EBS | Network block volume in one AZ | One 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 TCP | One initiator at a time unless cluster-aware | On-prem SANs |
| Local NVMe (instance store) | Disk in the host | One host | Lost with the instance |
| Ceph RBD | Block image on a Ceph cluster | One client by default | Same 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.
-- 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.
| Product | Protocol | Scales how | Known sharp edges |
|---|---|---|---|
| NFS (v3, v4.1) | NFS over TCP | One server, or pNFS for parallel data | Close-to-open consistency; stale file handles after server failover |
| AWS EFS | NFS v4.1 managed service | Elastic capacity, regional | Higher per-operation latency than local disk; priced per GB-month well above S3 |
| CephFS | POSIX on Ceph (metadata servers + OSDs) | Add MDS and OSD nodes | MDS tuning; same Ceph cluster can also expose block and S3 |
| SMB / CIFS | SMB 3 | Windows ecosystems | Different locking model |
| Lustre | Native client | Many metadata and object storage targets | HPC; 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.
| Concern | GFS | HDFS | CephFS / Lustre |
|---|---|---|---|
| Metadata | Single master, namespace in RAM, operation log, checkpoints | Single active NameNode (HA pair and Federation exist), EditLog and image | Metadata server cluster (MDS / MDT) |
| Data unit | 64 MB chunk | 128 MB block (typical) | Object / stripe |
| Durability | 3 replicas default, checksums per block | Replication factor 3 default, erasure coding available | Replication or erasure coding in the underlying store |
| Writes | Record append for concurrent producers | Write once, append only | POSIX writes |
| Fits | Large sequential reads and appends | Batch analytics | Shared 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 keyReal 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.
| Property | S3 | Google Cloud Storage | Azure Blob Storage | MinIO / Ceph RGW |
|---|---|---|---|---|
| Container | Bucket | Bucket | Container inside a storage account | Bucket |
| Namespace | Flat, prefix by convention | Flat; optional hierarchical namespace buckets | Flat, optional hierarchical namespace (ADLS Gen2) | Flat |
| Rename | Copy and delete | Copy and delete (rename for hierarchical buckets) | Rename for hierarchical namespace | Copy and delete |
| API | S3 | JSON and XML (S3-interoperable) | Blob REST | S3-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).
-- 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).
| Store | Read-after-write for objects | Listing after writes | Source |
|---|---|---|---|
| Amazon S3 | Strong (PUT and DELETE, all Regions) | Strong | S3 User Guide |
| Google Cloud Storage | Strong global consistency for object read-after-write, metadata update, delete and object listing | Strong | GCS consistency page |
| Azure Blob Storage | Strong consistency for blob operations within a storage account (not re-verified here) | Strong (not re-verified) | Microsoft docs, not fetched |
| MinIO | Strong for single objects in a single deployment (distributed mode uses erasure sets) | Strong | MinIO docs (not re-verified for listing) |
| Ceph RGW | Strong within a zone; multi-site replication between zones is asynchronous and eventually consistent | Strong within a zone | Ceph 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).
-- 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-dateReal 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.
| Feature | Protects from | Does not protect from | Cost note |
|---|---|---|---|
| Versioning | Overwrite, plain delete | Account compromise, bucket deletion, region loss | Every version bills as storage |
| Object Lock governance | Delete by ordinary users | Users with bypass permission | Same as versioning |
| Object Lock compliance | Everyone, including root, until retain-until | Nothing in scope, but you also cannot fix a mistake | Cannot shorten retention |
| Legal hold | Delete while hold is on | Whoever may remove the hold | None extra |
| Cross-Region or cross-account replication | Region loss, account compromise (with separate account) | Logical corruption replicated as a new version | Storage + 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 deletedReal 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.
| Class | Intended for | Retrieval | Minimum duration | Retrieval fee |
|---|---|---|---|---|
| Standard | Frequently accessed | Milliseconds | None | No |
| Intelligent-Tiering | Unknown or changing access | Milliseconds (optional archive tiers: minutes to hours) | None | No |
| Standard-IA / One Zone-IA | Rarely accessed, needs fast access | Milliseconds | 30 days (128 KB minimum billed size) | Yes, per GB |
| Glacier Instant Retrieval | Archive read about once a quarter | Milliseconds | 90 days | Yes |
| Glacier Flexible Retrieval | Archive | Minutes to hours | 90 days | Yes |
| Glacier Deep Archive | Long-term archive | Hours | 180 days | Yes |
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.
-- 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 2Real 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).
| Mechanism | Overhead | Failures tolerated | Repair cost | Used by |
|---|---|---|---|---|
| 3 replicas | 3.0x | 2 copies lost | Copy one replica | GFS, HDFS default, Ceph replicated pools |
| Reed-Solomon K+M | (K+M)/K | M shards lost | Read K shards to rebuild one | S3 (internal), MinIO, Ceph EC pools, HDFS erasure coding policies |
| Cross-Region replication | 2x storage + transfer | Whole-Region loss | Asynchronous copy | S3 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.
| Client | Behaviour | Knob |
|---|---|---|
AWS SDK for Go v2 manager.Uploader | Splits into parts, uploads concurrently, aborts on failure unless LeavePartsOnError | PartSize, Concurrency, MaxUploadParts |
AWS CLI s3 cp | Multipart over a threshold, parallel | multipart_threshold, multipart_chunksize, max_concurrent_requests |
Laravel putFileAs (Flysystem S3) | Streams the file; large streams use multipart in the SDK | Disk options |
| MinIO | Same API, same limits | Server 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.
| Variant | What is signed | Limits it can enforce | Use |
|---|---|---|---|
| Presigned GET | Method, key, expiry, optional response header overrides | Time, key | Private download |
| Presigned PUT | Method, key, expiry, signed headers (Content-Type, Content-Length, x-amz-*) | Exactly one content type and, if signed, one length | Direct upload of one object |
| Presigned UploadPart | One part of one multipart upload | Upload id, part number | Browser-side multipart |
| Presigned POST (policy) | A JSON policy | Size range, key prefix, content type pattern, metadata | Form-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).
-- 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.
| Constraint | Presigned PUT | POST policy |
|---|---|---|
| Exact size | Yes, sign Content-Length | Yes (min = max) |
| Size range | No | Yes: content-length-range |
| Content type | Exact value | Exact or starts-with |
| Key | Fixed | Fixed or starts-with prefix |
| Client | fetch/XHR with PUT | HTML 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.
| Concern | Content-addressed | Name-addressed |
|---|---|---|
| Identity | Hash of bytes | Chosen by writer |
| Update in place | Impossible by design | Overwrite |
| Dedup | Automatic | Needs a separate index |
| Integrity check | Built in | Separate checksum column |
| Access control | Needs a separate mapping from owner to digest | Natural (per-key policy) |
| Deletion | Reference counting or GC; privacy erasure is hard | Delete the key |
| Hash choice | SHA-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.
-- 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 inventoryServing 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 ContentReal 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.
| Need | Mechanism | Product |
|---|---|---|
| Public, cacheable, forever | Content-hashed key + Cache-Control: immutable | Any CDN |
| One private file, short time | Signed URL | CloudFront signed URL; S3 presigned URL (no CDN caching) |
| Many private files, one session | Signed cookie | CloudFront signed cookies |
| App must authorise every hit | Redirect (302) to a short-lived URL | Laravel temporaryUrl |
| Seeking and resuming | Range and 206 | S3, 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).
| Approach | Resume after | Server state | Best for |
|---|---|---|---|
| Single presigned PUT | Never (restart) | None | Files under a few tens of MB |
| S3 multipart with presigned parts | Part boundary | Upload id in your DB | Large files, browser to S3 |
| tus (1.0.0) | Any byte offset | Upload resource with offset | Flaky mobile networks, open protocol |
| Content-defined chunking + digests | Chunk | Chunk index | Sync, 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).
| Data | Put it in | Why |
|---|---|---|
| Owner, permissions, status, display name, folder tree | Database row | Queryable, transactional, indexable |
| Content-Type, Cache-Control, Content-Disposition | Object system metadata | Needed at serve time by the store and CDN |
| Content hash, size | Both (object checksum, DB column) | Verify on read, dedup lookups |
Lifecycle bucket (retention=7y) | Object tag | Lifecycle filters read tags |
| Full-text, thumbnails, derived data | Separate objects + DB row | Derived 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.
| Option | Who holds the key | Audit | Trade-off |
|---|---|---|---|
| SSE-S3 | AWS (S3-managed) | Limited | Default, zero effort, no per-request key control |
| SSE-KMS | You, via AWS KMS key policy | CloudTrail per use | KMS cost and quota; cross-account needs key policy |
| DSSE-KMS | You, two layers | CloudTrail | Compliance requirements |
| SSE-C | You, sent on every request | Yours | Cannot be used with CloudFront or most managed services |
| Client-side | You (application, HSM, KMS) | Yours | Provider 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: allowReal 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.
| Layer | Scope | Use |
|---|---|---|
| IAM identity policy | Principal | What this role may do |
| Bucket policy | Bucket | Who may do what here; cross-account; mandatory conditions |
| Block Public Access | Account or bucket | Hard stop on public exposure |
| ACL | Object or bucket | Legacy; disabled by default through Bucket owner enforced |
| Access points, VPC endpoint policies | Network and per-app | Per-application entry points |
| Presigned URL | One request | Temporary 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 tuneReal 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.
| Lever | Reduces | Risk |
|---|---|---|
| Lifecycle to colder classes | Storage | Retrieval fees, minimum durations |
| CDN in front | Egress, GETs | Cache invalidation cost, signed-URL design |
| Fewer, larger objects (compaction) | Requests, per-object overhead | Read amplification for small reads |
| Intelligent-Tiering | Storage with no retrieval fee | Per-object monitoring fee, ignores tiny objects |
| Abort incomplete multipart | Orphan storage | None |
| Same-Region compute and VPC gateway endpoint | Transfer, NAT charges | Cross-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.
| Layer | Role | Product examples |
|---|---|---|
| Storage | Immutable files | S3, GCS, Azure Blob, MinIO, Ceph RGW |
| File format | Columnar data | Parquet, ORC, Avro |
| Table format | Snapshots, schema evolution, commits | Iceberg, Delta Lake, Hudi |
| Catalog | Where the current metadata pointer lives | Hive Metastore, AWS Glue, Nessie, REST catalog |
| Engine | Query | Trino, 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.
| Feature | AWS S3 | Google Cloud Storage | Azure Blob Storage | MinIO | Ceph RGW |
|---|---|---|---|---|---|
| Signed temporary access | Presigned URL (SigV4) | Signed URL (V4) | SAS token | Presigned URL (SigV4) | Presigned URL (SigV4) |
| Strong consistency | Yes | Yes | Yes (not re-verified here) | Yes (single deployment) | Within a zone |
| Object Lock | Yes | Retention policies, object holds | Immutable storage, legal hold | Yes (S3 API) | Yes (S3 API, not re-verified) |
| Erasure coding | Internal | Internal | Internal | Reed-Solomon sets | Pools (k+m) |
| Where it runs | AWS | GCP | Azure | Anywhere | Anywhere |
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.
| Antipattern | What goes wrong | Fix |
|---|---|---|
Storing files in a database row (bytea, BLOB) | Bloated WAL, backups and replicas; buffer cache churn; app memory per request | Object key in the row, bytes in the store |
LIST to find a file | Slow, billed per page of 1,000 keys, grows with bucket size | Query the database; keep the key |
| User-supplied file name as key | Collisions, overwrites, path tricks (../), personal data in logs | Generate UUID or hash keys |
| Sequential or timestamp-prefixed keys at huge rates | Concentrates load on one prefix partition ("hot prefix"); S3 now scales prefixes automatically but a sudden spike can still see 503 Slow Down | Spread keys with a hash prefix, retry with backoff |
| Proxying large downloads through the app server | PHP/Go workers tied up for slow clients | 302 to a presigned URL or CDN |
| Public bucket for convenience | Data leak | Block Public Access + CDN with origin access control |
| Trusting client-declared type and size | Malware, huge uploads | Signed constraints, server-side HEAD, content sniff |
| Presigned URLs with 7-day expiry, logged | Bearer tokens in logs live for days | Minutes of life, never log full URLs |
| No lifecycle rule for incomplete multipart uploads and noncurrent versions | Silent growing bill | Lifecycle rules from day one |
| Treating the bucket as a queue or lock service | Polling cost, no ordering | Use a queue; use conditional writes only for coarse create-once |
| One object per tiny record | Request cost, slow scans | Batch into larger objects (compaction) |
| Overwriting objects in place that a CDN caches | Stale content for TTL | Immutable, 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
| Knob | Where | Meaning | Typical value |
|---|---|---|---|
X-Amz-Expires | Presigned URL | Lifetime in seconds | 300 to 900 |
X-Amz-SignedHeaders | Presigned URL | Headers that must match exactly | content-type;host |
PartSize / Concurrency | Go manager.Uploader | Multipart part size and parallel parts | 16 MiB / 4 to 16 |
multipart_threshold, multipart_chunksize | AWS CLI | Switch-over size and part size | 8 MB / 8 MB (CLI defaults, not re-verified) |
Range: bytes=a-b | GET | Inclusive byte range | per read |
Cache-Control | Object metadata | CDN and browser TTL | public, max-age=31536000, immutable for hashed keys |
AbortIncompleteMultipartUpload.DaysAfterInitiation | Lifecycle | Clean orphan parts | 7 |
NoncurrentVersionExpiration.NoncurrentDays | Lifecycle | Expire old versions | 30 |
If-None-Match: * | PutObject | Create only if absent | CAS and locks |
use_path_style_endpoint / UsePathStyle | Laravel / Go | Needed for MinIO and many S3-compatible stores | true |
visibility | Laravel disk | private or public object ACL behaviour | private |
Errors you will meet
| Code | Where | Meaning | Action |
|---|---|---|---|
403 SignatureDoesNotMatch | Presigned PUT/GET | Signed header, region, clock or key differs | Send exactly the signed headers; check clock skew and Region |
403 AccessDenied | Any | Policy, expired URL, Block Public Access | Read the policy evaluation; check expiry |
403 RequestTimeTooSkewed | Signed requests | Client clock too far from server time (15 minutes in AWS's documentation, not re-verified) | Fix NTP |
400 ExpiredToken / AccessDenied (expired) | Presigned | Credentials or URL expired | Request a new URL |
404 NoSuchKey / NoSuchUpload | GET / multipart | Key missing or upload aborted | Check key, re-initiate |
409 OperationAborted, 409 BucketAlreadyOwnedByYou | Bucket ops | Conflicting concurrent change | Retry later |
412 PreconditionFailed | Conditional PUT | If-None-Match or If-Match failed | Someone wrote first; read and decide |
416 InvalidRange | Range GET | Range outside the object | Clamp to size |
400 EntityTooSmall / EntityTooLarge | Multipart or POST policy | Part under 5 MiB or size outside policy | Fix part plan or the policy |
503 SlowDown | Any | Request rate above current capacity | Exponential backoff with jitter (Timeouts, Retries & Jitter) |
403 InvalidObjectState | GET | Object is in an archive class, not restored | RestoreObject, 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
| Operation | First-byte latency (rough order of magnitude, inference) | Throughput note |
|---|---|---|
| Local NVMe read | tens of microseconds | GB/s |
| EBS volume read | around one millisecond | Provisioned IOPS and MB/s |
| EFS / NFS read | a few milliseconds | Per-operation overhead dominates small files |
| S3 GET in the same Region | tens of milliseconds | Scale with parallel connections and range requests |
| S3 Glacier Flexible restore | minutes to hours | Asynchronous |
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: *.
// 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)
}// 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
}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)
}
}// 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)
}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)
}
}// 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
}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)
}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,PresignUploadPartandPresignPostObjectare the four entry points; the options functions3.WithPresignExpiressets the lifetime. - To make the store enforce a header, it must be part of the
PutObjectInputyou sign; the returnedPresignedHTTPRequesthasSignedHeader, and the browser must send those headers verbatim. manager.Uploader(packagefeature/s3/manager) buffersPartSizebytes per part and uploadsConcurrencyparts at once; memory use is roughlyPartSize x Concurrency. It aborts the multipart upload on failure unlessLeavePartsOnErroris true.MaxUploadPartsdefaults to 10,000.- Reading:
GetObjectreturns a stream; alwaysdefer out.Body.Close()and preferio.Copyto a destination overio.ReadAllfor big objects. Range reads useRange: bytes=a-b. - Errors are typed: use
errors.Aswith*types.NoSuchKey,*types.NotFound(HEAD) andsmithy.APIError(ErrorCode()forSlowDown,PreconditionFailed). The SDK's retryer already backs off on 503; setRetryMaxAttemptsdeliberately. - Credentials: use the default chain (
config.LoadDefaultConfig) in production. Thes3cfghelper uses static keys to stay self-contained; for MinIO setBaseEndpointandUsePathStyle. crypto/sha256plusio.TeeReaderhashes while streaming;cas.Putreads 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: *onPutObjectis the SDK fieldIfNoneMatch; 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
// 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
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
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
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
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');
});-- 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). Configurekey,secret,region,bucket,url,endpoint; for MinIO and other S3-compatible stores setendpointanduse_path_style_endpoint => true. Storage::temporaryUrl($path, now()->plus(minutes: 5))returns a presigned GET for thes3driver (and a signed route for the local driver). The third argument takes response overrides such asResponseContentTypeandResponseContentDisposition.Storage::temporaryUploadUrl($path, $expiration)returns['url' => ..., 'headers' => [...]]; the client must send those headers. It exists for thes3driver only.putFileandputFileAsaccept anUploadedFileorIlluminate\Http\Fileand stream it; do notfile_get_contentsa large upload into memory.- Visibility:
publicandprivatemap 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.getVisibilityandsetVisibilityexist;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' => trueon the disk so failures raise exceptions instead of returningfalse. - 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, presignedUploadPart) or a tus server for large browser uploads.
Solving the classic problems
Users upload through the app and PHP workers or pods run out
| Solution | How | Advantage | Cost or limit |
|---|---|---|---|
| Presigned PUT | App signs, browser PUTs to the store | App bandwidth and workers freed | Need pending row and confirm step |
| Presigned multipart parts | App signs each UploadPart | Resume per part, large files | More round trips; store upload id |
| tus server | tusd or similar writes to S3 | Resume at any byte | Another 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
| Workload | Storage | Extra technique | Reason |
|---|---|---|---|
| User uploads (avatars, attachments) | Object store, private bucket | Presigned PUT, DB metadata, CDN for public derivatives | Durable, cheap, bypasses app servers |
| Database data directory | Block volume | Snapshots, replication | Needs low latency in-place writes |
Shared uploads/ for a legacy CMS | EFS / NFS | Migrate to objects when possible | POSIX semantics required |
| Backups, archives, compliance | Object store, cold class | Object Lock, lifecycle, CRR to another account | Cheapest durable, immutable |
| Analytics over logs and events | Object store with Parquet and Iceberg | Compaction, partitioning | Engines scan ranges in parallel |
| Static website and downloads | Object store + CDN | Hashed keys, immutable | Edge serves; origin sees misses |
| Hadoop/Spark with data locality | HDFS or object store with S3A | Erasure coding | Locality vs elasticity |
| ML training data | Object store + local NVMe cache, or a parallel FS (Lustre) for HPC | Prefetch, range reads | Throughput vs cost |
| Container images | Registry on an object store | Content-addressed layers | Dedup and verification |
| Small structured records | Database, not objects | n/a | Queries, 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
| Scale | Design | What breaks next |
|---|---|---|
| 1x (thousands of files) | One private bucket, presigned URLs, files table | Nothing; set lifecycle and versioning early |
| 10x (millions of files, TB) | CDN, hashed keys for public assets, event-driven processing, Storage Lens | Egress 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, replication | Metadata 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.
- 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]- 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`.- 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>- 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: bytesExpiry (expected, not run): wait past
X-Amz-Expires, repeat step 3, expect403 AccessDeniedwithRequest has expired.Content-addressed dedup (expected, not run; the in-memory test proves the logic): upload the same bytes twice through
cas.Store; the second call returnsstored=falseand the backend counter stays at onePutObject.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.jsonThe two JSON files are imported below. Replace the example account id 111122223333 and bucket name with yours.
{
"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 }
}
]
}{
"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:
The direct-upload flow with a presigned URL:
The GFS / HDFS architecture: metadata master, chunk servers, direct data path:
Content addressing in Git: blobs deduplicated, trees as Merkle nodes:
Common misconceptions
| Belief | Reality |
|---|---|
| S3 is a file system with folders | Flat key space; / is a character; rename is copy plus delete |
| S3 is eventually consistent | Strong read-after-write for PUT and DELETE since 2020, with consistent listing |
| A presigned URL is private | It is a bearer token valid until expiry; anyone holding it can use it |
| Eleven nines means the data is always available | Durability is not availability, and neither protects from your own delete |
| Versioning is a backup | Same account, bucket and Region; use Object Lock and replication to another account |
| The master in GFS/HDFS carries the data | It serves metadata only; data flows between clients and chunk servers |
| Content-addressed means secret | The key is public maths of the content; use access control and encryption |
| Glacier is always cheaper | Minimum durations, retrieval fees and tiny-object rounding can invert it |
| Client-side size checks bound uploads | Only a signed constraint or policy is enforced by the store |
LIST is a fine query engine | It is slow, paged at 1,000 keys and billed; use a database or Inventory |
| S3-compatible means identical | Compatibility is partial; test your exact calls on the target |
| Encryption at rest stops leaked credentials | Authorised principals receive plaintext; access control does that job |
Cheat sheet
| Topic | Remember |
|---|---|
| Models | Block = raw disk, one host. File = POSIX tree, shared. Object = flat key to immutable blob over HTTP |
| Metadata master | GFS/HDFS: one index in RAM, data goes client to chunk server directly |
| S3 consistency | Strong read-after-write for PUT/DELETE; listing consistent |
| Multipart | Parts 1 to 10,000; 5 MiB to 5 GiB; abort leftovers with lifecycle |
| Range GET | Range: bytes=a-b inclusive, 206 Partial Content |
| Presigned URL | Bearer token, minutes of life, sign Content-Type and length, record pending row, HEAD to confirm |
| POST policy | Needed for size range, key prefix and type pattern |
| CAS | key = SHA-256; dedup, immutability, verify on read; ownership lives in the DB |
| Serving | CDN in front; signed cookies for many files; hashed keys with immutable |
| Resumable | tus (Upload-Offset, HEAD then PATCH) or multipart parts |
| Metadata | DB for queries, object metadata for serving headers, tags for lifecycle |
| Encryption | SSE-S3 default since 2023; SSE-KMS for audit; SSE-C is yours to hold; client-side for zero trust |
| Access | IAM + bucket policy + Block Public Access (all four) + ACLs disabled |
| Cost | storage + requests + egress; model all three; egress usually wins |
| Antipatterns | files in DB, LIST to find, user file names as keys, proxying downloads |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| Block storage | Raw disk addressed by block number, attached to one host (EBS, iSCSI) |
| File storage | Shared hierarchical tree with POSIX semantics (NFS, EFS, CephFS) |
| Object storage | Flat key to immutable blob store over HTTP (S3, GCS, Azure Blob, MinIO, Ceph RGW) |
| POSIX | Standard file system interface: open, read, write, seek, rename, locks |
| NFS | Network File System, mounts a remote tree as local |
| EFS | AWS Elastic File System, managed NFS |
| CephFS | POSIX file system on a Ceph cluster using metadata servers |
| GFS | Google File System: single master, chunk servers, 64 MB chunks |
| HDFS | Hadoop Distributed File System: NameNode, DataNodes, 128 MB blocks |
| Lustre | Parallel file system for HPC with metadata and object storage targets |
| Chunk server | Node storing replicated chunks as local files (GFS), a DataNode in HDFS |
| NameNode / metadata server | The index of namespace and block locations |
| S3 | Amazon Simple Storage Service |
| Bucket | Named container of objects in a Region |
| Key | The object's name within a bucket |
| Prefix | A leading part of a key used for grouping and listing |
| Flat namespace | No real directories; slashes are just characters |
| Object metadata | System headers and user x-amz-meta-* labels stored with an object |
| Versioning | Keeping every version; delete adds a delete marker |
| Delete marker | Placeholder version that hides earlier versions |
| Object Lock | Retention and legal hold preventing delete or overwrite |
| WORM | Write once, read many |
| Lifecycle policy | Rules that transition or expire objects by age or tag |
| Storage class | Price and performance tier (Standard, IA, Glacier, Deep Archive) |
| Glacier | Archive storage classes with retrieval delay and fees |
| Retrieval cost | Per-GB fee to read from colder classes |
| Read-after-write consistency | A read after a successful write sees the write |
| Strong consistency | Operations observe the latest committed state |
| Multipart upload | Upload as numbered parts assembled by a complete call |
| Range GET | Request of a byte range, returns 206 Partial Content |
| List objects | Paged listing of keys (1,000 per page), billed per request |
| Request pricing | Per-request charges for PUT, GET, LIST and others |
| Egress | Data leaving the provider to the internet or another Region |
| Erasure coding | Splitting data into K data and M parity shards (Reed-Solomon) |
| Durability | Probability that stored data is not lost |
| Eleven nines | 99.999999999% annual object durability design target |
| Cross-region replication | Asynchronous copy of new objects to another Region (CRR) |
| Event notification | Message to SQS, SNS, Lambda or EventBridge on object events |
| Presigned URL | URL carrying a signature that grants one request for a limited time |
| Expiry | Lifetime of a signature (X-Amz-Expires) |
| POST policy | Signed JSON rulebook for browser form uploads |
| Content-type constraint | Condition fixing or limiting the uploaded media type |
| Content-addressable storage | Store whose key is the hash of the content |
| SHA-256 | 256-bit cryptographic hash used for content addresses |
| Dedup | Storing identical content once |
| Immutability | Content under a key never changes |
| Git object | Blob, tree or commit identified by a hash of its content |
| IPFS | Peer-to-peer content-addressed network using CIDs |
| Registry | OCI/Docker image store addressing blobs by digest |
| Signed cookie | CDN-validated cookie authorising many private files |
| Resumable upload | Upload that continues after interruption |
| tus | Open protocol for resumable uploads over HTTP |
| Chunking | Splitting a file into pieces for transfer or dedup |
| SSE-S3 | Server-side encryption with S3-managed keys |
| SSE-KMS | Server-side encryption with an AWS KMS key |
| SSE-C | Server-side encryption with a customer-provided key per request |
| Client-side encryption | Encryption in the application before upload |
| IAM policy | Identity-based permissions document |
| Bucket policy | Resource-based policy attached to a bucket |
| Public access block | Four settings that stop public exposure |
| ACL | Legacy per-object access list, disabled by default |
| MinIO | Open-source S3-compatible object store |
| Ceph RGW | RADOS Gateway: S3 and Swift API on Ceph |
| GCS | Google Cloud Storage |
| Azure Blob | Microsoft Azure Blob Storage |
| Parquet | Columnar file format with footer statistics |
| Iceberg | Open table format with snapshots over object storage |
| Data lake | Object storage used as the analytics store |
| Storage facade | Laravel Illuminate\Support\Facades\Storage over Flysystem disks |
| temporaryUrl | Laravel presigned GET |
| temporaryUploadUrl | Laravel presigned upload URL plus required headers |
| putFileAs | Laravel streaming upload with chosen name |
| Visibility | Laravel public or private file setting |
| Hot prefix | Key prefix receiving traffic beyond its current capacity |
References
- Amazon S3 User Guide, What is Amazon S3 (consistency): https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html
- Amazon S3, multipart upload overview: https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpuoverview.html
- Amazon S3, multipart upload limits: https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html
- Amazon S3, sharing objects with presigned URLs: https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html
- Amazon S3, POST policy conditions: https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-HTTPPOSTConstructPolicy.html
- Amazon S3, Object Lock: https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lock.html
- Amazon S3, versioning: https://docs.aws.amazon.com/AmazonS3/latest/userguide/Versioning.html
- Amazon S3, storage classes: https://docs.aws.amazon.com/AmazonS3/latest/userguide/storage-class-intro.html
- Amazon S3, storage classes and durability: https://aws.amazon.com/s3/storage-classes/
- Amazon S3, lifecycle management: https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lifecycle-mgmt.html
- Amazon S3, server-side encryption: https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingEncryption.html
- Amazon S3, SSE-C: https://docs.aws.amazon.com/AmazonS3/latest/userguide/ServerSideEncryptionCustomerKeys.html
- Amazon S3, replication: https://docs.aws.amazon.com/AmazonS3/latest/userguide/replication.html
- Amazon S3, Block Public Access: https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-control-block-public-access.html
- Amazon S3, Object Ownership and ACLs: https://docs.aws.amazon.com/AmazonS3/latest/userguide/about-object-ownership.html
- Amazon S3, event notifications: https://docs.aws.amazon.com/AmazonS3/latest/userguide/EventNotifications.html
- Amazon S3, performance guidelines: https://docs.aws.amazon.com/AmazonS3/latest/userguide/optimizing-performance.html
- Amazon S3, checking object integrity (checksums): https://docs.aws.amazon.com/AmazonS3/latest/userguide/checking-object-integrity.html
- Amazon S3, GetObject API: https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html
- Amazon S3 pricing: https://aws.amazon.com/s3/pricing/
- Amazon CloudFront, signed cookies: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-signed-cookies.html
- AWS SDK for Go v2, service/s3 (PresignClient): https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3
- AWS SDK for Go v2, feature/s3/manager: https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/feature/s3/manager
- Ghemawat, Gobioff, Leung, The Google File System (SOSP 2003): https://research.google.com/archive/gfs-sosp2003.pdf
- Apache Hadoop, HDFS Architecture: https://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-hdfs/HdfsDesign.html
- MinIO, erasure coding: https://min.io/docs/minio/linux/operations/concepts/erasure-coding.html
- Ceph, RADOS Gateway: https://docs.ceph.com/en/latest/radosgw/
- Google Cloud Storage, consistency: https://cloud.google.com/storage/docs/consistency
- tus, resumable upload protocol 1.0.0: https://tus.io/protocols/resumable-upload
- Pro Git, Git Internals: Git Objects: https://git-scm.com/book/en/v2/Git-Internals-Git-Objects
- IPFS Docs, Content Identifiers (CIDs): https://docs.ipfs.tech/concepts/content-addressing/
- OCI Distribution Specification: https://github.com/opencontainers/distribution-spec/blob/main/spec.md
- Apache Iceberg, table specification: https://iceberg.apache.org/spec/
- Laravel 13, File Storage: https://laravel.com/docs/13.x/filesystem