Design an image hosting service (like Imgur)
medium 50 minUpload a picture, get a link at once, and let the whole world look at it.
Deep dives
Compare the options before you open them, then say which you would pick.
Deep dive 1
The processing pipeline
When do you make the sizes?
BreaksInside the upload request
- How
- Decode and resize before answering.
- Limit
- Seconds of waiting, CPU next to traffic, and one harmful file can stop the server.
- Choose when
- A handful of uploads.
WorksAll on demand at the edge
- How
- Keep a cleaned master and make a size on the first view.
- Limit
- The first viewer waits, popular pages cause bursts of CPU, and evicted sizes are made again.
- Choose when
- Most images are never viewed.
StrongCommon sizes ahead, rare ones on demand
- How
- Three sizes by the worker; a fixed list of others on first request, then stored.
- Limit
- Some sizes nobody asks for. The list needs care.
- Choose when
- 500 views an upload: our choice.
One worker, three ways out
Inside the worker
- 1
Look
Real type from the first bytes, then size in pixels from the header. Over 50 megapixels or 200 frames: stop before decoding.
- 2
Check
Compare with lists of known bad material, then classifiers. Nothing is public yet.
- 3
Decode once
Into pixels, with memory and time limits. Turn it the right way up and convert to one colour space (sRGB).
- 4
Resize from pixels
A good downscale filter such as Lanczos, light sharpening. Larger first, the smaller from it.
- 5
Encode
JPEG at about 85 for large and 75 for small, WebP at about 80. Tune by looking, not by the number.
- 6
Forget
Nothing is copied from Exif except what an allow list names, such as camera and exposure. Place is never on it unless the owner asks for it.
Libraries such as libvips work with little memory on ordinary CPUs. A GPU may help classifiers; measure before buying it for resizing. Animated GIFs are large: make a short video loop and a still first frame, with the GIF as a fallback.
Deep dive 2
Caching and famous pictures
A picture goes from 10 to 50,000 views a second. What absorbs it?
BreaksMore servers reading the store
- How
- Autoscale the image service.
- Limit
- 15 GB/s for one picture, minutes to add machines, and all of it paid at origin.
- Choose when
- Slow growth.
WorksCDN alone
- How
- Each edge keeps a copy.
- Limit
- When hundreds of edges miss together, each asks the store once.
- Choose when
- Normal popularity.
StrongEdge with merging, shield, immutable copies
- How
- One request per edge, one per shield, long shared life.
- Limit
- One more hop for cold pictures; a purge must reach both layers.
- Choose when
- Sudden fame is expected, as here.
Four layers
| Layer | Keeps it | Answers | Purge |
|---|---|---|---|
| Browser | 1 hour | repeat views | not possible |
| Edge | 30 days | 95% | yes, by tag |
| Shield | 30 days | 80% of the rest | yes, first |
| Store | always | 1% | delete |
Two lives. max-age=3600 is for the browser and s-maxage=2592000 for shared caches. A year in the browser with immutable is faster, but a takedown could not reach it. We choose an hour, and say why.
Formats. Either put the format in the address, as here, and let the page choose with <picture>, or negotiate by Accept and send Vary: Accept. Reduce Accept to two or three values at the edge first, or each browser's own header becomes another cache entry.
Noticing fame
Can we fill all edges in advance? Most CDNs fill on demand; a normal request only fills the place it reaches. Merging and the shield already make the first wave cheap: hundreds of edges cost a few store reads. Spend the effort on smaller files: at 300 KB, 500 million views are 150 TB; a third less is 50 TB saved. See cache warming and thundering herd.
Deep dive 3
Storage, duplicates and deletion
One meme is uploaded 10,000 times. How is it stored?
BreaksOne record, shared by all
- How
- Return the first uploader's ID for equal bytes.
- Limit
- Anyone can then delete, or learn that it existed. Titles and owners mix.
- Choose when
- Never for user content.
Works10,000 copies
- How
- Store each upload.
- Limit
- 10,000 × 1.4 MB = 14 GB for one meme.
- Choose when
- Few duplicates; simplest to delete.
StrongOwn records, shared blob
- How
- Hash the bytes; records refer to the blob through
blob_refs. - Limit
- Deletion needs care, and equal-looking pictures with other bytes are not found.
- Choose when
- 10% duplicates: 1.4 TB a day saved.
Delete without a race
- 1
Hide
Record to deleted, links answer 404, caches purged. This is what the user wanted.
- 2
Drop the reference
Remove the row in
blob_refs. - 3
Wait
If no reference is left, mark the blob with a date 30 days ahead.
- 4
Check again and lock
At that date, in one transaction on the hash: still no reference? Then set it to removing. A new upload that sees removing stores its own new blob version.
- 5
Remove
Delete the files. The sweeper is safe to repeat.
Which class for which file
| File | Class | Why |
|---|---|---|
| Small copies | standard | Under 128 KB: minimum size would be billed |
| Medium and large, recent | standard | Origin of cache misses |
| Large copies, 90 days unseen | infrequent, instant access | Cheaper to keep, fee to read |
| Originals | instant archive class after 90 days | Read only by owner or for new sizes |
| Hour-long retrieval classes | not for links | A public picture must open now |
"Unseen" must come from edge logs, not from store reads: a popular picture in the caches looks unread at the store. Durability of the store is not a backup against our own mistakes: keep versions for 30 days and copy to a second region. A sample of 0.1% is read and hashed daily to find damage.
Deep dive 4
Safety, moderation and takedown
When is an upload checked?
BreaksAfter reports
- How
- Publish now and react.
- Limit
- The worst pictures are public and cached, and may be copied before anyone reports.
- Choose when
- Closed groups who know each other.
WorksCheck after publishing
- How
- Public at once, scanned in the background.
- Limit
- Seconds to minutes of exposure, then a worldwide purge.
- Choose when
- Trusted accounts only.
StrongGate before the first public byte
- How
- Placeholder, automatic checks, people for the doubtful part, appeal.
- Limit
- Delay and mistakes; needs staff.
- Choose when
- Anonymous uploads: our choice.
How a score becomes a decision (example policy)
| Result | Action |
|---|---|
| Under 0.3 | Publish |
| 0.3 to 0.7 | Review, or publish with a mature label by policy |
| Over 0.7 | Hold and review first |
| Match with a known-illegal list | Block, isolate, trained team, report as law requires |
| Same hash as something removed | Block, allow appeal |
Checks include adult and violent content, and text in the picture (OCR) that shows phone numbers or addresses, as used in harassment. A person decides close cases: a medical photo or a painting may score high. Reviewers get blurred previews, breaks, rotation and support. Their decisions and appeals become training examples. If 1% of uploads need a person at 10 seconds each: 100,000 × 10 s = 278 hours a day, about 46 people at six hours of review each.
Law, in short (not legal advice)
Known illegal images
United States law (18 U.S.C. 2258A) requires a report once a provider has actual knowledge. It does not itself order a search; many services choose one.
Copyright
A valid notice under 17 U.S.C. 512 means acting expeditiously. After a counter notice, restore in 10 to 14 business days unless a lawsuit is announced.
Personal data
People may ask for erasure. Deleting covers record, blob if unshared, caches and logs after their retention.
Deep dive 5
Uploads that survive a bad network
A phone loses signal at 80% of a 20 MB upload. What happens?
BreaksStart again, no key
- How
- The client posts the file once more.
- Limit
- 16 MB wasted, and a lost answer makes two images.
- Choose when
- Small files on good networks.
WorksMultipart parts
- How
- Send 5 MB parts, repeat a missing one.
- Limit
- Needs the client to keep track of parts.
- Choose when
- Large files to object storage.
StrongResumable with an offset and a key
- How
- Ask the server how far it got, send the rest; complete is idempotent.
- Limit
- Server state for 24 hours and a cleaner.
- Choose when
- Mobile clients.
Edge cases
What can go wrong
| Case | Severity | Problem | Answer |
|---|---|---|---|
| Abandoned upload | low | Bytes nobody owns | Remove after 24 hours |
| False type | high | A program named .jpg | First bytes, decode, re-encode |
| Pixel bomb | high | Tiny file, huge picture | Pixel limit before decoding |
| Location in Exif | critical | Home address published | Private original, re-encode |
| Job crash loop | medium | One file kills workers | Three tries, dead-letter queue, status failed |
| Queue backlog | medium | Minutes until ready | Scale by oldest job, small first |
| Store region down | critical | Cold pictures fail | Edges serve what they hold; second region for reads |
| CDN down | critical | All views fail | Second CDN, tested; origin cannot carry 417 Gbit/s |
| Damaged file | medium | Broken picture | Checksums, versions, second copy |
| Hot counter | medium | All writes on one row | Edge logs, sharded counters |
| Hotlinking | medium | Another site uses our traffic | Referrer rules, smaller copies, limits |
| Upload bot | high | A million files, storage bill | Limits per account and address, trust levels, daily byte alarm |
| Flood on one picture | high | Attack on a link | Edge absorbs, limits per client at the edge |
| Coordinated harassment | critical | Same picture from many accounts | Hash block list, OCR, review |
| Purge missed | critical | Blocked picture still served | Purge shield before edge, verify from outside, short browser life |
Failure drill: say it before you read it
- 1
The queue is down
Uploads are still stored and recorded as processing. The sweeper queues them when it returns. Links show the placeholder.
- 2
The shield is down
Edges go to the store: 5% of 173,600 is 8,700 reads a second instead of 1,740. Plan the store's limits for that.
- 3
Redis is down
API reads and the 1% of views that miss go to the shards: at most 1,740 more lookups a second over 16 shards. Cached views do not notice.
- 4
A check model fails
Fail closed: new anonymous images wait. Say the cost: uploads look slow, nothing unsafe is published.