Files, media and blob storage
Ten million dish photos: the database keeps the facts, object storage keeps the bytes, and the upload never passes through our servers.
Blob storage keeps large, opaque files, such as photos, videos and documents, in a system built for bytes, while the database keeps the facts about them: who uploaded what, for which dish, and whether it is ready to show. Getting a file feature right is mostly about keeping those two jobs apart and deciding how bytes travel between the phone, the store and the screen. This chapter does that for Dabba’s dish photos.
The brief from the first chapter counts about 3 million dish photos across Dabba’s 50,000 restaurants, most taken on the owner’s phone and around 2 to 4 MB each as uploaded. A menu page shows 20 to 40 dish thumbnails, and every customer who opens a menu loads them. Those two facts, millions of large originals and an enormous number of small reads, decide almost everything below.
Why the bytes do not go in the database
Three million originals at an average of 2 MB is about 6 TB. The live orders database from the sharding chapter is about 360 GB. Putting photos in database rows would make the menu database many times larger than everything else Dabba stores, and every database job would get slower with it: backups would copy 6 TB, replicas would replay megabytes per upload, and the database’s memory cache would fill with image bytes that push out the menu rows it was meant to hold.
Object storage, the service S3 made familiar, is built for exactly the opposite workload. Its interface is small on purpose: put a whole object at a key, get it, delete it, list keys by prefix. There are no partial updates and no transactions across objects. In exchange it stores many copies or erasure-coded fragments across separate facilities, scales without planning, and costs a small fraction of database storage per gigabyte. Since late 2020, S3 also returns the new object to any read that follows a successful write, which removes a class of upload bugs older designs had to work around.
Facebook’s Haystack paper, linked at the end of this chapter, explains why even a normal filesystem struggles here. At billions of small files, the metadata, directory entries and per-file records, costs more disk reads than the photos themselves. Haystack packed many photos into large files and kept a small in-memory index from photo id to position, so that reading any photo took one disk seek. Object stores apply the same idea at larger scale, and we inherit it by not storing files ourselves.
The database keeps one row per photo: dish id, storage key of the original, keys of the resized versions, status, uploader, and timestamps. That row is small, transactional and indexed, which is what databases are good at.
The upload path that keeps our servers out of the way
The first version usually sends the photo through the API: the app posts the image to Dabba’s server, which writes it to object storage. It works, and it puts the slowest part of the system in the most expensive place. A restaurant owner on a 4G connection with a 3 Mbps uplink takes about 10 seconds to send a 3.8 MB photo. For those 10 seconds an API server holds the connection and buffers the bytes, and an upload burst, for example a few thousand restaurants onboarding in the same week with 80 photos each, ties up API capacity that customers placing orders need.
The standard alternative is the presigned URL. The API does not receive the photo; it gives the app permission to send it straight to object storage.
- The app asks the API: “I want to upload a photo for dish 5521.” The API checks that this user manages the restaurant that owns dish 5521.
- The API creates a photo row with status
pending, chooses the storage key itself, for exampleuploads/r88213/d5521/7f3c…e1.jpgwith a random part, and returns a URL signed with Dabba’s storage credentials. The signature covers that key, the HTTP method, and an expiry of ten minutes. - The app sends the bytes directly to object storage using that URL. Storage checks the signature and accepts the upload. Dabba’s API never sees the bytes.
- Object storage emits an “object created” event, which goes onto a queue.
- An image worker picks it up, processes the photo, and updates the row to
ready.
Two details in step 2 matter for security. The server chooses the key, never the client, so a client cannot overwrite another restaurant’s photo by naming its key. And the signature should restrict what can be sent: with S3’s presigned POST policy, for instance, the API can require a content-type starting with image/ and a size between 10 KB and 15 MB. Without a size limit, a leaked URL lets someone store a 5 GB file at Dabba’s expense for as long as the URL is valid.
Content-type checks at upload are only a hint, because the client chooses what to declare. The worker in step 5 makes the real decision by decoding the file.
What the worker does before anyone sees the photo
The original upload is never what customers see. The image worker runs through a fixed list, and each step exists because something went wrong without it somewhere.
It decodes the image with a proper library. A file that does not decode is rejected, whatever its declared type. This also catches files that are valid images with something else appended. It applies the orientation recorded by the phone’s camera, so that photos do not appear sideways, and then strips the metadata. Phone photos usually carry GPS coordinates of where they were taken, and a home-kitchen restaurant owner’s photos would otherwise publish her home address on every menu.
It produces the four sizes the apps actually display, from a 160-pixel thumbnail up to a 1,080-pixel full view, encoded as WebP, which every Android version Dabba supports can show. It runs an automated content check and flags doubtful images for a person to review. It writes each derived image to object storage under a key that includes a hash of its content, then records those keys on the photo row and sets the status to ready.
Every step must be safe to run twice. The queue delivers at least once, as in the streams chapter, and a worker killed halfway through will see the same upload again. Because derived keys come from the content hash, running twice writes the same objects to the same keys, and the status update is a simple “set to ready” that can be repeated.
The owner of restaurant 88213 replaces the photo of paneer tikka with a better one. The design stores the thumbnail at a fixed key, dishes/5521/thumb-480.webp, overwritten with the new image, and the CDN caches images for 30 days. What do customers see, and for how long?
Show the worked answer
Customers who load the menu through a CDN location that has the old thumbnail cached keep seeing the old photo for up to 30 days. Customers routed to a location without a cached copy see the new one. The owner checks on her phone, sees the new photo, and then gets a call from a regular asking why the photo has not changed.
We could purge that key from the CDN on every replacement, which works but adds a purge call to every edit and depends on purges arriving everywhere. The simpler fix, and the reason earlier chapters gave photos content-hashed URLs, is never to overwrite: each new image gets a new key, derived from its content hash, and the menu points at the new key. Old keys can be cached forever because they never change, and a change is visible as soon as the menu data that references it is.
Serving: the numbers that make resizing mandatory
The brief counts about 100 image loads per session, 400 million a day: about 4,600 a second on average, and about 17,000 a second in the dinner hour, which carries 15% of the day.
Now the bytes. If the menu served the original 2 MB photos, 400 million requests would move about 800 terabytes a day, and customers on mobile data would wait several seconds per menu. Served as resized images of about 60 KB, the same requests move about 24 TB a day. That thirty-fold difference is why resizing is part of the design, not a later optimisation.
Twenty-four terabytes a day still should not come from object storage directly. Data transfer out of a cloud provider is charged per gigabyte, typically at several times the monthly cost of storing that gigabyte, and object stores are not built for very low latency to phones in Patna. So images go through a CDN, as covered earlier in this pathway, with keys that never change and cache headers that say so: Cache-Control: public, max-age=31536000, immutable. With 3 million photos in four sizes and most views concentrated on popular restaurants, the CDN serves the large majority of requests from its edge, and object storage sees mainly the long tail.
There is a second way to produce sizes: resize on demand. The app requests /img/5521/w480.webp; an image service at the CDN origin fetches the original, resizes it on the first request, and the CDN caches the result. That avoids generating sizes nobody requests and makes adding a new size a client change. Its cost is on the first request for each size, and on the image service, which now sits in the read path.
| Approach | First view of a new photo | Adding a new size | What can fail | Fits when |
|---|---|---|---|---|
| Resize at upload | Fast; sizes already exist | A backfill job over every original | Worker backlog delays “ready” | A small, stable set of sizes |
| Resize on demand behind the CDN | Slow once per size per CDN region | Change the URL in the app | Image service overload on a cold cache | Many sizes or frequent design changes |
Dabba resizes at upload, because it has four sizes that change rarely, and because the worker’s other jobs, metadata stripping and content checks, have to happen before publication anyway.
Uploads that never finish: a walk-through
Here is a failure every upload system meets. An owner onboarding her restaurant at 15:00 uploads 80 photos on a patchy connection. Photo 37’s upload completes in object storage, but the app was designed to call the API with “upload done” afterwards, and that call fails when the connection drops. The app retries a few times and gives up. The photo row stays pending. The owner sees a spinner on dish 37, uploads the photo again, and that one works.
Two things are now wrong, and neither raises an error. Dabba is storing an original that nothing refers to. And in a quieter variant, a row is marked pending forever for an object that does exist. Across a few thousand onboardings a month, this adds up to many gigabytes of orphaned originals and a support queue of “my photo is stuck”.
The fix moves the source of truth for “upload finished” from the app to the store. The object-created event from step 4 above, not a client call, is what triggers the worker and moves the row along. A client that loses its connection after uploading does not matter, because storage has already reported the upload. For uploads that never complete at all, a lifecycle rule on the bucket deletes anything under the uploads/ prefix after two days, since originals are copied to a permanent prefix only once processed. A nightly reconciliation job lists rows that have been pending for more than an hour and checks whether their object exists, fixing whichever side is wrong.
The costs: an event queue between storage and the worker, a lifecycle rule someone has to understand before changing, and a reconciliation job. In exchange, a dropped connection on the owner’s side cannot leave Dabba’s data inconsistent.
Files that must stay private
Dish photos are public; anyone may see them, which is why a long-lived CDN cache is fine. Dabba also stores files that are not: the food safety licence and tax documents each restaurant uploads during onboarding, and the identity documents riders provide. These use the same upload path, into a separate bucket that allows no public reads at all.
Reading them is the mirror image of uploading. When an operations reviewer opens a restaurant’s licence, the admin API checks that this reviewer may see it, records the access in an audit log, and returns a presigned GET URL for that one object, valid for a few minutes. The browser fetches the document directly from storage. The bytes never pass through the admin service, and the permission decision never leaves it.
Two settings go with that. The URL’s expiry is short, because a presigned URL is a bearer credential: anyone who has it can use it until it expires, whether or not they are the reviewer. And responses for private objects are marked as not cacheable, so that no CDN or shared proxy keeps a copy that outlives the reviewer’s permission. The cost is that every view of a private document is a fresh fetch from storage, which is fine for a few thousand reviews a day and would not be for a public menu.
Deleting, and paying for what stays
When a restaurant leaves Dabba, its photos must go: the originals, every derived size, and the cached copies. Content-hash keys make deletion slightly harder than fixed keys, because we must look up every key the photo rows recorded rather than deleting by a prefix. Dabba therefore stores each restaurant’s derived images under a prefix that includes the restaurant id, so the deletion job can remove them by listing that prefix. CDN copies expire on their own, or are purged if the removal is urgent, for instance after a legal request.
Storage cost has a second lever: storage classes. Originals are read once by the worker and then almost never, only when a new size is added. Moving them after 30 days to an infrequent-access class cuts their storage price substantially. Archive classes are cheaper still but charge to retrieve and can take hours, which would make a backfill of a new size slow and expensive. The class is a promise about how the data will be read, and we choose it from the access pattern, not from the price list alone.
When this design is more than the problem needs
Very small files with strict consistency needs can stay in the database. A delivery signature image of a few kilobytes, stored with the order it belongs to and backed up with it, is simpler there than split across two systems. The line is not exact, but once files are larger than a few hundred kilobytes, numerous, or served to the public, they belong in object storage.
We would revisit the design when Dabba adds video, for example short clips of dishes. Video needs transcoding into several bitrates, segmenting for adaptive streaming, and range requests so players can seek. The upload path above still applies, but the worker becomes a pipeline, and the serving path is a different problem.
Customers can now see the menu and the dishes. Once they order, they want to see something else: the rider, moving on a map, every few seconds. Until now the client has always asked and the server answered. The next chapter, on realtime delivery, covers what changes when the server has news first, and what it costs to keep a connection open to every customer waiting for dinner.