Skip to content

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.

26 min read0/9 questions

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 storageFile storageObject storage
What it looks likeA raw disk attached to one serverA shared folder tree (paths, directories)A flat bucket of objects, each with a key and metadata
AccessThe OS mounts it; a filesystem or database sits on topNFS or SMB, mounted on many serversHTTP API: PUT, GET, DELETE by key
AWS exampleEBSEFSS3
OthersPersistent disks, local NVMeAzure Files, FilestoreGoogle Cloud Storage, Azure Blob, Cloudflare R2
LatencyLowest (sub-millisecond)LowTens of milliseconds to first byte
ScaleUp to tens of TB per volumePetabytes, sharedEffectively unlimited
Best forDatabase data files, boot disksLegacy apps that need a shared filesystemImages, 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.

Quick check
Which storage fits each need? You are running Postgres on an EC2 instance. Where do its data files live?
Need a nudge? A hint rules out a wrong answer.

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()
);
Quick check
A teammate stores uploaded photos as BYTEA columns in Postgres. The app has 50 million photos at about 2 MB each. What is the main problem?
Need a nudge? A hint rules out a wrong answer.

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.

Direct upload with a presigned URL
ClientAPIS3POST /uploads {type: image/jpeg, size: 3 MB}insert photo row (pending), sign URL{upload_url, photo_id} (expires in 5 min)PUT upload_url (3 MB of bytes)200 OKevent: object created

The client asks permission. The API checks auth, file type, size limits, and the user's quota.

1/6
presign.py
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 it in order5 steps

Put the photo upload flow in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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:

  1. CreateMultipartUpload returns an upload id.
  2. UploadPart sends each part with its part number. Each response carries that part's ETag. Parts can go in parallel and in any order.
  3. CompleteMultipartUpload sends 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.

A 4 GB upload that survives a dropped connection
PhoneAPIS3POST /uploads {size: 4 GB}{upload_id, part URLs 1..20}PUT parts 1..4 in parallelETags for parts 1..150resume upload_idparts 1..150 done, URLs for 151..256all parts done

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.

1/7

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.

Pythonpart_plan.py
MiB = 1024 ** 2GiB = 1024 ** 3MAX_PARTS = 10_000MIN_PART = 5 * MiB def plan(size: int) -> int: """Double the part size from the 5 MiB minimum until the file fits in 10,000 parts.""" part = MIN_PART while -(-size // part) > MAX_PARTS: # ceiling division part *= 2 return part for label, size in [("photo", 3 * MiB), ("phone video", 4 * GiB), ("raw footage", 300 * GiB)]: part = plan(size) parts = max(1, -(-size // part)) print(f"{label:<12} {size / GiB:8.2f} GiB part {part // MiB:>3} MiB parts {parts:>6}") # What a drop at 60% costs yousize = 4 * GiBpart = plan(size)in_flight = 4 * partprint(f"\nsingle PUT, drop at 60%: re-send {size / GiB:.2f} GiB")print(f"multipart, drop at 60%: re-send {in_flight / MiB:.0f} MiB (only the parts in flight)")
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

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))
Need a nudge? Hints walk you through it.

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.

Pythonetag.py
import hashlib data = bytes(range(256)) * 40_000 # about 10 MB of sample byteswhole_md5 = hashlib.md5(data).hexdigest() def multipart_etag(blob: bytes, part_size: int) -> str: parts = [blob[i:i + part_size] for i in range(0, len(blob), part_size)] digests = b"".join(hashlib.md5(p).digest() for p in parts) return f"{hashlib.md5(digests).hexdigest()}-{len(parts)}" print("MD5 of the file: ", whole_md5)print("ETag, 5 MiB parts: ", multipart_etag(data, 5 * 1024 ** 2))print("ETag, 8 MiB parts: ", multipart_etag(data, 8 * 1024 ** 2))
Output
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.

Quick check
Your nightly job verifies backups by comparing each S3 object's ETag with the local file's MD5. It starts reporting thousands of 'corrupt' files right after you switch the uploader to multipart. What is going on?
Need a nudge? A hint rules out a wrong answer.

