Lesson 12 of 38Building blocks
Storage and Blobs
Pick block, file, or object storage, upload with presigned URLs, serve through a CDN, and tier data to cut costs.
Photos, videos, PDFs, backups, and logs are most of the bytes in almost every product, and they do not belong in your database. Getting them into the right kind of storage, uploading them without routing gigabytes through your API servers, and moving old data to cheaper tiers is the difference between a storage bill of $138,000 a year and $37,000. It also shows up in nearly every system design case study, from Instagram to YouTube to Dropbox.
Block, file, and object storage
There are three ways to store bytes, and they suit very different jobs.
| Block storage | File storage | Object storage | |
|---|---|---|---|
| What it looks like | A raw disk attached to one server | A shared folder tree (paths, directories) | A flat bucket of objects, each with a key and metadata |
| Access | The OS mounts it; a filesystem or database sits on top | NFS or SMB, mounted on many servers | HTTP API: PUT, GET, DELETE by key |
| AWS example | EBS | EFS | S3 |
| Others | Persistent disks, local NVMe | Azure Files, Filestore | Google Cloud Storage, Azure Blob, Cloudflare R2 |
| Latency | Lowest (sub-millisecond) | Low | Tens of milliseconds to first byte |
| Scale | Up to tens of TB per volume | Petabytes, shared | Effectively unlimited |
| Best for | Database data files, boot disks | Legacy apps that need a shared filesystem | Images, video, backups, logs, data lakes |
| Cost (rough, per GB-month) | ~$0.08 | ~$0.30 | ~$0.023, far less in cold tiers |
Object storage is the default for user content. Its traits: you write an object in one go and replace it rather than editing it in place, keys look like paths (users/42/avatar.jpg) but the namespace is flat, durability is extreme (S3 is designed for 99.999999999%, "eleven nines", by storing copies across several data centers), and you pay only for what you store and transfer.
Metadata in the database, bytes in object storage
The core pattern: the bytes go to object storage, and a small metadata row (who owns it, the object key, size, content type, dimensions, created date) goes in your database. The database stays small and fast; the object store holds petabytes.
CREATE TABLE photos (
id BIGSERIAL PRIMARY KEY,
owner_id BIGINT NOT NULL REFERENCES users(id),
object_key TEXT NOT NULL, -- 'photos/42/9f1c2e.jpg'
bytes INTEGER NOT NULL,
width INTEGER,
height INTEGER,
status TEXT NOT NULL DEFAULT 'pending',
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);BYTEA columns in Postgres. The app has 50 million photos at about 2 MB each. What is the main problem?Uploading with presigned URLs
If uploads go through your API servers, every byte of every video crosses your servers twice (in from the client, out to storage), tying up connections and bandwidth. Instead, the API hands the client a presigned URL: a normal S3 URL with a cryptographic signature that grants permission to do one thing (for example PUT to one key) for a short time (say 5 minutes). The client uploads directly to S3.
The client asks permission. The API checks auth, file type, size limits, and the user's quota.
import boto3
s3 = boto3.client("s3")
url = s3.generate_presigned_url(
"put_object",
Params={"Bucket": "photos-prod", "Key": "photos/42/9f1c2e.jpg", "ContentType": "image/jpeg"},
ExpiresIn=300, # seconds
)Downloads of private files work the same way: a presigned GET URL valid for a few minutes. Large files (over about 100 MB) use multipart upload: split into parts, upload them in parallel, retry only failed parts.
Put the photo upload flow in order.
- Tap the steps below in the right order.
Multipart and resumable uploads
A single PUT is fine for a 3 MB photo. It falls apart for a 4 GB video from a phone on a train. One request means one TCP connection carrying every byte, so a dropped connection at 90% throws away 3.6 GB and the user starts again. It is also slow, because one connection rarely fills the available bandwidth.
Multipart upload splits the object into numbered parts that are uploaded independently and stitched together at the end. In S3 it is three calls:
CreateMultipartUploadreturns an upload id.UploadPartsends each part with its part number. Each response carries that part's ETag. Parts can go in parallel and in any order.CompleteMultipartUploadsends the list of part numbers and ETags. S3 assembles the object, and only now does it appear in the bucket.
The S3 rules worth knowing: up to 10,000 parts, and every part except the last must be at least 5 MiB. That combination means the part size you choose sets the largest file you can upload, so pick it from the file size, not as a fixed constant.
With presigned URLs, the API calls CreateMultipartUpload itself and then presigns one UploadPart URL per part (or per batch of parts as the client asks for them). The client still never sends bytes through your servers.
Resumable is what multipart gives you for free once the client remembers its progress. Step through a dropped connection.
The API picks a part size (say 16 MiB, so 256 parts), creates the multipart upload, and stores the upload id against the video row.
Two failure modes catch teams in production. First, parts of an upload that is never completed or aborted sit in the bucket and are billed, but do not show up in a normal object listing. Every bucket that accepts multipart uploads should have a lifecycle rule with AbortIncompleteMultipartUpload after a few days. Second, presigned part URLs expire. For a slow upload, hand out URLs in batches as the client needs them rather than all 256 up front with a long expiry.
Outside S3, the ideas are the same with different names: Google Cloud Storage has resumable upload sessions, and tus is an open protocol for resumable HTTP uploads with client and server libraries in most languages, useful when you want the same behavior in front of any storage.
Press Run (⌘ Enter) to see what happens.You hard-code 16 MiB parts. A user uploads a 200 GiB file. How many parts would that need? (S3 allows at most 10,000.)
MiB = 1024 ** 2 GiB = 1024 ** 3 print(200 * GiB // (16 * MiB))
Checksums and ETags: knowing the bytes arrived intact
Bytes can be corrupted on a phone's flash, in a proxy, or by a bug in your own chunking code. TCP's own checksum is weak and does not protect anything outside the connection. If you care that the file a user uploaded is the file you store, you need an end-to-end checksum: computed on the client before upload, verified by the storage service on arrival, and saved in your metadata row so you can check it again later.
The ETag looks like a checksum but is not a reliable one. For a simple PUT of an unencrypted or SSE-S3 encrypted object, S3's ETag happens to be the MD5 of the content. For a multipart upload it is the MD5 of the concatenated part MD5s plus - and the part count, so it changes if you upload the same file with a different part size. For SSE-KMS encrypted objects it is not an MD5 of the content at all. Treat an ETag as a version identifier (it changes when the object changes), not as a content hash.
Press Run (⌘ Enter) to see what happens.Same bytes, three different values. That is why "compare the ETag to the file's MD5" breaks the first time someone uploads a large file.
For real integrity checks, S3 supports additional checksums: CRC32, CRC32C, CRC64NVME, SHA-1 and SHA-256. You send the checksum with the upload, S3 recomputes it, and the upload is rejected if they differ. The checksum is stored with the object and can be read back later. Current AWS SDKs calculate a CRC checksum on uploads by default, and S3 adds a CRC64NVME checksum to new objects uploaded without one. For multipart uploads, CRC-based algorithms can produce a full-object checksum (the same value you would compute over the whole local file) instead of a checksum of part checksums, which makes end-to-end comparison straightforward. Check the S3 docs for which algorithms support which mode.
A content hash (usually SHA-256) also enables deduplication: if two users upload the same file, store the bytes once under a key derived from the hash and point both metadata rows at it. File sync products lean on this heavily, at the level of chunks rather than whole files, as you will see in the file sync case study.
The full picture: upload, process, serve
Step through the whole life of a photo, including how it is read back through a CDN.
The client asks to upload. The API writes a pending row and returns a presigned URL. Small, fast JSON.
Because object keys never change contents (a new upload gets a new key), images can be cached at the CDN and in browsers for a year.
Users upload 2 million photos a day at about 400 KB each. How many GB per day? (1 GB = 1,000,000 KB)
print(2_000_000 * 400 // 1_000_000)
Lifecycle and storage tiers
Most stored data goes cold fast: a photo is viewed a lot in its first week and almost never after a year. Object stores offer cheaper storage classes for data you read rarely, with the trade-off of retrieval fees or slower access.
| S3 storage class | Rough price per GB-month | First-byte latency | Use it for |
|---|---|---|---|
| Standard | $0.023 | Milliseconds | Hot data: new uploads, active assets |
| Standard-IA (infrequent access) | $0.0125 | Milliseconds (per-GB retrieval fee) | Older photos, read monthly |
| Glacier Instant Retrieval | $0.004 | Milliseconds (higher retrieval fee) | Archives that still must open instantly |
| Glacier Flexible Retrieval | $0.0036 | Minutes to hours | Backups you rarely restore |
| Glacier Deep Archive | $0.00099 | Up to 12 hours | Compliance archives kept 7+ years |
(Rough us-east-1 list prices; check the current pricing page before real decisions. Intelligent-Tiering can move objects between tiers automatically based on access.)
A lifecycle rule automates the moves: for example, move to Standard-IA after 30 days, to Glacier Instant Retrieval after 180 days, and delete temporary uploads after 7 days.
{
"Rules": [
{
"ID": "photos-tiering",
"Filter": { "Prefix": "photos/" },
"Status": "Enabled",
"Transitions": [
{ "Days": 30, "StorageClass": "STANDARD_IA" },
{ "Days": 180, "StorageClass": "GLACIER_IR" }
]
},
{
"ID": "expire-tmp",
"Filter": { "Prefix": "tmp/" },
"Status": "Enabled",
"Expiration": { "Days": 7 }
}
]
}Run the cost comparison for 500 TB of photos.
Press Run (⌘ Enter) to see what happens.Consistency and conditional writes
Older material says S3 is "eventually consistent", meaning a read right after a write might return the old object. That stopped being true in December 2020. S3 now gives strong read-after-write consistency for every PUT and DELETE, including overwrites, and LIST results reflect completed writes immediately. After a successful upload, any later GET returns the new bytes. If you hear "S3 is eventually consistent" in an interview answer, it is out of date.
Strong consistency does not mean transactions. Two things still bite:
- Concurrent writers to the same key: the last write to finish wins, and the other is silently lost. Nothing in a plain
PUTchecks what was there. - Caches in front: S3 is consistent, but a CDN that cached the old version is not. Overwriting an object in place is one more reason to prefer new keys for new content.
For the first problem, S3 added conditional writes in 2024, which turn the bucket into something you can coordinate on:
If-None-Match: *on aPUTmeans "create this only if no object exists at this key". If one does, S3 answers412 Precondition Failed. Use it when exactly one writer must win: claiming a job by writinglocks/job-981, writing an event exactly once under an idempotency key, or making sure two workers never both produceoutput/2026-10-22.parquet.If-Match: <etag>means "overwrite only if the object is still the version I read". This is compare-and-swap: read a manifest, change it, write it back with the ETag you read, and retry from the read if someone else got there first. Open table formats on object storage depend on exactly this kind of atomic swap to commit new versions of a table.
Run a simulation of two workers adding entries to the same manifest file.
Press Run (⌘ Enter) to see what happens.Writer B read the manifest, but writer A committed first. B's write is rejected with 412, B re-reads (now containing A's file), adds its own, and succeeds. Without If-Match, B's write would have erased A's entry and nobody would have noticed.
reports/2026-10-22.csv. You want exactly one to write it and the others to stop. What is the simplest correct approach?Encryption and private media
Encryption at rest is on by default. Since January 2023 every new object in S3 is encrypted with SSE-S3 (keys managed entirely by AWS) unless you choose otherwise. The real choice is whether you need SSE-KMS, where the data keys are protected by a key you manage in AWS KMS. KMS adds three things SSE-S3 does not: every use of the key is logged in CloudTrail, the key policy is a second permission check (a caller needs both S3 access and permission to use the key), and you can disable the key to make the data unreadable everywhere at once. The cost is a KMS call per request, which gets expensive and can hit KMS request limits on busy buckets; enabling S3 Bucket Keys cuts those calls dramatically. Regulated workloads sometimes require client-side encryption, where data is encrypted before it leaves your service and S3 never sees plaintext.
Be clear about what at-rest encryption protects against: someone walking off with a disk. It does nothing against a caller with valid read permission, because S3 decrypts for anyone who is authorized. The controls that actually prevent leaks are bucket policies, IAM, S3 Block Public Access (on by default for new buckets), and never making a bucket public to serve files.
That raises the question of serving private media through a CDN. A presigned S3 URL works, but it bypasses the CDN entirely: every view is a request to the bucket, with no edge caching. The CDN-native answer is signing at the CDN layer:
- CloudFront signed URLs grant access to one file until an expiry time. Good for a single download, like an invoice PDF or a purchased ebook.
- CloudFront signed cookies grant access to many files matching a path pattern. This is the right tool for video: an HLS or DASH stream is a playlist plus hundreds of segment files, and signing each segment URL is impractical. Set one cookie for
/videos/981/*and every segment request carries it.
The bucket itself stays private with origin access control (OAC), so the CDN is the only thing that can read it. The CDN checks the signature at the edge, then serves from cache, so private content still gets edge performance. Other CDNs offer the same idea as signed tokens, often checked in an edge function.
The trade-off is the expiry. A signed link can be shared, and anyone holding it has access until it expires. Short lifetimes (minutes for downloads, a few hours for a viewing session) limit the damage; you refresh them from your API while the user is logged in. For paid video that must resist copying, signing is only the first layer, and DRM comes on top, as covered in video streaming.
- object storage
- A flat bucket of immutable objects addressed by key over HTTP, like S3. Cheap, durable, effectively unlimited.
- block storage
- A raw network disk attached to one server, like EBS. Used for databases and boot volumes.
- presigned URL
- A time-limited signed URL that lets a client upload or download one object directly from storage.
- metadata vs blob
- Small descriptive rows live in the database; the large bytes live in object storage, linked by key.
- storage class
- A price and access-speed tier like S3 Standard, Standard-IA, or Glacier Deep Archive.
- lifecycle rule
- A policy that moves objects to cheaper tiers or deletes them after a number of days.
- multipart upload
- Uploading an object as numbered parts that can be sent in parallel, retried alone, and combined at the end.
- end-to-end checksum
- A checksum computed by the client, verified by storage on arrival, and stored for later checks. An ETag is not one.
- conditional write
- A PUT that succeeds only if a precondition holds: no object yet (If-None-Match) or still the version you read (If-Match).
- signed cookie
- A CDN credential granting time-limited access to every file under a path, used for private video streams.