Skip to content

Pattern: Handling Large Files and Blobs

Intermediate 53 min read Part 11 of 18

Move big files without choking your servers: presigned URLs, multipart and resumable uploads, chunk dedupe, metadata sync, events and signed CDN delivery.

Summary#

Large files such as photos, videos, documents, backups and model weights should not pass through your application servers. The pattern splits the work in two:

  • The control plane is your API. It authenticates the user, decides what they may upload or download, records metadata in a database, and hands out a short-lived, narrowly scoped presigned URL.
  • The data plane is the blob store and the CDN. The client sends bytes straight to object storage, such as Amazon S3, Google Cloud Storage or Azure Blob Storage, and downloads them from a CDN edge using signed URLs.

The extras make this work for real-world files:

  • Multipart and resumable uploads handle flaky networks and multi-gigabyte files.
  • Chunking with content hashes enables deduplication and sync of only the changed parts.
  • Storage event notifications keep the metadata database in step with what actually landed in the bucket, and trigger processing such as scanning, thumbnails and transcoding.

The hard part is not the upload. It is keeping two systems, the database and the bucket, consistent when either side can fail.

Why It Exists#

Picture the naive design. A user uploads a 2 GB video to POST /videos. A load balancer forwards the request to an API server, which reads the body and writes it to S3. Downloads run the same path in reverse. This is the server as a proxy. For a 50 KB avatar it is fine. As files grow, it falls apart in several ways at once.

  • Bandwidth. Every byte crosses your servers twice: once in from the client, once out to storage. Suppose 1,000 users upload at the same time at 20 Mbit/s each. That is 20 Gbit/s inbound and another 20 Gbit/s outbound to S3. You now need a fleet sized for bandwidth, not for request logic, and you pay for that fleet to do nothing smarter than copy bytes.

  • Connection time. A 2 GB file on a 20 Mbit/s home uplink takes 2 × 8,000 / 20 = 800 seconds, more than 13 minutes. That is 13 minutes of a held connection, a worker thread or event-loop slot, socket buffers, and often a memory buffer, all for one request. Thread-per-request servers run out of threads quickly.

  • Timeouts and limits on the path. Infrastructure in front of your code was not built for 13-minute requests:

    • AWS Application Load Balancers close idle connections after 60 seconds by default.
    • Amazon API Gateway caps request payloads at 10 MB.
    • Synchronous AWS Lambda invocations cap payloads at 6 MB.
    • Reverse proxies and CDNs in front of your API usually enforce body-size limits of their own.

    You can raise some of these limits, but every raise makes the fleet more fragile.

  • Deploys and crashes kill uploads. A rolling deploy, an autoscaling scale-in or a crashed process drops every in-flight upload on that host. The user's 98%-complete upload restarts from zero.

  • Blast radius. Upload traffic and API traffic share the same servers. A burst of uploads, such as everyone posting photos after a concert, starves latency-sensitive API calls such as login and feed loads.

  • Cost. In the cloud, data that crosses availability zones or leaves the region is billed. Proxying can add cross-AZ hops that a direct client-to-S3 path never pays for.

Meanwhile, the blob store is already built for this job. S3 and its peers accept uploads from anywhere on the internet, scale to enormous aggregate throughput, and store objects with very high durability: S3 is designed for 99.999999999%, "eleven nines". So the fix is to get your servers out of the byte path. Keep them in the decision path: who may upload, what, how big, and where it goes.

The same reasoning explains why large blobs don't belong inside the database either. A 100 MB value in a relational row bloats pages, slows backups and replication, wastes the buffer cache, and makes every replica carry it. A common rule of thumb: if it's larger than a few megabytes and you never run SQL predicates over its bytes, it belongs in object storage, with a pointer in the database. The prerequisite page Object Storage and Blob Storage covers how those stores work inside.

How It Works#

The core move is to separate the control plane from the data plane:

  • Control plane: small JSON requests to your API. They carry authentication, authorisation, validation, metadata writes, and URL signing.
  • Data plane: large byte streams. Uploads go between the client and the blob store; downloads go between the client and the CDN, which pulls from the blob store.

Everything else in this pattern is a refinement of the right-hand side. Each refinement has to answer one of these questions:

  • How is the URL made safe?
  • How do huge files and broken connections work?
  • How do we avoid storing the same bytes twice?
  • How does the database learn what really happened?
  • How are downloads made fast and private?

Why not route blobs through app servers#

The opening section listed the symptoms. Here is the reasoning in one sentence: application servers are scarce, stateful-while-busy and frequently replaced, while blob stores are vast, stateless to the client and built to absorb bytes. Every second a byte spends in your fleet is a second of capacity you are paying for, and a second during which a deploy can destroy it.

There are still legitimate reasons to proxy, and naming them shows judgement:

  • Small payloads. For a 200 KB profile picture or a 1 MB CSV, one request through the API is simpler than a two-step presign flow. The overhead is negligible, and you validate inline.
  • Inline transformation or inspection that must happen before storage. Examples: stripping EXIF GPS data before the original is ever written, encrypting client data with a key the storage provider must never see, or a regulated environment where every byte must pass through a data-loss-prevention scanner. Even here, a separate dedicated ingest tier is usually better than your general API servers.
  • Clients that cannot speak to the blob store. Old devices, locked-down networks that only allow your domain, or protocols such as SFTP and AS2 that partners insist on. A gateway service terminates those and writes to the blob store.

Why not route blobs through app servers, in depth#

Streaming versus buffering. A well-written proxy streams: it reads a chunk from the client socket and writes it to the storage socket, keeping only a small buffer. A badly written one, such as a framework that parses the whole multipart form into memory, holds the entire file. At 1,000 concurrent 100 MB uploads, buffering means 100 GB of RAM. Streaming fixes memory but not connection time, bandwidth, or deploy fragility.

Backpressure couples the two sides. When streaming, the proxy can only write to storage as fast as the client sends, and only read from the client as fast as storage accepts. A slow mobile client pins a server slot for the whole transfer. With thousands of slow clients you exhaust connection slots long before CPU. This is the same slow-client problem that pushed web servers to event-driven designs, and it is why buffering reverse proxies exist in front of application servers.

The bandwidth bill. Suppose a photo app ingests 300 TB a day, which is 100 million photos at 3 MB. Proxied, the fleet moves 600 TB a day of internal traffic: 300 TB in and 300 TB out. At an average of about 3.5 GB/s, peaking around 3× that, the bytes alone need dozens of hosts with 10–25 Gbit/s network interfaces. With direct upload, the API handles about 1,200 tiny requests per second on average, and two or three ordinary instances cope.

Failure semantics. With a proxy, "the upload failed" can mean many things: the client to proxy leg broke, the proxy to storage leg broke, the proxy crashed, or the storage write succeeded but the response was lost. Each needs different cleanup. With direct upload, the client talks to one endpoint whose semantics are documented. A PUT either produced an object or it didn't, and S3 has been strongly consistent for reads after writes since December 2020. Parts of a multipart upload are individually acknowledged.

Presigned upload and download URLs#

A presigned URL is an ordinary HTTPS URL to an object in the blob store, with extra query parameters:

  • who signed it (the access key or credential scope);
  • when it was signed;
  • how long it is valid for;
  • which headers are bound to it;
  • a cryptographic signature over all of the above, plus the HTTP method and the object key.

Anyone holding the URL can perform exactly that one operation, such as PUT to uploads/u_42/9f3c.jpg, until it expires. They need no cloud credentials of their own.

