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.
See it run
Follow a picture from the phone to the private store, through the worker, out to the edge, and back down again.
Operations
Upload a picture
The API gives permission, the file goes straight to storage, the link comes back before processing.
Step 1 of 9
Ask for permission
bytes
2.4 MB
type
image/jpeg
Size, type and who is asking. Why: refuse before any bytes move.
Step 1: Ask for permission
def open_upload(req): limits.check(req.client) # 429 if over if req.bytes > 20 * MB: return 413 return store.signed_put(new_key(), req.bytes, minutes=15)def complete(upload, key): # idempotent by key obj = store.head(upload.key) # really there? image_id = insert_if_absent(random_base62(7), "processing") queue.send(image_id) # a sweeper repeats it if lost return 201, link(image_id), delete_token- Time
- 0.3 s after the file
- Load
- 116/s
- Peak (3x)
- 347/s
- Upload traffic
- 116 MB/s
Store first, record second, job third. A lost job is found later; a record without a file never exists.
In the real world
The same image hosting doing real jobs. Pick one and step through it.
A 20 MB upload stops at 80%.
Step 1 of 4
80%
offset
16 MB
16 of 20 MB arrived, then nothing.
Step 1: 80%
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Serving the original until sizes are ready
criticalIt may hold the place it was taken, and nobody has checked it. Caches keep it.
Wrongreturn redirect(original_url)Rightreturn placeholder(max_age=5)Any size from the address
majorA script can ask for 1x1, 1x2, 1x3 and fill CPU and cache.
Wrongresize(image, int(width))Rightif size not in SIZES: return 404Deleting the blob with the record
criticalOther people's records may point at the same bytes.
Wrongstore.delete(image.hash)Rightrefs.delete(image.hash, image.id)if refs.empty(image.hash): mark_for_sweep()Counting views in the image row
major95% of views never reach it, and a famous picture makes one row hot.
WrongUPDATE images SET views = views + 1Rightcounts = sum_per_minute(edge_logs)Trusting the file name
criticalA name says nothing about the content.
Wrongif name.endswith(".jpg"): accept()Rightif real_type(first_bytes) in ALLOWED: decode_in_sandbox()
Interview tips
Start from bytes
- 17.4 GB/s is the problem statement.
- 500 views to one upload.
- 1% reaches the store.
Name who waits
- Uploader: for the original.
- Viewer: for a cache.
- Nobody: for thumbnails.
Show judgement
- Gate before public.
- People for close cases.
- Law named, not guessed.
Mention money
- Smaller formats first.
- Cold large files only.
- Minimum sizes and fees.