Ch.73: System Design: Build a Spotify-Style Music Service
Outline
- 0:00 From Play to another device
- 0:45 The complete service
- 1:15 Requirements
- 1:57 Size the media path
- 2:36 Prepare tracks and preserve playlists
- 3:36 Follow the first sound
- 4:30 Calculate the playback buffer
- 5:23 Seek and track playback position
- 6:33 Save intent and delivery work
- 7:26 Hand off to the speaker
- 9:28 Lost reports and newer commands
- 10:47 Measure what listeners hear
- 11:37 Return to the architecture
Transcript
0:00 A music streaming service turns a chosen recording into sound. We'll design that path, calculate how long a buffer survives a slow link, and trace a transfer with a lost reply. You tap Play on Spotify, hear it on your phone, then choose the speaker. The music moves across the room. What actually moved? Playback did. The speaker fetches its own audio. Spotify's Connect guide describes the phone as a controller, rather than a relay forwarding the song bytes. Ah, so the bytes take one route and the buttons take another.
0:31 That phone can keep controlling the song without carrying it. This is our proposed system, informed by public documentation, with the source links in the description. We'll keep the sound and its remote control separate on the map. With those two paths in mind, follow the highlighted song route across this map: a recording becomes playable files, a nearby delivery cache supplies them, and the speaker turns them into sound. The upper route prepares the files before that journey can begin. So my phone gets promoted to remote control.
1:02 Along the bottom, commands leave the phone and device reports come back. We'll follow those buttons after the bytes. And that remote still owes us an honest answer. Before choosing services, what should the listener be able to do? So, four functional requirements for that song: find it, keep its playlist ordered, play or pause or jump to a chosen time, and transfer to one online device. I'd keep Pending beside those actions. A spinner is annoying; the app saying Playing while the room stays quiet is worse.
1:33 Yeah, I'd trust the room over that label. Those are the actions. Non-functional requirements set how well they work: fast first sound, few interruptions, and accepted playlist and control changes that survive a service restart. We aren't building recommendations, royalty accounting, offline downloads or speakers playing in perfect lockstep. That last one needs much tighter clock coordination than changing the active player. Then the device's confirmation is part of the product. Let's size the media path with an invented workload: one million simultaneous listeners, each receiving 192 kilobits per second of encoded audio.
2:06 Across that million listeners, the payload totals 192 gigabits per second. Network overhead and variable-rate peaks would add more. So the application server shouldn't relay every song byte. A content delivery network, or CDN, serves reusable media from caches near listeners. Our API handles the smaller control requests. That sizes shared delivery. One listener's connection can still slow down; we'll need the player to react to that. First, how do we get a playable recording into those caches? Before anyone presses Play on track T, an ingestion worker validates the uploaded recording and encodes playable versions.
2:43 Each version keeps that song in a particular format and quality. We store those media objects under immutable versioned names. Publish the ready catalog version only after its files and timeline information exist. A search result shouldn't lead to an unfinished encoding job. Where does playlist P's order live if this service restarts? In P's database row, as ordered track identifiers: T, U and V. Save that order before confirming the edit. If the process dies, its replacement reads the same record.
3:14 Choosing T sends that track to playback. Suppose search still lists T after its availability changes. Must the index update before anyone can press Play? No, the playback resolver can recheck current availability and account permission. Search helps us discover a track; it doesn't authorize playing it. Right, Play can reject a stale result without making every search update synchronous. Once the track is ready, take a Play request for track T on device D. Our playback resolver checks access, chooses a compatible version, and returns a media location with short-lived delivery authorization.
3:48 Device D fetches the bytes from the CDN. The cache can reuse the immutable audio object, but it must still validate permission. A cache hit isn't permission to listen. And expiring authorization can't erase bytes already downloaded. Then the player buffers encoded bytes and decodes them into sound. That buffer is audio downloaded ahead of the current listening position. We don't need the whole song before starting. Hmm, I think I'd ask for more audio upfront on an unreliable connection. What does that cost the first Play?
4:20 More waiting before the first note. The extra reserve can protect playback afterward, but we pay for it during startup. We should choose those amounts separately. Now take the illustrative audio rate. Divide by 8 bits per byte. That's 24,000 bytes per second, or 96,000 for a segment containing 4 seconds of the song. 20 seconds of reserve sounds generous. If arrivals fall to half the needed rate, can we keep playing at this quality? For a while. Each second we play 1 second of audio, but only half a second arrives.
4:53 Look at the shrinking bar. Ah, we'd spend the reserve at half speed. So our 20-second buffer lasts 40 seconds under that continuing deficit. With no arrivals, it lasts 20. Right, that reserve buys time to detect the slowdown and fetch a lower-rate version. Detection, downloading and decoding still have to fit inside that window. And 20 seconds is our running buffer example, not a rule to make everyone wait 20 seconds before a song. Those are different decisions. Because changing quality changes how many bytes represent a moment in the song, a seek must preserve media time, not a byte offset copied from another encoding.
5:32 On these aligned 4-second segments, a seek to 2 minutes 3.5 seconds lands inside the segment beginning at 2 minutes. Fetch it, then decode past the first 3.5 seconds. So those different byte counts still land us at the same song moment. Apple's authoring guide requires aligned boundaries across quality versions for its streaming format. Once playback starts, what keeps the progress display moving between reports? It saves a song position and a steady elapsed-time clock reading together. If 2 seconds pass while audio keeps playing, add those 2 seconds: our 2-minute position becomes 2 minutes and 2 seconds.
6:10 Wait, if that clock keeps ticking through a stall, won't our progress bar get ahead of the song? Yeah, the clock keeps going; the song position freezes. Save a fresh anchor when playback resumes. A seek or new track also resets it. Ah, counting that stall would add 5 seconds the listener never heard. The player must leave that time out; an old server report can't fix its current position. With stale reports, the control path needs care. The phone sends what the account wants; the player reports what it has done.
6:40 Spotify's transfer API warns that ordering with other player calls isn't guaranteed. That warning would make me distrust a tidy status row. Suppose we save transfer 42, crash before sending Pause, and the phone keeps playing. What survives that crash to get Pause delivered? For our design, save the new intent and its Pause command in one transaction. Commit only if the account revision still matches the one we read. That saved command is the outbox entry; a delivery worker can find it after restart.
7:12 Ah, so restarting the service doesn't forget that it owes the phone a Pause. It still hasn't heard the phone stop. Exactly. Those are our three separate boxes: desired state committed, command delivered, device report received. Next, take an online handoff. Accept transfer 42 as pending, then send Pause to the phone that's playing. Wait for its acknowledgement that playback stopped, including the stopped position. Say the phone stops 2 minutes into the track, but its reply gets lost. If we retry Pause, do we get a different position after waiting?
7:46 Give that Pause a stable command identifier. The phone saves its first result before replying, including where it stopped. A duplicate returns that original result without pausing again. So that's our stopped phone. The speaker is still waiting. What makes it safe to start the next phase? Check that transfer 42 is still current and waiting for the old stop. Then commit the new phase and the speaker's Start command together. A duplicate Pause reply can't advance a phase that's already changed. And that Start uses its own command identifier with the saved media position.
8:19 Now the speaker retrieves those bytes, fills its buffer and prepares the decoder. We're following the same song again. Playback starts and the speaker reports Playing for revision 42. That current report lets the controller show Playing on speaker. Accepting the transfer alone didn't justify that label. Hold on. What if the speaker starts playing, then crashes before saving that result? The phone's saved result still handles the earlier retry. This speaker crashed before storing its result. On recovery, ask what state and position we can observe now, then load the latest committed request.
8:53 The speaker's pre-crash audible progress remains uncertain. A command identifier can't make sound and storage one atomic action. My instinct is to shorten the normal handoff's quiet gap. Could the speaker fetch the song before we stop the phone? Yes. It can fetch authorized bytes and fill its buffer while the phone plays. Preparing the speaker doesn't permit sound yet; that still waits for the phone's stopped-position reply. So we've moved a track position and control responsibility, rather than shipping the phone's buffer to the speaker. Perfectly synchronized room audio is a separate problem.
9:28 Now lose the speaker's Playing report. The Start command arrived, so the speaker may already be playing. Our service sees a missing acknowledgement, not proof of silence. Suppose the interface switches its label back to the phone. But we already stopped it, didn't we? We did. Keep the transfer unconfirmed, ask the devices for current state, and retry the same command identifier. Then suppose the listener presses Pause and the account accepts revision 43. The desired row now says Paused, with confirmation still unknown.
10:00 The delayed Playing report for 42 finally arrives. It's real evidence of an older action. It cannot replace the newer Pause in our current account row. What does our speaker know right now? Only 42; 43 hasn't reached it. Keep that late report as older evidence. Duplicate Start returns its saved result without restarting sound. Reject a new command below the highest revision that device has actually seen. Hold on. So a listener can press Pause, get a successful response, and still hear music on a disconnected device?
10:32 Yes. Success records the accepted intent; it's little comfort while the music keeps going. We can't switch off a speaker through a broken connection. Even the first phone Pause can be unconfirmed, which means our normal handoff must wait. Because these failures sound different, keep their measurements separate: tap to first sound, stalls while playing, and command to device acknowledgement. Put the session and revision on reports. We can then connect that late Playing report to the Pause the listener thought had worked. Spotify's 2018 network delivery experiment cut stutter while startup delay stayed the same.
11:08 Measuring just that first sound would have missed the change. Yeah, I'd keep both measures in view when debugging playback. For example, a control-service outage may leave buffered playback going while a new Pause remains unconfirmed. An audio-delivery failure threatens the buffer instead. One generic availability counter would hide that difference. I'd check the command path before blaming the buffer. So 'it took ages to start', 'it kept stopping', and 'Pause did nothing' send us to different parts of that map.
11:37 Finally, on the same architecture, preparation creates ready track versions. Search and playlists help choose one. The resolver authorizes it, and nearby media delivery feeds the player's buffer and decoder. Right. That song can keep arriving while the controls are out of reach. The account path records intent and delivers commands; reports tell us what was confirmed. Moving playback carries a media position to the new player, which retrieves the recording itself. When contact disappears, preserve the accepted action and show what remains unknown.
12:09 That's how a simple Play button can stay honest about a much larger system. Thanks for listening to Learning Podcasts.