Design a music streaming service like Spotify
hard 50 minAny of 100 million songs starts within a fifth of a second, keeps playing on a bad network, follows the listener from phone to speaker, and is counted once so that artists are paid.
See it run
One song from tap to ear, its quality while the network changes, and the slower paths beside it: search, mixes, downloads and devices.
Operations
Play a track
A small request says yes and returns a manifest. The audio comes from the edge.
Step 1 of 11
Tap
track
t_81
device
phone
The app sends the track and its device. Why: we must know that this person may play this song here.
Step 1: Tap
def start(user, track, device): claims = verify(user.token) # no call if user.country not in track.countries: return 403, "not_available_in_country" m = cache.get(track.id) or load(track.id) rates = [r for r in m.rates if r <= claims.max_rate] sig = sign(track.id, expires=now() + 3600) events.later("play_started", new_play_id()) return 200, manifest(m, rates, sig)- Time
- under 200 ms
- Load
- 306,000/s peak
- First piece
- 24 KB
- Signed for
- 1 hour
For the next track in the queue, do all of this before the listener taps.
In the real world
The same music streaming doing real jobs. Pick one and step through it.
Edges stop answering at 20:00.
Step 1 of 4
Fetches fail
buffer
30 s
Players still hold up to 30 seconds of music.
Step 1: Fetches fail
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Reading starts a second as streams
criticalA song lasts minutes. The bandwidth becomes 225 times too small.
Wrongstreams = starts_per_second # 100,000Rightstreams = starts_per_second * 225 # 22.5 millionEncrypting files per person
criticalNo two listeners share bytes, so caches never hit.
Wrongfile = encrypt(track, key_of(user))Rightfile = encrypt(track, key_of(track))licence = issue(user, device, key_of(track))Paying from counters
criticalA timed-out increment is unknown, and fake plays cannot be taken out.
Wrongcounter.add(track, 1)Rightlog.append(play_id, track, heard_ms)# remove repeats, then close the periodCaching the personal result
majorAnother listener gets the first one's order.
Wrongcache[q] = rank(found, user)Rightcache[(q, country, language)] = foundreturn rank(found, user)Removing by position
majorSomebody inserted a song a moment ago; the wrong one goes.
Wrongremove(position=7)Rightremove(entry_id="e_30", base="s_41")
Interview tips
Lead with numbers
- 102,000 starts a second, 306,000 at peak.
- 68.8M listening, 11 Tb/s.
- So audio never touches a service.
Trace one song
- Label, encoder, storage, region, edge, buffer, ear.
- Say what is cached at each place.
- Say what fails at each place.
Say trade-offs
- Four rates cost storage and save silence.
- Weekly mixes cost freshness.
- Licences leave removed songs on devices for a while.
Join product and system
- A mix is a table with a deadline.
- A play is money.
- A transfer is one compare-and-set.