AlgoViz

Design an image hosting service (like Imgur)

medium 50 min

Upload 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

A job queue feeds a worker machine with no internet access. Inside it a file is checked, cleaned and resized. It reads the private store and writes the public store. Doubtful files go to the review team, files that fail go to a dead-letter queue.

Inside the worker

  1. 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. 2

    Check

    Compare with lists of known bad material, then classifiers. Nothing is public yet.

  3. 3

    Decode once

    Into pixels, with memory and time limits. Turn it the right way up and convert to one colour space (sRGB).

  4. 4

    Resize from pixels

    A good downscale filter such as Lanczos, light sharpening. Larger first, the smaller from it.

  5. 5

    Encode

    JPEG at about 85 for large and 75 for small, WebP at about 80. Tune by looking, not by the number.

  6. 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

LayerKeeps itAnswersPurge
Browser1 hourrepeat viewsnot possible
Edge30 days95%yes, by tag
Shield30 days80% of the restyes, first
Storealways1%delete
Hit rates are assumptions. Long life does not promise a hit: caches drop what is rarely asked.

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

Example bands: 10 to 50 times the usual is rising, 50 to 200 viral, above that exceptional. New images have no usual rate, so also require a minimum count.

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. 1

    Hide

    Record to deleted, links answer 404, caches purged. This is what the user wanted.

  2. 2

    Drop the reference

    Remove the row in blob_refs.

  3. 3

    Wait

    If no reference is left, mark the blob with a date 30 days ahead.

  4. 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. 5

    Remove

    Delete the files. The sweeper is safe to repeat.

Which class for which file

FileClassWhy
Small copiesstandardUnder 128 KB: minimum size would be billed
Medium and large, recentstandardOrigin of cache misses
Large copies, 90 days unseeninfrequent, instant accessCheaper to keep, fee to read
Originalsinstant archive class after 90 daysRead only by owner or for new sizes
Hour-long retrieval classesnot for linksA 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)

ResultAction
Under 0.3Publish
0.3 to 0.7Review, or publish with a mature label by policy
Over 0.7Hold and review first
Match with a known-illegal listBlock, isolate, trained team, report as law requires
Same hash as something removedBlock, allow appeal
Scores are a model's output, not truth. Measure both kinds of error on real samples.

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

CaseSeverityProblemAnswer
Abandoned uploadlowBytes nobody ownsRemove after 24 hours
False typehighA program named .jpgFirst bytes, decode, re-encode
Pixel bombhighTiny file, huge picturePixel limit before decoding
Location in ExifcriticalHome address publishedPrivate original, re-encode
Job crash loopmediumOne file kills workersThree tries, dead-letter queue, status failed
Queue backlogmediumMinutes until readyScale by oldest job, small first
Store region downcriticalCold pictures failEdges serve what they hold; second region for reads
CDN downcriticalAll views failSecond CDN, tested; origin cannot carry 417 Gbit/s
Damaged filemediumBroken pictureChecksums, versions, second copy
Hot countermediumAll writes on one rowEdge logs, sharded counters
HotlinkingmediumAnother site uses our trafficReferrer rules, smaller copies, limits
Upload bothighA million files, storage billLimits per account and address, trust levels, daily byte alarm
Flood on one picturehighAttack on a linkEdge absorbs, limits per client at the edge
Coordinated harassmentcriticalSame picture from many accountsHash block list, OCR, review
Purge missedcriticalBlocked picture still servedPurge shield before edge, verify from outside, short browser life

Failure drill: say it before you read it

  1. 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. 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. 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. 4

    A check model fails

    Fail closed: new anonymous images wait. Say the cost: uploads look slow, nothing unsafe is published.