The key facts:

  • The server signs locally. Generating a presigned URL is a pure computation with the server's credentials, using HMAC-SHA256 for AWS Signature Version 4. There is no network call to S3, so it takes microseconds and can't fail because S3 is slow.
  • The blob store verifies. When the request arrives, S3 recomputes the signature from the request and its own copy of the secret, and checks the expiry. If any signed element differs, such as a different key, method or bound header, verification fails with 403 SignatureDoesNotMatch.
  • Permissions are the signer's. The URL carries the permissions of the identity that signed it, intersected with what the signature covers. If the signing role can't write to the bucket, neither can the URL. If the signing credentials are temporary (an STS session), the URL stops working when they expire, even if its stated expiry is later.
  • Expiry is bounded. For SigV4, S3 accepts a maximum validity of 7 days. In practice, use minutes: 5–15 minutes for uploads (time to start the transfer; an upload already in progress isn't cut off at expiry), and minutes to an hour for downloads.

Upload variants.

  • Presigned PUT. The client sends the raw bytes as the body. It is simple and works from browsers via fetch, from mobile and from CLIs. The signature can bind headers such as Content-Type, so the client must send exactly that value. It can also bind a checksum header, such as x-amz-checksum-sha256 or Content-MD5, so S3 rejects bytes that don't match the hash the client declared. A PUT presign cannot express "any size up to 50 MB". You can bind Content-Length to an exact value, or check the size after upload.
  • Presigned POST (browser form upload) with a policy. The server signs a JSON policy document listing conditions, such as the bucket, a key prefix (starts-with $key uploads/u_42/), content-length-range (minimum and maximum bytes), allowed content types and the expiry. The browser submits a multipart form directly to S3. This is how you enforce a size range at the storage edge. GCS supports a similar policy-document POST. Azure has no direct equivalent, but its SAS tokens can scope permissions and expiry.
  • Presigned multipart. One signed URL is issued per part of a multipart upload. See the next section.

Download variants.

  • Presigned GET from the bucket. This is fine for private, infrequently accessed files, such as a user downloading their own invoice PDF. You can override response headers in the signature, for example response-content-disposition=attachment; filename="invoice.pdf", so the browser downloads the file rather than rendering it.
  • Signed CDN URLs or cookies. These are the right default for anything read often or read globally. See the CDN section below.
  • Public CDN URLs for truly public assets, such as product images and the public videos of a site. These need no signatures. You still keep the bucket itself private and let only the CDN read it.

Presigned URLs, in depth#

The server chooses the key. Never let the client pick the object key. Otherwise a malicious client can overwrite another user's file or plant objects under paths your code trusts. Generate keys server-side, typically tenant/user/uuid or a content hash. Store the user's original filename only as metadata. Randomised keys also avoid enumeration: a guessable key like /invoices/1001.pdf invites scraping, if the object is ever readable.

What a URL can and cannot constrain.

ConstraintPresigned PUTPresigned POST policyCheck after upload
Exact keyyesyes, or a key prefixn/a
HTTP methodyesPOST onlyn/a
Expiryyesyesn/a
Content-Type valueyes, signed headeryes, exact or prefixverify actual bytes (magic numbers)
Size rangeexact length onlyyes, content-length-rangeHEAD the object
Checksum of bytesyes, signed checksum headerpartly, via form fieldscompare stored checksum
Malware-freenonoscan in processing

Content-Type is a claim, not a fact. A client can declare image/png and send an executable. Always validate the real bytes after upload, by sniffing magic numbers and decoding with a hardened library, before you trust or serve the file.

Revocation is hard. A presigned URL can't be "unissued". To kill outstanding URLs you must:

  • rotate or disable the signing credentials (which kills every URL they signed);
  • tighten a bucket policy, for example denying requests whose signature is older than N seconds, using the s3:signatureAge condition key;
  • or delete or move the object.

That's why short expiries matter: a 10-minute URL that leaks is a 10-minute problem.

Leak surfaces. Signed URLs are bearer tokens. They leak through:

  • browser history;
  • Referer headers when a page links elsewhere;
  • server and CDN logs;
  • analytics tools that record full URLs;
  • messages users copy and paste.

To limit the damage:

  • prefer short download expiries;
  • set Referrer-Policy;
  • avoid logging query strings;
  • for long-lived access to many files, use signed cookies instead.

Browser uploads need CORS. A browser PUT to bucket.s3.amazonaws.com from app.example.com is a cross-origin request. The bucket must have a CORS rule that allows your origin, the PUT method, and the headers you sign. It must also expose ETag if the client needs it for multipart. A missing CORS rule is the most common reason a presigned upload "works in curl but not in the browser".

Where the URL is generated. The signing service needs credentials with write access to the upload prefix, and only that. Use a dedicated IAM role scoped to arn:aws:s3:::bucket/uploads/*, separate from roles that can read processed media or delete anything. If an attacker compromises the presign endpoint, they can upload junk but not read or destroy user data.

Multipart and resumable uploads#

A single PUT is all-or-nothing. Suppose a 4 GB upload over a mobile link dies at 99%. The 3.96 GB already sent is wasted, and the user starts again, perhaps on the same flaky link. Two related mechanisms fix this.

Multipart upload (S3 terminology, also in GCS's XML API and Azure block blobs). The file is split into numbered parts, which are uploaded independently and in any order, often in parallel. A final call then stitches them into one object. S3's flow has four calls:

  1. CreateMultipartUpload returns an UploadId.
  2. UploadPart is called once per part, with a PartNumber from 1 to 10,000. Each part except the last must be at least 5 MiB, and none may exceed 5 GiB. Each successful part returns an ETag.
  3. CompleteMultipartUpload takes the list of (PartNumber, ETag) pairs. S3 assembles the object atomically. Before this call, the object does not exist for readers.
  4. AbortMultipartUpload discards the parts. ListParts tells you which parts S3 already has, and is the key to resuming.

A single S3 PUT is limited to 5 GB. Beyond that, multipart is mandatory; above about 100 MB, AWS recommends it anyway. Over the long-standing limits, the maximum object size is 5 TiB, which is 10,000 parts of up to 5 GiB.

Resumable upload. Resuming means: after a failure, find out what the server already has, then send only the rest. There are three common shapes:

  • S3 multipart resume. Keep the UploadId. After a crash, call ListParts (or rely on your own record of completed part numbers and ETags), then upload only the missing parts and complete. The granularity of loss is one part. With 16 MiB parts, a dropped connection wastes at most 16 MiB per in-flight part.

  • Google Cloud Storage resumable uploads.

    • The client (or your server) starts a resumable session and gets back a session URI. The URI is itself a bearer credential, valid for up to a week.
    • The client PUTs chunks with a Content-Range: bytes start-end/total header. Chunks must be multiples of 256 KiB, except the last.
    • After an interruption, the client sends an empty PUT with Content-Range: bytes */total. The response is 308 Resume Incomplete, and its Range header says how many bytes were persisted. The client continues from there.

    Unlike S3 multipart, the bytes are a single sequential stream, so there is no parallelism within one session.

  • The tus open protocol (tus.io) for resumable uploads over HTTP, often used when uploads go to your own ingest servers or a vendor that speaks it:

    • POST creates an upload and returns its URL.
    • PATCH with an Upload-Offset header appends bytes.
    • HEAD returns the current Upload-Offset for resuming.

    Client libraries exist for browsers, iOS, Android and more. Server implementations such as tusd can write the result to S3 or GCS. Vimeo is a well-known adopter.

Choosing the part size.

  • Too small means many requests. Each part costs a round trip, request overhead and a request charge, and you may hit the 10,000-part cap.
  • Too large means more work lost per failure, and more memory if you buffer parts.

The cap sets a floor. For a file of size F, the part size must be at least F / 10,000. For a 1 TiB file that is about 105 MiB per part. For typical consumer uploads (100 MB–10 GB), 8–64 MiB parts are a good range. On mobile, smaller parts (5–8 MiB) reduce waste on flaky links.

Parallelism and throughput. A single TCP connection's throughput is bounded by roughly (window size) / RTT. It also drops sharply under packet loss: the Mathis model says throughput is roughly proportional to MSS / (RTT × √loss). Sending 4–8 parts at once spreads the transfer over several connections. That often multiplies throughput on high-latency or lossy paths, until the client's uplink is saturated.

For server-side bulk transfers, such as backups from a data centre, dozens of parallel parts are common. S3's per-prefix request rate (at least 3,500 writes per second per partitioned prefix) is rarely the bottleneck for a single file. For mobile clients, cap parallelism at 2–4: more parallel connections compete with each other and with the user's other apps.

Integrity per part. Send a checksum with each part, such as Content-MD5 or one of the newer x-amz-checksum-* headers (CRC32, CRC32C, SHA-1, SHA-256), so corruption is caught per part. S3 rejects a part whose bytes don't match. A multipart object's ETag is not the MD5 of the whole file. It is commonly computed as the MD5 of the concatenated part digests, with a -N suffix giving the part count. So for end-to-end verification, rely on full-object checksums or your own content hash, not the ETag.

Abandoned uploads cost money. Parts of a multipart upload that is never completed or aborted are stored and billed indefinitely, but they are invisible in normal listings. Always configure a lifecycle rule such as AbortIncompleteMultipartUpload after 1–7 days. In your own tables, give every upload session an expires_at, and run a sweeper that aborts expired sessions.

Multipart and resumable uploads, in depth#

Where the client stores resume state. A browser stores the UploadId, the file's identity (name, size, last-modified time, and ideally a hash of its first few MiB) and the list of completed parts in localStorage or IndexedDB. A mobile app stores the same in its local database. On app restart, it matches the file to the saved session and resumes.

Mobile platforms add a twist. iOS background URLSession transfers and Android WorkManager continue uploads while the app is suspended. They work best with one file per request, so apps often write each part to a temporary file and enqueue one background task per part.

The server's view: an upload session table.

ColumnPurpose
upload_idProvider's multipart ID or session URI
file_idLinks to the file's metadata row
part_size, total_partsFixed at creation, so presigned part URLs can be reissued
parts_doneBitmap or count, updated optionally (ListParts is the source of truth)
expires_atWhen the sweeper aborts the upload
statusactive, completing, completed, aborted

Re-issuing URLs. Part URLs expire. A 4 GB upload on a slow link may take an hour, so issue URLs lazily, for example in batches of 20 parts, or on request for each part. Don't sign all 10,000 up front with a long expiry.

Completion is a commit point. CompleteMultipartUpload is the moment the object becomes visible. Call it from your server, not the client, if you want to validate the part list and the declared size first. If the call itself times out, it is safe to retry with the same part list: S3 treats completing an already-completed upload as success, or you can verify with a HEAD. This is one more place where idempotency is what makes retries safe.

Downloads resume too. HTTP Range requests (Range: bytes=1048576-) return 206 Partial Content. Blob stores and CDNs support them, so download managers resume and split big files into parallel ranges. Video players rely on ranges, or on segmenting (HLS/DASH), to seek without downloading everything. Use If-Match with the ETag so a resumed download fails cleanly if the object changed in between.

Chunking and dedupe by hash#

Multipart upload splits a file into parts to transfer it. Chunking splits a file into pieces to store and identify it. Each chunk is addressed by a cryptographic hash of its content, such as SHA-256. That content addressing unlocks three big wins.

  1. Deduplication. If two users upload the same 1 GB file, or one user uploads it twice, the chunks already exist. The client asks "which of these hashes do you lack?" and uploads only those. Storage and bandwidth drop sharply for popular content and for repeated backups.
  2. Delta sync. When a user edits 1 MB in the middle of a 2 GB file, only the chunks covering the edit change. The client re-hashes, finds the few new chunks and uploads just those. This is the heart of file-sync products such as Dropbox.
  3. Integrity for free. A chunk's name is its hash, so corruption is detectable on every read: re-hash and compare.

Fixed-size chunking cuts at every N bytes: 4 MiB, say. It is simple and fast, and it works well for files that change in place (databases, VM images) and for whole-file dedupe. Dropbox's public API, for instance, defines a file's content_hash as follows: split the file into 4 MiB blocks, SHA-256 each block, then SHA-256 the concatenation of those digests.

Fixed-size chunking has one famous weakness, the boundary-shift problem. Insert one byte at the start of a file, and every later chunk boundary moves by one byte. Every chunk's hash changes, and dedupe drops to zero.

Content-defined chunking (CDC) fixes this. Boundaries are chosen by the content itself:

  1. Slide a small window, for example 48 bytes, across the data.
  2. Compute a rolling hash of the window. A Rabin fingerprint or a gear hash can be updated in O(1) per byte.
  3. Declare a boundary wherever the hash's low k bits are all zero.

Boundaries then depend only on nearby bytes. After an insertion, boundaries re-synchronise within a chunk or two, and all later chunks keep their old hashes. Chunk sizes average about 2^k bytes, with minimum and maximum limits.

The idea was popularised by the Low-Bandwidth Network File System (LBFS), from Muthitacharoen, Chen and Mazières at SOSP 2001. It used Rabin fingerprints over a 48-byte window, with an expected chunk size of 8 KB. Backup tools such as restic and Borg use CDC, as do many dedupe storage systems. FastCDC (Xia et al., USENIX ATC 2016) made it much faster, using a gear hash and "normalised" chunking that tightens the size distribution.

Exact dedupe for crawlers and pipelines. Content hashing isn't only for user files. A web crawler fetching billions of pages finds that a large share are exact duplicates under different URLs: mirrors, tracking parameters, printer-friendly views. The straightforward, strong solution:

  • Hash each page's content.
  • Store the hash in the metadata DB's URL or page table, with an index on the hash column.
  • Before processing a page, look up its hash, and skip the page if it's already present.

Some worry that a huge index slows writes. For most systems that worry is overstated, because modern databases handle large B-tree indexes well. A 10-billion-row hash index is roughly 10¹⁰ × about 50 bytes, or 500 GB, so it is sharded. The usual alternative is a Bloom filter of seen hashes, for example in Redis with the RedisBloom module (BF.ADD, BF.EXISTS):

  • Size. For n = 10 billion items at a 1% false-positive rate, the filter needs m = −n ln p / (ln 2)² ≈ 10¹⁰ × 4.6 / 0.48 ≈ 9.6 × 10¹⁰ bits, about 12 GB, with k ≈ 7 hash functions.
  • False positives. A false positive means skipping a page that was not a duplicate. That is an acceptable loss for a crawler, but not for a file store, where skipping an upload would lose data.
  • Choice. It's elegant, but the indexed column is simpler and exact, and is usually the better default. Probabilistic Data Structures covers the maths in depth.
  • Near-duplicates. Near-duplicate detection (the same article with a different ad block) needs similarity hashing. Charikar's SimHash (STOC 2002) was applied at web scale by Manku, Jain and Das Sarma ("Detecting Near-Duplicates for Web Crawling", WWW 2007), using 64-bit fingerprints and a small Hamming-distance threshold.

Chunking and dedupe, in depth#

Where to dedupe.

  • Client-side (source) dedupe: the client hashes and asks the server which hashes it lacks. It saves upload bandwidth, which is the scarce resource for consumers.
  • Server-side (target) dedupe: the server hashes after receipt. It saves only storage.

File-sync and backup products do client-side dedupe. Object stores generally do neither, and leave it to you.

Cross-user dedupe leaks information. If the server answers "already have it" for a hash, an attacker can test whether anyone has stored a particular file. Examples: a leaked document, or a template with one variable field, such as a salary letter, where the attacker tries every plausible value. Harnik, Pinkas and Shulman-Peleg described these side channels (IEEE Security & Privacy, 2010).

A related abuse: knowing a file's hash lets someone "upload" the hash and claim a file they never had. That turns the service into a content-distribution channel. Tools exploiting this in a consumer sync service surfaced around 2011.

There are three mitigations:

  • Dedupe only within a user or tenant. This is the most common choice.
  • Proof of ownership. The server challenges the client to hash random ranges of the file, which proves it has the bytes, not just the hash.
  • Add per-user randomness, such as always uploading the first chunk, which disables cross-user dedupe for small files.

Reference counting and garbage collection. With dedupe, deleting a file can't simply delete its chunks, because other files may share them. You need either:

  • reference counts per chunk, updated transactionally with file versions; or
  • mark-and-sweep GC, which periodically marks every chunk reachable from a live file version and deletes unmarked chunks older than a grace period.

Mark-and-sweep is slower, but it is robust to the bugs that corrupt reference counts. The grace period protects chunks that were uploaded but not yet committed, which the sequence above shows can happen.

Chunk size versus metadata. Smaller chunks dedupe better but multiply metadata:

  • A 1 PB store with 4 MiB chunks has about 2.7 × 10⁸ chunks.
  • With 8 KB CDC chunks it has about 1.3 × 10¹¹: a 32-byte hash plus a location for each is several terabytes of index.

That's why consumer sync tools pick megabyte-scale blocks, while backup systems use kilobyte-scale CDC and accept a larger index.

Metadata DB plus blob store#

Blob stores are excellent at holding bytes under a key, and poor at everything else you need:

  • "all files owned by user 42, newest first";
  • "files shared with this team";
  • "total bytes per tenant";
  • "is this file approved for display?"

So every real system pairs the store with a metadata database, such as PostgreSQL, MySQL, DynamoDB or Cassandra. The database row is the source of truth for what the application believes exists. The blob store is the source of truth for the bytes.

Simple apps, such as Instagram-style photo storage, need only FILE (plus DERIVATIVE for thumbnails and sizes), with one blob per file. Sync and backup products add versions and chunks. Keep blob keys opaque and immutable. A "rename" changes display_name, never the key. A new version writes a new key; it never overwrites the old one. Immutable keys make CDN caching trivial, because a key never changes meaning, and they make concurrent edits safe. Upload sessions live in the separate table described in the multipart section.

The status lifecycle is a small state machine. It is the same idea as Multi-Step Processes, applied to one file.

A Failed file is not a dead end: an operator, or an automated redrive, can send it back to Processing once the cause is fixed. The diagram leaves that edge out for clarity.

State synchronisation challenges#

You now have two systems with no shared transaction: a database and a bucket. Every failure mode is a way for them to disagree.

SituationHow it happensSymptomFix
Dangling metadataRow created, upload never happened (user closed the tab)pending rows forever; UI shows a broken fileExpiry on pending rows plus a sweeper that marks them expired
Orphan blobBytes landed, but the "complete" call or event was lost; or the DB insert came after the upload and failedStorage you pay for that nobody can seeEvent-driven reconciliation, plus periodic inventory diff (S3 Inventory vs DB)
Lying clientClient says "done" without uploading, or uploads a different sizeRow says ready, object missing or wrongNever trust the client: verify with HEAD (size, checksum) or the storage event
Delete half-doneRow deleted, blob delete failed (or the reverse)Orphan bytes, or a row pointing at nothingSoft delete the row, then async blob delete with retries; hard-delete the row last
Double processingStorage event delivered twiceTwo thumbnails jobs, double quota chargeIdempotent handlers keyed by object key + version/ETag

Ordering rule: write the metadata row first, as pending, before issuing the URL. That way, any object in the upload prefix has a row that explains it. The worst case is an expired pending row, which is cheap and visible. Writing the row after the upload risks orphan blobs whenever the second write fails.

Confirming completion: client callback versus storage events. There are two ways to learn that an upload finished:

  1. The client calls POST /files/id/complete after the PUT succeeds. It is fast, simple and gives immediate UI feedback. But clients crash between the PUT and the callback, and malicious clients lie. If you use it, the server must still HEAD the object to confirm its size and checksum.
  2. The blob store emits an event: S3 Event Notifications to SQS, SNS, Lambda or EventBridge; GCS Pub/Sub notifications; Azure Event Grid. A worker consumes it and marks the row uploaded. This is trustworthy, because it comes from the storage system itself, and it fires even if the client disappears. But delivery usually takes seconds, and is at-least-once.

The robust answer is both: the callback for responsiveness, the event as the guarantee, with handlers idempotent so whichever arrives second is a no-op. Add a periodic reconciliation job that compares a storage inventory, such as S3 Inventory reports or a ListObjectsV2 scan of a prefix, against the database. It catches the rare lost event.

Storage event semantics to design for.

  • Delivery is at-least-once. Duplicates happen.
  • Events for different objects can arrive out of order, and even events for the same key can. S3 includes a sequencer value in each event so consumers can order events for the same key.
  • Delivery is usually fast but not instant. Usually seconds, occasionally longer.
  • The event says the bytes exist, not that they are valid. Validation is a processing step.

Post-upload processing via events#

Almost every upload needs work afterwards:

  • virus and malware scanning;
  • type validation;
  • thumbnails and resized variants;
  • video transcoding into adaptive bitrates;
  • OCR or text extraction for search;
  • content moderation;
  • EXIF stripping;
  • indexing;
  • notifying followers.

Doing this in the upload request is the proxy mistake all over again. Instead, the storage event starts an asynchronous pipeline. This is a specialisation of Managing Long-Running Tasks.

The design points:

  • Quarantine first. Uploads land in a prefix or bucket that is never served directly. Only after validation and scanning are objects copied, or derivatives written, to the serving location. A malicious file uploaded at 10:00 can't be shared publicly at 10:01.
  • Use a queue between events and workers. Use the queue's retries, visibility timeouts and dead-letter queue rather than processing inside a notification Lambda with no backpressure. For heavy fan-out, such as video, use an orchestrated workflow: one job per rendition, with joins.
  • Make every step idempotent, keyed by (storage_key, version or ETag, step). Duplicate events and retries are normal.
  • Write derivatives to deterministic keys, such as media/{file_id}/w640.webp, so a re-run overwrites with identical content rather than creating duplicates.
  • Report progress back. The client sees processing, then ready, via polling GET /files/id, or a push over SSE or WebSocket (see Real-time Updates).

Video is the heavy case. YouTube has publicly cited more than 500 hours of video uploaded every minute. A typical pipeline:

  1. Split each upload into segments of a few seconds.
  2. Transcode the segments in parallel into a ladder of resolutions and bitrates, for example 240p to 4K, with H.264, VP9 or AV1 codecs.
  3. Package them as HLS or DASH.
  4. Publish the manifest.

Parallel segment transcoding turns a one-hour encode into minutes, given enough workers. Design a Video Streaming Platform covers it end to end.

CDN delivery with signed URLs#

Downloads usually outnumber uploads, by 10:1 to over 1,000:1 for popular media. Serving them straight from the bucket has three costs:

  • every read pays the store's request and egress price;
  • reads travel to a single region;
  • latency for far-away users is 100–300 ms per round trip.

A CDN caches objects at edge locations near users. A cache hit is often served in tens of milliseconds. Offloading 95% or more of requests from the origin is typical for popular media. Content Delivery Networks covers the mechanics.

Making private content cacheable. The tension is that a CDN wants to cache once and serve to everyone, while private content must be served only to authorised users. Signed CDN URLs resolve it:

  • Authorisation happens at your API. It checks that the user may see the file and returns a URL signed with the CDN's key. CloudFront signed URLs use an RSA or ECDSA key pair whose public half you register with CloudFront. Cloud CDN signed URLs use an HMAC key. Azure offers token-based authentication on some tiers.
  • Verification happens at the edge, with no call to your servers: the signature, the expiry, and optionally the client IP or path.
  • The cached object is shared. CDNs exclude the signature parameters from the cache key, so many users' differently signed URLs for the same object hit the same cached copy.
  • The bucket is closed to everyone else. In AWS, CloudFront's Origin Access Control lets the bucket policy allow reads only from that distribution. Users can't bypass the CDN to fetch directly from S3.

Signed cookies for many files. An HLS video consists of a manifest plus hundreds of segment files. Signing every segment URL is painful, and it breaks players that build segment URLs themselves. Instead, set a signed cookie with a policy, such as "any object under /videos/abc/* until 18:00", and the browser sends it on every segment request. CloudFront and Cloud CDN both support signed cookies.

Choose expiry by content type.

  • Download links: minutes.
  • Video sessions: the length of the video plus a buffer.
  • Image grids in a feed: around an hour.

Long enough to avoid mid-session failures, short enough that leaked links die. Some CDNs can also bind a signature to an IP range, which helps for high-value content but breaks for mobile users switching networks.

Fast downloads beyond caching.

  • Use immutable, versioned keys (media/abc/v3/w640.webp) with Cache-Control: public, max-age=31536000, immutable. Edges and browsers then never revalidate, and an update is just a new URL.
  • Use an origin shield (a regional mid-tier cache) to collapse misses from many edges into one origin fetch.
  • Serve the right size. Responsive images (srcset) and modern formats (WebP, AVIF) can cut bytes by half or more versus JPEG at similar quality. For video, adaptive bitrate streaming lets the player switch quality per segment as bandwidth changes.
  • Support range requests, so large downloads can be resumed and fetched in parallel, and video can seek.
  • Pre-warm or push for predictable spikes, such as a launch trailer. Multi-CDN setups add resilience for the largest services.

Preventing abuse#

Presigned URLs give strangers on the internet write access to your storage. Here is how to keep that safe.

  • Authenticate and rate-limit the presign endpoint. It is the gate. Limit URLs per user per minute, and outstanding pending uploads per user. See Rate Limiting.
  • Enforce size at every layer you can:
    • a declared size at presign, checked against quota;
    • a content-length-range POST policy, or an exact signed length;
    • a post-upload HEAD;
    • a quota charged only when the upload is confirmed.
  • Bind type and checksum in the signature, then verify the real content after upload. Allow-list types, sniff magic bytes, re-encode images, and never execute or render untrusted files on your main origin.
  • Scan for malware before anything is shared. Commercial and open-source scanners (for example ClamAV) run as a processing step.
  • Moderate content where users can share publicly: perceptual-hash matching against known-bad lists, plus classifiers and human review.
  • Serve user content from a separate domain, such as usercontent.example.net, never app.example.com. Then a malicious HTML or SVG file can't run script with your app's cookies. Add Content-Disposition: attachment for types that shouldn't render inline, and X-Content-Type-Options: nosniff. Large providers serve user content from a separate domain for exactly this reason.
  • Use short expiries, scoped keys, and least-privilege signing roles. And keep lifecycle rules for quarantine prefixes, so rejected or abandoned bytes disappear.

Cloud provider terminology#

The same ideas go by different names on each cloud.

ConceptAWSGoogle CloudAzure
Object storeS3 bucketCloud Storage bucketBlob Storage container
Temporary scoped URLPresigned URL (SigV4)Signed URL (V4)Shared Access Signature (SAS)
Browser form upload with policyPresigned POSTPolicy document POSTn/a (SAS on PUT)
Chunked uploadMultipart upload (parts)Resumable upload (session URI); XML API multipartBlock blob: Put Block + Put Block List
Upload eventsS3 Event Notifications, EventBridgePub/Sub notifications, EventarcEvent Grid
CDNCloudFrontCloud CDN, Media CDNAzure Front Door / Azure CDN
Private CDN-to-bucket accessOrigin Access ControlPrivate origin authenticationPrivate Link / managed identity
Signed CDN accessSigned URLs, signed cookiesSigned URLs, signed cookiesToken authentication (tier-dependent)
Lifecycle cleanupLifecycle rules, AbortIncompleteMultipartUploadObject Lifecycle ManagementLifecycle management policies

Azure block blobs are assembled from up to 50,000 blocks, each uploaded with Put Block under a block ID, then committed in order with Put Block List. That is the same staged-then-commit idea as S3 multipart.

Worked example: a photo and video sharing app#

Requirements:

  • 50 million daily active users.
  • 100 million photo uploads a day at an average of 3 MB (after client-side compression).
  • 2 million video uploads a day at an average of 200 MB.
  • Feeds are read heavily: each user views about 200 images a day.

Upload load.

  • Photos: 100M × 3 MB = 300 TB/day. That averages 1,160 uploads/s; with a 3× peak, about 3,500/s.
  • Videos: 2M × 200 MB = 400 TB/day, averaging about 23 uploads/s. They need multipart: 200 MB / 16 MiB ≈ 12 parts each, so about 280 part-PUTs/s on average.
  • Ingest total: about 700 TB/day, roughly 8 GB/s on average, or 65 Gbit/s, and around 200 Gbit/s at peak.

Proxying that would need a dedicated network-heavy fleet. Direct upload sends it straight to the blob store, which absorbs it by design.

API load. About 3,500 presign requests per second at peak, plus completions, plus video part-URL batches. Each is a small JSON request with one metadata insert. Ten modest API instances and a sharded or managed database handle this comfortably. The metadata DB takes about 3,500 inserts/s and about 7,000 status updates/s at peak, which is well within a few sharded PostgreSQL primaries or one DynamoDB table.

Processing.

  • Each photo yields 4 variants (thumbnail, 320, 640, 1080 widths), so 400M derivative writes a day. At about 50 ms of CPU each, that is 100M × 4 × 0.05 s ≈ 2 × 10⁷ CPU-seconds a day, about 230 cores on average and about 700 at peak.
  • Video transcoding dominates. Assume 2M videos × 5 renditions, at roughly 1 CPU-minute per rendition per minute of video, with videos averaging 4 minutes. That is about 4 × 10⁷ CPU-minutes a day, around 28,000 cores busy on average. This is why video platforms invest in hardware encoders and accelerators.

Download load.

  • 50M users × 200 images × about 100 KB (feed-sized variant) = 1 PB/day, about 93 Gbit/s on average.
  • At a 97% CDN hit rate, origin egress is about 3% of that: 30 TB a day, or roughly 0.9 PB a month.

The CDN carries the rest. Images use immutable keys and year-long cache headers. Private posts use signed URLs with a one-hour expiry, embedded in the feed response.

Both "Metadata DB" boxes are the same database, drawn twice to keep the picture readable. Not shown: the sweeper and inventory reconciler, which run periodically against both the metadata DB and the object store.

When to Use It#

Use direct-to-storage transfers whenever any of these hold:

  • Files are larger than a few megabytes, or arrive in high volume: photos, video, audio, documents, datasets, logs, backups, ML artefacts.
  • Clients are on mobile or unreliable networks, and uploads must survive drops and app restarts. That calls for multipart or resumable uploads.
  • Downloads are frequent or global, so CDN delivery cuts latency and cost.
  • Files must be private but still fast: signed CDN URLs or cookies.
  • The same content is likely to be uploaded repeatedly (backups, sync clients, crawled pages), so content hashing and dedupe save bandwidth and storage.
  • Uploads trigger heavy processing (transcoding, scanning, ML inference) that must be decoupled from the request.

Typical interview prompts that need this pattern:

  • Dropbox / Google Drive: chunked, deduplicated, resumable sync with a metadata DB.
  • YouTube / Netflix: multipart video upload, transcoding pipeline, adaptive streaming over a CDN.
  • Instagram: photo upload with variants, feed images over a CDN.
  • WhatsApp or Slack attachments: presigned uploads, signed expiring downloads.
  • Web crawler: raw page blobs in object storage, content hashes in the metadata DB.
  • ChatGPT file uploads, or a log-ingest system.

When NOT to Use It#

  • Small payloads. For a 50 KB avatar or a 500-byte JSON document, one ordinary API request is simpler, and the two-step flow is pure overhead. For small structured values, use database columns or a document store.
  • You must transform or inspect every byte before it is stored, for compliance reasons, and the provider's server-side options (encryption with your own key, object lambdas, quarantine-then-scan) can't satisfy the rule. Use a dedicated ingest service that streams, not your general API.
  • Data that must be queried, not just stored. Analytics rows belong in a warehouse or lakehouse (Parquet in object storage, queried by an engine), not in opaque blobs behind a metadata row. That's a different pattern.
  • Interview scope. If the problem has no large files, don't introduce presigned URLs to sound sophisticated. If it does, a sentence about presigned URLs plus CDN may be all the interviewer needs, unless they ask for depth on resumability or dedupe.

How to Implement It#

  1. Split the API into control-plane endpoints:

    • POST /uploads (request a URL);
    • POST /uploads/:id/complete (optional callback);
    • GET /files/:id (status and metadata);
    • GET /files/:id/download (a signed URL).

    No endpoint accepts file bytes.

  2. Create a metadata row first, with status pending, a server-generated key, the declared size, type and SHA-256, and an expires_at timestamp. Check the quota here.

  3. Sign narrowly: one key, one method, a short expiry, bound Content-Type, and a checksum header. Use a POST policy when you need a size range. Sign with a role that can only write to the upload prefix.

  4. Use multipart above about 100 MB (or a few MB on mobile). Issue part URLs in batches, persist the session, and add an AbortIncompleteMultipartUpload lifecycle rule.

  5. Subscribe to storage events. Feed them into a queue, and have an idempotent worker HEAD and verify each object before marking it uploaded. Keep the client callback for fast UI, and treat it as a hint.

  6. Run processing asynchronously from the quarantine prefix: validate, scan, build derivatives, then mark ready. Push status to the client.

  7. Serve through a CDN. Keep the bucket private, use origin access control, signed URLs or cookies for private content, immutable keys, and long Cache-Control.

  8. Reconcile. Run sweepers for expired pending rows and soft-deleted files, and a periodic inventory diff to find orphan objects.

  9. Add content hashing if dedupe or sync matters: fixed 4 MiB blocks for sync, CDC for backup-style workloads, and a hash index in the metadata DB.

Here is a presign endpoint in TypeScript with AWS SDK v3. It generates a server-chosen key, binds type and checksum, and sets a short expiry:

import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { randomUUID } from 'node:crypto';
 
const s3 = new S3Client({ region: 'us-east-1' });
const ALLOWED = new Set(['image/jpeg', 'image/png', 'image/webp', 'video/mp4']);
const MAX_BYTES = 200 * 1024 * 1024; // larger files must use multipart
 
export async function createUpload(userId: string, req: { type: string; size: number; sha256: string }) {
  if (!ALLOWED.has(req.type)) throw new HttpError(415, 'type not allowed');
  if (req.size <= 0 || req.size > MAX_BYTES) throw new HttpError(413, 'use multipart');
  await quotas.reserve(userId, req.size);                // fails if over quota
 
  const fileId = randomUUID();
  const key = `uploads/${userId}/${fileId}`;             // never client-chosen
  await db.files.insert({ id: fileId, ownerId: userId, key, status: 'pending',
    declaredSize: req.size, contentType: req.type, sha256: req.sha256,
    expiresAt: new Date(Date.now() + 30 * 60_000) });
 
  const url = await getSignedUrl(s3, new PutObjectCommand({
    Bucket: 'media-quarantine', Key: key,
    ContentType: req.type,                               // client must send exactly this
    ContentLength: req.size,                             // exact length is signed
    ChecksumSHA256: req.sha256,                          // base64 SHA-256; S3 rejects mismatches
  }), { expiresIn: 600 });                               // 10 minutes to start the PUT
 
  return { fileId, url, headers: { 'Content-Type': req.type,
    'x-amz-checksum-sha256': req.sha256 } };
}
TechnologyFits when
Amazon S3 (+ CloudFront)AWS-native; presigned PUT/POST, multipart up to 10,000 parts, rich events, OAC for private CDN origins
Google Cloud Storage (+ Cloud CDN / Media CDN)GCP-native; resumable sessions for sequential streams, signed URLs and cookies, Pub/Sub notifications
Azure Blob Storage (+ Front Door)Azure-native; SAS tokens, block blobs with staged blocks, Event Grid
Cloudflare R2S3-compatible API with no egress fees, paired with Cloudflare's CDN
MinIO / Ceph RGWSelf-hosted or on-prem S3-compatible storage; air-gapped or data-sovereignty requirements
tus protocol (tusd, Uppy)Cross-platform resumable uploads to your own ingest tier, or when you want one protocol over many backends
Uppy and similar client librariesBrowser uploads with chunking, retries, progress and presigned multipart built in
SQS / Pub/Sub / KafkaBuffering storage events for idempotent workers with retries and DLQs
ClamAV or commercial scannersMalware scanning as a post-upload step
FFmpeg, AWS Elemental MediaConvert, transcoding servicesVideo renditions and HLS/DASH packaging

Trade-offs#

OptionProsConsPick when
Proxy through API serversSimplest; inline validation; one requestBandwidth, timeouts, memory, deploys kill uploads; expensive at scaleFiles under a few MB; strict inline-inspection rules
Presigned single PUTServers out of the byte path; simple clientAll-or-nothing; 5 GB max on S3; no size rangeFiles up to about 100 MB on decent networks
Presigned POST with policyEnforces size range and key prefix at the storeBrowser-form semantics; AWS/GCS-specificBrowser uploads needing hard size limits
Multipart / resumableSurvives drops; parallel; very large filesMore calls and state; orphan parts need cleanupLarge files, mobile clients, long transfers
Fixed-size chunks + hashSimple; good for in-place edits and whole-file dedupeBoundary shift kills dedupe on insertionsFile sync, block-level storage
Content-defined chunksDedupe survives insertions; best savingsCPU for rolling hash; more metadata; variable sizesBackups, versioned archives
Direct bucket download (presigned GET)Simple, privateNo edge caching; single-region latency; request costsRare private downloads (invoices, exports)
CDN with signed URLs/cookiesFast global reads, private content, origin offloadKey management; leaked-link window; cache invalidation for mutable keysFrequently read media, private or public

Common Pitfalls#

  • Letting clients choose object keys. This leads to overwrites, path tricks and enumeration. Always generate keys server-side.
  • Long-lived presigned URLs (days) that leak via logs and referrers. Use minutes for uploads, and short expiries plus signed cookies for media sessions.
  • Trusting the client's "upload done" call or declared Content-Type. Verify size and checksum with HEAD, and validate the real bytes.
  • Forgetting the CORS configuration for browser uploads, or forgetting to expose ETag for multipart.
  • No lifecycle rule for incomplete multipart uploads. Invisible parts accumulate on the bill.
  • Writing metadata after the upload. Lost second writes create orphan blobs. Write pending first.
  • Serving user uploads from your main domain. An uploaded HTML or SVG file becomes stored XSS. Use a separate domain, nosniff, and attachment disposition.
  • Public buckets "for the CDN". Use origin access control so only the CDN can read.
  • Mutable keys behind long cache TTLs. Users see stale images after an edit. Version the keys instead of purging caches.
  • Non-idempotent event handlers. Duplicate S3 events double-charge quota or produce duplicate thumbnails.
  • Signing every HLS segment instead of using signed cookies, or embedding long-lived signed URLs in cached HTML.
  • Cross-user dedupe without thinking about privacy. It lets attackers confirm that a file exists, or claim files by hash.

Real-World Examples#

  • Dropbox splits files into 4 MiB blocks, each identified by SHA-256. That is visible in its public API's content_hash definition. Clients upload only blocks the server lacks. Dropbox moved most of its storage from Amazon S3 onto its own exabyte-scale system, Magic Pocket, which it described publicly in 2016.
  • Facebook's photo storage.
    • "Finding a Needle in Haystack: Facebook's Photo Storage" (Beaver, Kumar, Li, Sobel and Vajgel, OSDI 2010) packs many photos into large append-only files. It keeps each photo's small offset metadata in memory, so a read costs about one disk seek instead of several filesystem metadata lookups.
    • "f4: Facebook's Warm BLOB Storage System" (Muralidhar et al., OSDI 2014) moved older, less-read blobs to Reed–Solomon erasure coding. That cut the effective replication factor from about 3.6 to about 2.1.
  • YouTube reports more than 500 hours of video uploaded per minute. Upload, segment-parallel transcoding and adaptive streaming via a global CDN are the textbook large-blob pipeline.
  • Netflix serves video from Open Connect, its own CDN of appliances placed inside ISP networks and at internet exchanges, filled during off-peak hours, so most viewing traffic never crosses the wider internet.
  • AWS, Google Cloud and Azure all document presigned or signed URLs, multipart or resumable uploads and storage event notifications as the recommended way to accept user uploads. The pattern is the platforms' own guidance, not a clever trick.

Case studies that use this pattern#

In the Interview#

Deep Dive: How URL signing actually worksShow

A presigned URL is safe because of a message authentication code. The signer and verifier share a secret, or in the asymmetric variant, the verifier holds a public key. Nobody without the secret can produce a valid tag for a modified request.

AWS Signature Version 4, step by step. Presigning a request takes four steps.

  1. Build a canonical request. This is a normalised string made of:
    • the HTTP method (PUT);
    • the URI-encoded path (/uploads/u_42/9f3c);
    • the sorted, encoded query string (X-Amz-Algorithm, X-Amz-Credential, X-Amz-Date, X-Amz-Expires, X-Amz-SignedHeaders);
    • the canonical headers, lower-cased, trimmed and sorted (at least host, plus anything else you chose to sign, such as content-type or x-amz-checksum-sha256);
    • the list of signed header names;
    • a payload hash. For presigned URLs this is the literal UNSIGNED-PAYLOAD, because the body doesn't exist yet when signing. That is why a signed checksum header is how you bind the content.
  2. Build the string to sign: the algorithm name, the timestamp, the credential scope (20261202/us-east-1/s3/aws4_request) and the SHA-256 of the canonical request.
  3. Derive a signing key by chained HMACs:
    • kDate = HMAC("AWS4" + secret, "20261202")
    • kRegion = HMAC(kDate, "us-east-1")
    • kService = HMAC(kRegion, "s3")
    • kSigning = HMAC(kService, "aws4_request")
  4. Compute the signature hex(HMAC-SHA256(kSigning, stringToSign)) and append it as X-Amz-Signature.

S3 repeats the computation from the incoming request and compares the result. Any change to the path, method, a signed header or a query parameter alters the canonical request and so the signature. Expiry is checked against X-Amz-Date plus X-Amz-Expires.

The derived-key chain means a leaked kSigning is valid only for one day, one region and one service, which limits blast radius in systems that cache derived keys. Security rests on HMAC-SHA256 behaving as a pseudo-random function: without the key, producing a valid tag for any new message is computationally infeasible, even after seeing many valid ones.

Symmetric versus asymmetric at the edge.

  • Shared secret (HMAC). Verification needs the secret wherever it happens. That's fine for a single storage service. Google Cloud CDN's signed URLs also use HMAC keys you register with the CDN.
  • Asymmetric. CloudFront signed URLs and cookies are signed with your private key, and the edge verifies them with the registered public key. Hundreds of edge locations then hold only public keys. A compromised edge can't mint URLs.

CloudFront supports two policy forms:

  • a canned policy: one resource, an expiry;
  • a custom policy: wildcards such as https://cdn.example.com/videos/abc/*, a start time, and an optional source IP range. Custom policies are base64-encoded into the URL or cookie.

Rolling your own for a gateway or a self-hosted store takes a few lines:

import { createHmac, timingSafeEqual } from 'node:crypto';
 
export function sign(path: string, expiresAt: number, keyId: string, secret: Buffer): string {
  const msg = `${path}\n${expiresAt}\n${keyId}`;
  const sig = createHmac('sha256', secret).update(msg).digest('base64url');
  return `${path}?exp=${expiresAt}&kid=${keyId}&sig=${sig}`;
}
 
export function verify(path: string, q: URLSearchParams, keys: Map<string, Buffer>): boolean {
  const exp = Number(q.get('exp')), kid = q.get('kid') ?? '', sig = q.get('sig') ?? '';
  const secret = keys.get(kid);                          // key IDs allow rotation
  if (!secret || !Number.isFinite(exp) || Date.now() / 1000 > exp) return false;
  const want = createHmac('sha256', secret).update(`${path}\n${exp}\n${kid}`).digest();
  const got = Buffer.from(sig, 'base64url');
  return got.length === want.length && timingSafeEqual(got, want); // constant time
}

Three details matter:

  • The key ID enables rotation: sign with the new key, and verify with both until old URLs expire.
  • A constant-time comparison avoids timing side channels.
  • The exact canonicalisation of the signed message prevents ambiguity attacks. Without separators, path=/a with exp=12 could collide with path=/a1 and exp=2.

Replays and single use. A signed URL can be used any number of times until it expires. Making it single-use needs state: a nonce recorded on first use and rejected afterwards. That is easy at one origin, but expensive across a global edge. Most systems accept multi-use within a short window. For uploads, S3's conditional write If-None-Match: * (available since 2024) makes a second PUT to the same key fail instead of overwriting, which gives write-once semantics per key.

Clock skew. Expiry checks compare against the verifier's clock. A signer whose clock is minutes fast produces URLs that look "not yet valid" or "already expired". Keep NTP healthy. Pick expiries comfortably longer than plausible skew, at least a few minutes.

Deep Dive: Content-defined chunking, the mathsShow

The rolling hash. A gear hash keeps one machine word h. For each input byte b, it updates h ← (h ≪ 1) + G[b], where G is a fixed table of 256 random 64-bit values. Because of the shift, a byte's influence leaves the word after 64 steps. So h depends only on the last 64 bytes: the window "rolls" for free, with no explicit subtraction.

Rabin fingerprints achieve the same with polynomial arithmetic modulo an irreducible polynomial over GF(2). They have a cleaner theory, but are slower in practice.

Boundary rule. Cut after byte i when (h AND mask) = 0, where the mask has k one-bits. For random-looking data, each position is a boundary with probability p = 2^−k, independently. So chunk length is approximately geometric with mean 2^k:

  • With k = 13, the expected chunk is 8 KiB.
  • The standard deviation is about equal to the mean, so many chunks are tiny and some are huge.

Two limits fix this:

  • A minimum size. Don't test for boundaries in the first min bytes after a cut. This also speeds things up, since those bytes are skipped.
  • A maximum size. Force a cut at max.

With min = 2 KiB, average 8 KiB and max = 64 KiB (LBFS's choice), chunks are well behaved.

Normalised chunking (FastCDC). Use a stricter mask (more one-bits, so fewer boundaries) before the expected size, and a looser mask after it. Lengths then cluster near the target. That reduces both tiny chunks (metadata overhead) and huge ones (lost dedupe). FastCDC combined this with gear hashing, and with skipping the sub-minimum region, to reach several times the throughput of Rabin-based CDC at a similar dedupe ratio.

Why insertions resynchronise. Insert d bytes at offset x.

  • Boundaries before x are unchanged, because their windows only saw earlier bytes.
  • Boundaries more than one window-length after x are unchanged too: they depend only on the 48–64 bytes before them, which are the same bytes, merely shifted.
  • Only the chunk containing x, and perhaps the next one if a boundary fell inside the disturbed window, get new hashes.

So an edit costs about 1–2 new chunks, about 8–16 KiB, regardless of file size. With fixed-size chunking, the same 1-byte insertion at the front of a 1 GiB file invalidates all 262,144 of its 4 KiB chunks.

Dedupe ratio, worked. Suppose nightly full backups of a 1 TB dataset, of which 1% changes per day, kept for 30 days.

  • Logical bytes written: 30 TB.
  • With CDC dedupe, physical bytes ≈ 1 TB + 29 × 10 GB ≈ 1.29 TB, a ratio of about 23:1, before compression.
  • With fixed-size chunks, the ratio depends on whether changes are in-place overwrites (similar savings) or insertions (savings collapse).

Are hash collisions a risk? With n chunks and a 256-bit hash, the chance of any collision is about n² / 2²⁵⁷. Take n = 2⁵⁰ (about 10¹⁵ chunks, which is exabytes at 4 KiB). Then p ≈ 2¹⁰⁰ / 2²⁵⁷ = 2⁻¹⁵⁷. That is unimaginably smaller than the rate of undetected hardware memory errors. Content addressing with SHA-256 is treated as collision-free in practice.

Weaker hashes are another matter. MD5 and SHA-1 have practical chosen collisions (SHA-1's SHAttered, 2017), so an attacker could craft two different files that dedupe to one. Use SHA-256 or BLAKE3 for dedupe keys.

Index cost. Each chunk entry stores a 32-byte hash, a location (about 16 bytes) and a reference count, so about 64 bytes with overhead. For 100 TB of unique data:

  • 8 KiB chunks give about 1.3 × 10¹⁰ entries, about 800 GB of index, which needs flash and a partitioned index.
  • 4 MiB blocks give about 2.6 × 10⁷ entries, under 2 GB, which fits in RAM on one node.

Chunk size is therefore an index-size trade-off as much as a dedupe one. Backup systems often add sparse indexing or container-level locality so they don't need a lookup per chunk. Consecutive chunks of a backup tend to reappear together, so the system loads the metadata for a whole container of them at once.

Deep Dive: Inside the blob store: durability, erasure coding and small filesShow

Where "eleven nines" comes from. Model each copy's disk as failing at an annual rate of about 2% (AFR). Re-replication after a failure takes about 6 hours.

  1. For a 3-replica object, the chance that one particular other disk fails within a 6-hour window is about 0.02 × 6 / 8,760 ≈ 1.4 × 10⁻⁵.
  2. Losing the object requires both remaining replicas to fail inside that window: (1.4 × 10⁻⁵)² ≈ 1.9 × 10⁻¹⁰.
  3. First failures happen about 3 × 0.02 = 0.06 times a year per object.
  4. The annual loss probability is therefore about 0.06 × 1.9 × 10⁻¹⁰ ≈ 1.1 × 10⁻¹¹, about eleven nines.

The independence assumption is the weak point. Correlated failures dominate real data loss: a rack's power, an availability zone, a firmware bug, a bad deploy, an operator deleting the wrong thing. That's why stores spread fragments across failure domains (racks, then AZs), checksum and scrub data continuously, and add protections such as versioning and object lock against logical deletes.

Erasure coding. Replication costs 3× storage. A Reed–Solomon RS(k, m) code splits data into k fragments and computes m parity fragments. Any k of the k + m fragments reconstruct the data.

  • RS(10, 4) stores 1.4× the data and survives any 4 simultaneous losses, which is more failures than 3× replication tolerates, at under half the cost.
  • The catch is repair cost. Rebuilding one lost fragment reads k = 10 fragments across the network, against one read for replication. It also adds latency to degraded reads.

Local Reconstruction Codes (Huang et al., "Erasure Coding in Windows Azure Storage", USENIX ATC 2012) add local parities over subsets of the fragments. Most single-fragment repairs then read only a local group, about 6 fragments instead of 12, at about 1.33× overhead for Azure's configuration.

Facebook's f4 applied RS(10, 4) within a region, plus XOR across regions, for warm blobs. That is how it brought the effective replication factor down to about 2.1. Hot data often stays replicated for read performance, and cold data is erasure-coded. That is the economic logic behind storage classes.

The small-file problem. Blob stores have per-object overhead:

  • a metadata entry;
  • a request charge on every PUT and GET;
  • for some storage classes, a minimum billable size (S3 Standard-IA bills objects smaller than 128 KB as 128 KB);
  • in filesystem-backed designs, several disk seeks per read just for metadata.

Haystack's contribution was to remove the filesystem-metadata seeks. Many photos are appended into large volume files. An in-memory index maps photo ID → (volume, offset, size), and a read is one seek.

The application-level lesson: pack tiny blobs. Examples: crawler pages in WARC files of about 1 GB, log lines in compressed hourly objects, ML training samples in shards such as TFRecord or WebDataset tar files. Read them with range GETs or streaming readers. Millions of 2 KB objects are a cost and throughput problem, while a few thousand 1 GB objects are not.

Request rates and key layout. S3 scales request capacity per prefix partition, at least 3,500 writes and 5,500 reads per second each, and splits hot prefixes automatically as load grows. Since 2018 AWS has said that randomised key prefixes are no longer needed for performance. A sudden 10× spike on a brand-new prefix can still see 503 Slow Down responses until partitions split. Use exponential backoff, and spread extreme write bursts across several prefixes, such as uploads/{shard}/....

Consistency and concurrency. S3 has offered strong read-after-write consistency for all objects since December 2020. A successful PUT is immediately visible to GETs and LISTs. Concurrent PUTs to the same key resolve as last-writer-wins, which is one more reason to use immutable, unique keys. Conditional writes (If-None-Match for create-only, and If-Match on ETag for compare-and-swap) now allow optimistic concurrency directly against the store. That echoes Dealing with Contention.

Tiering and lifecycle. Access to most blobs decays quickly: a photo is viewed mostly in its first days. Lifecycle rules move objects from a hot class to infrequent-access and then archive classes after N days, cutting storage cost several-fold. Archive retrieval takes minutes to hours, so classify by real access patterns. An unexpected mass restore from archive is slow and expensive.

Key Takeaways#

  • Keep file bytes out of your application servers. The API is the control plane (auth, quota, metadata, signing); the blob store and the CDN are the data plane.
  • Presigned URLs are short-lived bearer credentials for one operation on one server-chosen key. Bind the type and checksum, enforce size, sign with a least-privilege role, and keep expiries in minutes.
  • Use multipart or resumable uploads for anything large or on flaky networks. Resume by asking the server what it already has, and clean up abandoned uploads with lifecycle rules.
  • Use content hashing for dedupe, delta sync and integrity. Fixed blocks suit sync; content-defined chunking survives insertions. Mind cross-user privacy and garbage collection.
  • The metadata DB is the source of truth for what the app believes exists. Write pending first, confirm via storage events plus HEAD verification, keep handlers idempotent, and reconcile against inventory.
  • Process uploads asynchronously from a quarantine area: validate, scan, build derivatives, then mark ready and notify the client.
  • Serve through a CDN from a private bucket, with immutable keys, long cache lifetimes, and signed URLs or cookies for private content, served from a separate user-content domain.