The full picture: upload, process, serve

Step through the whole life of a photo, including how it is read back through a CDN.

Photo storage: upload, process, and serve
ClientClientAPIAPIPostgres: metadataPostgresmetadataObject storage: S3 bucketObject storageS3 bucketThumbnailer: LambdaThumbnailerLambdaCDN: CloudFrontCDNCloudFrontJSONmetadatapresigned PUTeventmark readyGET imageon miss

The client asks to upload. The API writes a pending row and returns a presigned URL. Small, fast JSON.

1/6

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.

Predict the outputPython

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)
Need a nudge? Hints walk you through it.

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 classRough price per GB-monthFirst-byte latencyUse it for
Standard$0.023MillisecondsHot data: new uploads, active assets
Standard-IA (infrequent access)$0.0125Milliseconds (per-GB retrieval fee)Older photos, read monthly
Glacier Instant Retrieval$0.004Milliseconds (higher retrieval fee)Archives that still must open instantly
Glacier Flexible Retrieval$0.0036Minutes to hoursBackups you rarely restore
Glacier Deep Archive$0.00099Up to 12 hoursCompliance 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.

lifecycle.json
{
  "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.

Pythonstorage_cost.py
# Rough S3 list prices, USD per GB-month (us-east-1). Check current pricing before real decisions.PRICE = { "Standard": 0.023, "Standard-IA": 0.0125, "Glacier Instant": 0.004, "Deep Archive": 0.00099,} TOTAL_TB = 500 # five years of user photosGB = TOTAL_TB * 1000 def monthly(split: dict[str, float]) -> float: return sum(GB * share * PRICE[tier] for tier, share in split.items()) everything_hot = {"Standard": 1.0}tiered = {"Standard": 0.05, "Standard-IA": 0.15, "Glacier Instant": 0.80} for name, split in [("all Standard", everything_hot), ("lifecycle tiers", tiered)]: cost = monthly(split) print(f"{name:<16} ${cost:>9,.0f}/month ${cost * 12:>10,.0f}/year")
Output
Press Run (⌘ Enter) to see what happens.
Quick check
A company must keep audit logs for 7 years for compliance. They are almost never read, and a 12-hour wait is acceptable when they are. Which class?
Need a nudge? A hint rules out a wrong answer.

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 PUT checks 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 a PUT means "create this only if no object exists at this key". If one does, S3 answers 412 Precondition Failed. Use it when exactly one writer must win: claiming a job by writing locks/job-981, writing an event exactly once under an idempotency key, or making sure two workers never both produce output/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.

Pythoncas_manifest.py
import hashlib, json class Bucket: """A tiny stand-in for S3 that supports If-Match on PUT.""" def __init__(self): self.objects = {} def get(self, key): body = self.objects[key] return body, hashlib.md5(body).hexdigest() def put(self, key, body, if_match=None): if if_match is not None: _, current = self.get(key) if current != if_match: return 412 self.objects[key] = body return 200 bucket = Bucket()bucket.put("manifest.json", json.dumps({"files": []}).encode()) def add_file(name, other_writer=None): for attempt in range(1, 5): body, etag = bucket.get("manifest.json") manifest = json.loads(body) manifest["files"].append(name) if other_writer and attempt == 1: other_writer() # someone else commits in between status = bucket.put("manifest.json", json.dumps(manifest).encode(), if_match=etag) print(f"{name}: attempt {attempt} -> {status}") if status == 200: return add_file("part-B.parquet", other_writer=lambda: add_file("part-A.parquet"))print(json.loads(bucket.get("manifest.json")[0]))
Output
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.

Quick check
Ten workers may all try to produce the daily report reports/2026-10-22.csv. You want exactly one to write it and the others to stop. What is the simplest correct approach?
Need a nudge? A hint rules out a wrong answer.

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.

Quick check
Paid subscribers stream videos served as HLS: a playlist plus about 600 segment files per video, through CloudFront. How should you protect them?
Need a nudge? A hint rules out a wrong answer.
Key terms
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.