Design YouTube
hard 45 minAnyone may upload a video, and anyone may watch it on any screen.
See it run
An upload, an hour of video cut in pieces, a viewer whose network changes, and a home page.
Operations
Upload
A 2 GiB file reaches storage in 256 parts and becomes a video.
Step 1 of 17
Pick a file
file
2 GiB, mp4
The app checks the type and the size before anything is sent.
Step 1: Pick a file
def open_upload(user, meta): check_quota(user); check_type(meta) v = db.insert_video(state="uploading") return sessions.create(v, part=8 * MiB, hours=24)def part_urls(session, numbers): return {n: storage.sign_put(session, n) for n in numbers}def complete(session): # idempotent parts = storage.list_parts(session) require(parts == session.expected) storage.join(session); scan(session); probe(session) db.set_state(session.video, "processing") queue.add_once(session.video)- Time
- 14 min at 20 Mb/s
- Load
- 256 parts of 8 MiB
The part size follows from the file size. At most 10,000 parts are allowed in S3.
In the real world
The same video sharing doing real jobs. Pick one and step through it.
Ten times the normal traffic for a page.
Step 1 of 5
The wave
- Traffic
- 10 times
Clients that fail wait a random, growing time before they try again.
Step 1: The wave
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Send files through the API
criticalAll bytes are carried twice, and a deploy breaks uploads.
WrongPOST /videos (2 GB body)RightPOST /uploads -> signed part links to storageEncode inside the request
criticalAn hour of video needs about 20 core-hours. The request dies first.
Wrongsave(file); transcode(file); return 200Rightcomplete(session); queue.add_once(video); return 202Count messages to find the end
majorA repeated message makes the rung look complete while a piece is missing.
Wrongif done_messages == 360: package()Rightif storage.count(video, rung) == 360: package()Cut renditions at different times
majorThe player cannot switch without a jump.
Wrongkeyframes wherever each encoder likesRightsame segment times in every renditionAdd one to the row
majorA hit brings thousands of updates a second to one row.
WrongUPDATE videos SET views = views + 1Rightevents.append(view) # sums per minute
Interview tips
Two systems
- A factory that may wait.
- A shop that may not.
- They meet in storage and one row.
Size both ways
- Hours in: cores and storage.
- Hours out: bits per second.
- Check given numbers against each other.
Publish early
- Low rungs first.
- Ready means playable.
- High rungs join the manifest.
Spend with care
- Better codecs for hot videos.
- Cold classes for old files.
- Rungs on demand for the long tail.