Files and object storage
What breaks
Section titled “What breaks”Back to the salon platform from lesson 0.3. Each salon has a public page with a gallery. The owner
opens the dashboard on her phone, picks a photo of a finished hairstyle and taps “Upload”. The API
receives the file, writes it to its own disk as /photos/salon-81/3.jpg, and the page links to it.
One server, one disk. It works.
Then lesson 1.2 puts two app servers behind a load balancer. The owner’s upload lands on server A. The next customer’s request for that photo lands on server B, which has no such file. Half the gallery is broken, and which half changes on every refresh.
Copy files between servers? A server that was down during the copy is wrong forever. Share one network disk? Now every request touches that one machine.
Then lesson 0.3’s arithmetic arrives. At peak, 1,000 page views a second × 20 photos × 200 KB is 4 GB a second, or 32 Gbps. One server’s 1 Gbps link moves about 125 MB a second. The app servers are thirty times short, on bytes that have nothing to do with booking.
And the upload hurts too. A 2 MB original is 16 megabits. Even at the 1.6 Mbps lesson 1.8 used for a slow phone, that is ten seconds, and for those ten seconds an app server holds a connection open to receive bytes it will only pass on.
What broke? The app server was doing three jobs: running the business logic, storing files, and shipping bytes to the world. Only the first is its job.
Terms used in this lesson:
- Metadata is data about a file: who owns it, what it belongs to, its size, its type, where it is stored. Not the bytes themselves.
- An object store keeps files as whole objects, each found by a name. Amazon S3 and Google Cloud Storage are two examples. In this lesson “object” and “file” mean the same thing.
- A CDN (content delivery network) is a set of caching servers spread around the world that answer requests near the user and fetch from your storage only on a miss.
Mental model
Section titled “Mental model”Split every file in two: the bytes go to an object store, the facts about them go in your database. The app server hands out permission to move bytes; it does not carry them. Uploads go from the phone straight to storage. Downloads come from a CDN in front of storage. The app keeps the record and decides who may do what.
Diagram
Section titled “Diagram”A direct upload with a presigned URL, then a customer viewing the photo.
The app server touched no photo bytes.
What an object store is
Section titled “What an object store is”AWS puts it simply: “An object is a file and any metadata that describes the file. A bucket is a container for objects.” Each object has a key, “the unique identifier for an object within a bucket”.
So it is a key-value store (lesson 1.6) whose values are files. What does that buy?
- Whole objects only. “Amazon S3 never adds partial objects; if you receive a success response, Amazon S3 added the entire object.” You cannot edit part of one either; to change even its metadata “you must put the entire object”. A file is written once and replaced, never patched.
- Consistent reads. S3 gives “strong read-after-write consistency” for writes, overwrites and deletes. Once the upload returns 200, a read finds it.
- Durability you would not build. S3 Standard is “designed to provide 99.999999999% durability and 99.99% availability of objects over a given year” (checked 2026-11-29).
What it does not give you is a query. You cannot ask the bucket for “every ready photo of salon 81,
in the order the owner chose”. That is a database question. Hence the split: the photo record holds
salon_id, key, size, status and position; the object store holds the bytes under key.
The cost of the split: two systems, and no transaction that covers both. Much of this lesson is about living with that.
Uploads: three ways in
Section titled “Uploads: three ways in”There are three ways to get the owner’s photo into the bucket.
Through the app server. The phone sends the file to the API; the API writes it to the bucket. Simple, and the server sees every byte, so it can check and transform the file on the way. The cost is the one from the opening: a connection held open for the whole slow upload, and the bandwidth paid twice, in and out.
Straight to storage with a presigned URL. A presigned URL is a link to one key with an expiry and a signature, made with the server’s storage credentials, in its query string. AWS: it allows an upload “without requiring another party to have AWS security credentials”. The phone sends the bytes to the bucket; the server only signs.
What does that URL grant? Lesson 1.7’s word answers it. AWS: “presigned URLs are bearer tokens that grant access to those who possess them.” Google says the same of its signed URLs. So:
- Authorise before you sign. The URL carries no user. The check “may she edit salon 81?” happens in the app, as in lesson 1.7, before the URL exists.
- The server picks the key. If an object with that key exists, “Amazon S3 replaces the existing object”. Let the client choose the key and it can overwrite someone else’s photo.
- Keep it short-lived. It can be used “multiple times, up to the expiration date and time”. As of 2026-11-29, S3 allows up to 7 days through the SDK, and Google’s longest is 604,800 seconds, also 7 days. An upload needs minutes.
- It can do no more than its signer. “The capabilities of a presigned URL are limited by the permissions of the user who created it.” Sign with credentials that can only write uploads.
Need to cap size or type? A presigned POST policy is a signed form with conditions. AWS lists
content-length-range, “the minimum and maximum allowable size for the uploaded content”, and
conditions on Content-Type and the key prefix. The bucket refuses an upload that breaks them.
In parts, for big files or bad networks. A single request that fails at 90% starts again from zero. S3’s multipart upload sends a file in parts, for “quick recovery from any network issues”; AWS suggests it from 100 MB. Google’s resumable upload does the same job. A 2 MB photo does not need it; a 2 GB video does.
How does the app know the upload finished?
Section titled “How does the app know the upload finished?”With a presigned upload the bytes went past the server. So who tells it?
The client says so. After the PUT returns, the phone calls POST /photos/42/complete. Do not take
its word. S3’s HEAD request “retrieves metadata from an object without returning the object itself”,
so the server learns the object exists and its size, then marks the record ready.
The store says so. S3 can publish an event when an object is created (s3:ObjectCreated:Put,
Post or CompleteMultipartUpload) to a queue or a function. It fires even if the phone dies right
after the upload. Two catches, in AWS’s words: events are “designed to be delivered at least once”,
and they “typically” arrive “in seconds but can sometimes take a minute or longer”. At least once
means sometimes twice, so the handler must be idempotent (lesson 1.3): marking photo 42 ready twice
must equal marking it once.
This course’s suggestion: the client call for speed, the event as the backstop.
Now the two-systems problem. What can go wrong between them?
- Record, no object. The server wrote a pending record and signed a URL; the owner closed the app. A sweep job deletes pending records older than, say, a day.
- Object, no record. The database write failed after the upload, or a record was deleted and its object was not. Nothing points at the bytes, and you pay to keep them. Choose a write order whose failure you can detect: record first, as in the diagram, or object first and removed if the record’s transaction does not commit. Delete an object only after the record change commits. Lifecycle rules help: S3 “deletes expired objects on your behalf”.
- Half an upload. For a multipart upload “there is no expiry; you must explicitly complete or
abort”. AWS recommends a lifecycle rule with
AbortIncompleteMultipartUpload.
After upload: processing
Section titled “After upload: processing”The original is 2 MB. The gallery shows 200 KB thumbnails. Who makes them?
Not the request. Resizing takes time and can fail, so this course puts it in a background job that runs after the upload is confirmed. Each copy has its own status; pages show only ready ones. Facebook’s web servers likewise “scale each photo to four different sizes” (Haystack paper, 2010).
Processing is also where you check the file, because it came from a user. OWASP’s file upload guidance includes “don’t trust the Content-Type header as it can be spoofed” and “Change the filename to something generated by the application”.
Serving: a CDN in front of the bucket
Section titled “Serving: a CDN in front of the bucket”Could the bucket serve 32 Gbps itself? A bucket lives in one region, which may be far from a customer in Lagos, and every view would be a request to storage.
A CDN fixes both. In AWS’s description of CloudFront, DNS sends the request to the edge location “that can best serve the request, typically the nearest”. If the object is cached there, the edge returns it. If not, it forwards the request “to your origin server … for example, to your Amazon S3 bucket” and “adds the object to the cache for the next time someone requests it”.
How long may the edge keep a copy? The file says. Cache-Control: max-age=N means the response
“remains fresh until N seconds after the response is generated” (MDN). If the origin sends nothing,
CloudFront’s default is 24 hours (checked 2026-11-29).
Then the owner replaces the photo. Under the same key, every edge keeps the old one until it expires.
So never reuse a key: each version gets a new key, and the record points at the new one. MDN calls
this “the cache-busting pattern”, and it makes immutable safe, meaning the response “will not be
updated while it’s fresh”. The recipe is a long max-age, immutable, and a new key for each
version. Cache invalidation in depth is lesson 2.4.
When a public URL is wrong. Gallery photos are for anyone. A paid video or a signed contract is not. For those the app checks permission and returns a short-lived signed read URL: the same bearer idea, for reading. A forwarded link still works until it expires.
Real case
Section titled “Real case”Roost, a booking platform for businesses that sell their time, shows business photos on public pages and on each service a customer can book.
Who uploads. The owner or a staff member allowed to edit the business, from the dashboard. Customers do not upload business photos.
Where the bytes go. Roost takes the first path: the photo goes to the app server, which writes it to an object store. Because the server has the bytes, it turns each upload into one normalised master copy and does not keep the phone’s original. A booking page never needs the full-size file, and keeping it would roughly double the storage.
How the app learns it finished. It wrote the object itself, so it knows. It then writes the metadata record that ties the photo to its business and service. Where that record is part of a larger database transaction, the object is stored first and removed if the transaction does not commit. When an owner replaces a photo, the new one is stored and recorded before the old one is removed.
Processing and serving. A background job makes resized copies for each place a photo appears, each with its own status (pending, ready, failed), so pages link only to copies that exist.
The trade-off. Passing bytes through the server costs bandwidth and connection time per upload, and buys one place to normalise and resize. With a few owner uploads at a time, that is cheap: this course’s reading, not a measurement.
Honest about scale. Roost is early-stage, with no recorded upload or photo-serving measurements. At much larger scale the design would move towards this lesson’s diagram: direct uploads, processing on its own workers, and the caching questions of lesson 2.4.
Trade-offs
Section titled “Trade-offs”Through the server or direct. Through the server is simpler and gives one place to check and transform; it costs a held connection and double bandwidth per upload. Direct scales with the store, and costs a confirm step, a CORS rule on the bucket so the browser may send to it, and checks that move to a background job. Through the server when uploads are few and small; direct when they are many, big or slow.
Public URL or signed read URL. A public URL behind a CDN is the cheapest and fastest to serve, and anyone with the link can see the file while it exists. A signed read URL limits who and for how long, and costs a request to your app per view and weaker caching. Public for content meant to be seen, signed for anything private.
What a CDN cannot fix. Facebook’s 2010 Haystack paper describes over 260 billion images and “over one million images per second at peak”. Its long tail of older photos “typically miss in the CDN”, and caching it all “would not be cost effective because of the very large cache sizes required”. So Facebook built a store needing “at most one disk operation per read”. A CDN helps popular files far more than the long tail.
Drill 1 — interview question
Section titled “Drill 1 — interview question”“Design photo upload and display for a holiday-rental marketplace. Hosts upload up to 30 photos per listing from their phones. Millions of guests browse listings every day.”
Model answer
Split. Photo bytes in an object store; a photos table with listing, key, size, position and
status.
Upload. The host asks to add a photo. The app checks she owns the listing, inserts a pending record with a server-chosen key, and returns a presigned POST with a short expiry and size and type conditions. The phone uploads straight to the store; multipart or resumable for large files on slow networks.
Confirm. The phone calls “complete”; the server HEADs the key and marks it uploaded. A storage event is the backstop, handled idempotently.
Process. A background job checks the file really is an image and makes a few sizes, each with a status. Listings show only ready photos.
Serve. A CDN in front of the bucket. A new key per version, and Cache-Control with a long
max-age and immutable.
Clean up. Sweep stale pending records; lifecycle rules for the upload area and for incomplete multipart uploads.
Rubric
- Splits bytes (object store) from metadata (database) — 2
- Uploads direct with a presigned URL or POST policy, server-chosen key, short expiry, authorisation first — 2
- Says how the app learns the upload finished, and verifies it — 2
- Processes in the background with a status per copy, and treats uploads as untrusted — 2
- Serves through a CDN with cache headers and a new key per version — 2
Total 10. 8 or more is a pass.
Drill 2 — interview question
Section titled “Drill 2 — interview question”The interviewer follows up: “Six months in, storage is growing faster than the number of photos on listings, and a few listings show broken images. What is happening, and how do you fix it?”
Model answer
Storage growing: objects with no record. Uploads never confirmed, records deleted without their objects, old versions left after a replace, and incomplete multipart uploads, whose parts stay until aborted. Compare the bucket’s keys with the table to find them. Fix with lifecycle rules and object deletion after the record change commits.
Broken images: records pointing at nothing, or not yet. The record was marked ready on the client’s word without a HEAD check, or the page linked a resized copy before the job made it, or an object was deleted before its record. Fix: verify before marking ready, show only ready copies, and keep the delete order.
Root cause. Two stores, no shared transaction. Order the writes so a failure is detectable, and sweep to repair it.
Rubric
- Names orphaned objects and their causes, including incomplete multipart uploads — 2
- Names records that point at missing or unprocessed objects — 2
- Explains the root cause: two systems, no shared transaction — 2
- Fixes with write order and verification — 2
- Fixes with lifecycle rules and a sweep job — 2
Total 10. 8 or more is a pass.
Drill 3 — hands-on exercise
Section titled “Drill 3 — hands-on exercise”Build a direct upload and break it on purpose. Use an S3 bucket in a test account, or an S3-compatible server you run locally.
- Write two endpoints: one inserts a pending record and returns a presigned PUT URL for a key the server generates; the other marks it uploaded after a HEAD check.
- Upload a photo with
curl -X PUT --upload-file. Predict first: what does the bucket return, and what does your table say before you call the second endpoint? - Wait past the expiry and try the same URL. Then change the key in the URL. Write down each error.
- Call “complete” without uploading. Does your HEAD check catch it?
- Upload, then stop the client before “complete”. Write the sweep that cleans it up.
- Serve the photo with
Cache-Control: public, max-age=31536000, immutable. Replace it under the same key and reload with the cache on. Then do it with a new key. Explain the difference.
Write one sentence per step on what surprised you.
Exit test
Section titled “Exit test”Answer without notes.
- Two app servers store uploads on their own disks. What breaks, and what two parts should each file be split into?
- What are a bucket, a key and an object? Name one thing an object store does not give you that a database does.
- What does a presigned upload URL grant, to whom, and for how long? Name three ways to limit it.
- After a direct upload, how does the app learn it finished? Give two ways and the catch in each.
- An owner replaces a photo and customers still see the old one. Why, and what change to keys and headers fixes it? When would you use a signed read URL instead of a public one?
Further reading
Section titled “Further reading”- Beaver et al., Finding a needle in Haystack: Facebook’s photo storage, OSDI 2010 — https://www.usenix.org/legacy/event/osdi10/tech/full_papers/Beaver.pdf.
- AWS, What is Amazon S3? — https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html; PutObject — https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObject.html; Optimizing performance — https://docs.aws.amazon.com/AmazonS3/latest/userguide/optimizing-performance.html; Durability — https://docs.aws.amazon.com/AmazonS3/latest/userguide/DataDurability.html; HeadObject — https://docs.aws.amazon.com/AmazonS3/latest/API/API_HeadObject.html. Checked 2026-11-29.
- AWS, Presigned URLs — https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html; POST policy — https://docs.aws.amazon.com/AmazonS3/latest/developerguide/sigv4-HTTPPOSTConstructPolicy.md.
- Google Cloud, Signed URLs — https://cloud.google.com/storage/docs/access-control/signed-urls; Resumable uploads — https://cloud.google.com/storage/docs/resumable-uploads.
- AWS, Multipart upload — https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpuoverview.html; Event notifications — https://docs.aws.amazon.com/AmazonS3/latest/userguide/EventNotifications.html; Lifecycle management — https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lifecycle-mgmt.html.
- AWS, How CloudFront delivers content — https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/HowCloudFrontWorks.html; Cache duration — https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html.
- MDN, Cache-Control — https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Cache-Control.
- OWASP, File Upload Cheat Sheet — https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html.