Design Spotify - let 80 million people listen at the same moment, answer a tap on play within 200 ms, keep the music playing when the network drops, and open a personal home screen at once. Almost all of the traffic is audio, and none of it should pass through your own servers. The staff-level signal is handing out a list of CDN URLs instead of bytes, treating the caches, the search index and the recommendation sets as copies of one source of truth, and doing the heavy work before the request arrives.
Written by a Staff+ Engineer and an Engineering Manager
12+ years of experience in distributed systems and real-time messaging. Tech lead for large-scale chat applications serving billions of users. Over 12 years of industry experience with 6 years in engineering leadership, building and scaling tech infrastructure teams that deliver end-to-end large-scale distributed systems.
Finished this lesson?
Sign in to save your progress across devices.
Tip: use ← and → to move between lessons.
Was this lesson helpful?
Rehearse this exact question with the author
45-minute mock with a Staff+ engineer who interviews at your target company. Premium members save $20.
What to Design?
Could you answer these today? Tick what you already know.
The boxes are quick to draw: an app, some services, a database, a CDN. A CDN is a network of servers close to the listeners, called edges, that hold copies of files. The interview is decided by four questions about what those boxes do at 80 million listeners. Each one is a deep dive later on this page, with three designs side by side: the one that sounds right, a better one, and the one that holds.
Swipe to see all columns
| The four questions, and the answer that sounds right | |||
|---|---|---|---|
| # | The interviewer asks | The answer that sounds right | What it misses |
| DD1 | 80 million people listen at once. Who sends them the audio? | Our streaming servers | That is 12.8 Tbps. The servers only hand out a list of CDN URLs. The audio is cut into 10-second pieces, so the quality can change in the middle of a song |
| DD2 | The home screen is personal. When does the model run? | When the app opens | Too slow, and a model outage blanks the app. Build the sets before anyone asks, refresh active listeners often, keep a fallback |
The same three habits answer all four:
Do not spend your questions on audio formats. Spend them on what the app promises its listeners.
Swipe to see all columns
| Scope Decisions | ||
|---|---|---|
| Question | Agreed answer | Why it matters |
| Do we also take in new music? | No. The catalog exists. Listener side only | No upload and no encoding. The design is about reading: play, search, home |
| How fast must a song start? | The play call answers within 200 ms, and the quality follows the network | The audio must be cut into small pieces at several quality levels, ready on a CDN (DD1) |
| How many listeners? | 80 million at the same moment, 100 million tracks | |
Out of scope (say this out loud): taking in and encoding new music, billing and subscriptions, podcasts, video and lyrics, social features, offline downloads and copy protection, and training the recommendation model. The model's output is assumed to be available.
FR1 — Search. Find tracks, artists, albums and playlists by keyword, with suggestions while the listener is still typing.
FR2 — Play. Stream any track on demand. The quality adapts to the network. Bitrate is the quality level: the number of kilobits used for one second of audio.
FR3 — Playlists. Create, rename and delete playlists. Add, remove and move tracks.
FR4 — Home feed. A home screen with playlists, albums and artists picked for this listener.
FR5 — One stream on the free tier. A free account plays on one device at a time. Premium may play on several.
The key principle behind all five
Swipe to see all columns
| Five facts and the conclusions they do not supportRead each row as: the fact on the left does not, by itself, imply the claim in the middle. | ||
|---|---|---|
| Fact | Does not imply | Why the gap exists |
| The server knows where the audio is | The server should send it | A song is 4.2 MB and its list of URLs is 10 KB. Send the list |
NFR1 — Fast start. The play call answers within 200 ms at p95. p95 means: 95 of 100 calls are at least this fast.
NFR2 — Fast search. Search results within 200 ms at p95.
NFR3 — Scale. 200 million listeners a month, 80 million at the same moment, 100 million tracks.
NFR4 — Availability. 99.95% for playback and search. A broken recommender, cache or search index never stops the music.
NFR5 — Safe playlist edits. A playlist change is confirmed within 300 ms, and two devices that edit the same playlist never silently overwrite each other.
| Capacity Thought Experiment | |
|---|---|
| Parameter | Value |
| Listeners | 200 million a month. 80 million at the same moment at peak |
| Catalog | 100 million tracks, 3.5 minutes on average |
| Bitrates | Three fixed levels: 96, 160 and 320 kbps |
| Segments | The pieces a track is cut into, 10 seconds each: 21 per track and bitrate. 120 KB, 200 KB or 400 KB |
| Audio at peak | 80 million times 160 kbps: 12.8 Tbps |
The number that identifies the real system is the gap between the audio and everything else:
audio at peak 12.8 Tbps 80 million listeners x 160 kbps
manifests at peak ~30 Gbps 380,000 play starts a second x 10 KB
ratio ~400 to 1 so the audio must never touch the app servers
Spotify is a small API that hands out URLs, next to a very large delivery network. The first four rows of the table are the interviewer's numbers. The rest are illustrative assumptions.
Interviewer signal: candidates who draw "streaming servers" between the app and the storage have missed the number. Candidates who say "12.8 Tbps cannot pass through my services, so they return a list of CDN URLs and the client pulls the audio itself" have found the system.
Three ideas shape everything:
A play request needs a decision: may this listener play, and where are the pieces of this track? The answer is the manifest, and it is 10 KB. The audio is 4.2 MB. So the services send the manifest, and the client fetches the audio from the CDN by itself.
The catalog database is the source of truth for tracks and playlists. Around it sit four helpers: a cache for sessions and manifests, a search index, a store of ready-made home sets, and the CDN. Each is a copy shaped for one kind of read, and each may be a little old. When one of them fails, the design says what happens: read the database, serve an older set, or let the listener play.
At 380,000 play starts and 200,000 searches a second, there is no time to cut audio, rank tracks or scan tables while a listener waits. All of that happens earlier. The request path is a handful of lookups.
The core recognition
This is a thin control plane on top of a CDN. The control plane is the set of services that decide: who may play, which URLs to use, what to show. The data plane, the part that moves the bytes, is the CDN.
| Design Decisions | |
|---|---|
| Design choice | Reason |
| The play call returns a manifest of signed CDN URLs | 10 KB from our servers, 4.2 MB from the CDN |
| Audio is cut into 10-second segments at 96, 160 and 320 kbps | The client can change the quality every 10 seconds, without a restart |
Three tables carry the catalog and the playlists. The fields to explain are
manifest_url, which points at audio that lives elsewhere, andversion, which protects a playlist from two editors.
One row per track. Artists and albums have tables of the same kind.
Swipe to see all columns
| tracks | ||
|---|---|---|
| Field | Type | Comment |
track_id | STRING | Key, for example t42 |
artist_id | STRING | For example a7, The Lanterns |
album_id | ||
One row per playlist, and one row per track in it.
Swipe to see all columns
| playlists | ||
|---|---|---|
| Field | Type | Comment |
playlist_id | STRING | Key, for example p7 |
user_id | STRING | The owner |
name | ||
Swipe to see all columns
| playlist_tracks | ||
|---|---|---|
| Field | Type | Comment |
playlist_id, track_id | STRING | Key |
position | INT | 1, 2, 3 and so on, with no gaps |
Swipe to see all columns
| Supporting records | ||
|---|---|---|
| Record | What it holds | Why it exists |
| Audio segment | t42/160/seg-007: 10 seconds of audio, 200 KB | The unit the CDN keeps and the client switches on. It never changes once published |
| Manifest | manifest:t42: the URLs of 21 segments at three bitrates | The answer to a play call. Cached so that a play start does not read the database |
Swipe to see all columns
| Storage | ||
|---|---|---|
| Store | Data | Consistency |
| PostgreSQL | tracks, artists, albums, playlists, users | The source of truth. Playlist changes run in transactions |
| S3 and the CDN | Audio segments at three bitrates | Written once, never changed. The CDN holds copies near the listeners |
| Redis | Sessions for 60 s, cached manifests | A helper. If it is empty, read the database or let the listener play |
Plain REST. No endpoint ever carries audio. A signed URL is a CDN address with a signature and an end time, here 5 minutes. The CDN checks the signature by itself, so it serves only listeners that the playback service has approved, without calling back.
Swipe to see all columns
| The endpoints | ||
|---|---|---|
| Call | Answered by | What it does |
GET /v1/tracks/{track_id}/stream | Playback service | Checks the session and returns the manifest: signed segment URLs at three bitrates, a bitrate to start with, and the manifest of the next track |
POST /v1/sessions/{session_id}/heartbeat | Playback service | Sent every 20 s with the position. Keeps the session alive. Answers 409 when another device took over |
GET /v1/search?q=lan&limit=10 | ||
Present the design as four short stories, each in its own colour on one whiteboard: Phase 1 press play (black), Phase 2 keep playing (blue), Phase 3 search and a playlist (green), Phase 4 the home feed (purple). All four follow Alice on her phone. The number on an arrow is the same number in the animation and in the step table.
Swipe to see all columns
| The four phases | |||
|---|---|---|---|
| Phase | Colour | Story | What it leaves behind |
| Phase 1: Press play (FR2, FR5) | Black | Alice presses play. The playback service checks her one stream and hands out a manifest. The first audio comes from the CDN | One session key |
| Phase 2: Keep playing (FR2) | Blue | The network drops and the client steps down a bitrate. A heartbeat keeps the session. The next track starts with no gap | A renewed session, one play event |
How to read the picture
t42 "Night Drive": 3:30 long, 21 segments.Each phase below is an interactive walkthrough of the same picture. It plays on its own. You can pause it, step with the arrow keys, and click any component to read its role.
Goal: answer a tap on play within 200 ms, without sending a single byte of audio from our own servers.
/v1/tracks/t42/streamClient → Playback serviceNothing is written in this step.
Swipe to see all columns
| Phase 1 step by step (black arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | Alice presses play on t42. The app calls the playback service and says: device phone-1, network good. | Nothing |
| 2 | The playback service writes Alice's session into Redis. She is on the free tier, so this is her one stream. No other device is playing. | session:alice: s-901, phone-1, t42. Gone after 60 s without a heartbeat |
Why it is built this way
The server needs little of it: about 5 ms for the session, 10 ms for the manifest, a few more to sign the URLs. That is under 20 ms on a cache hit and about 50 ms on a miss. The rest is the network between the phone and the nearest region. So two things protect the budget: a high cache hit rate, and regions close to the listeners.
Goal: keep the music going for 3:30 while the network changes, and keep the session honest without holding a connection open.
t42/160/seg-007Client → CDN edgeNothing is written in this step.
Swipe to see all columns
| Phase 2 step by step (blue arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | Alice's train enters a tunnel. Segment 7 at 160 kbps, 200 KB, takes 12 seconds to arrive. It holds only 10 seconds of audio. | Nothing |
| 2 | The app decides by itself: the next segment at 96 kbps. It asks the CDN for t42/96/seg-008, 120 KB. | Nothing |
| 3 | Few listeners near Alice play this track at 96 kbps, so the edge has no copy. It fetches the segment from the audio store once and keeps it. Alice has it about 7 seconds later. The music never stopped. | |
Why it is built this way
t42/160/seg-007 is the same URL for every listener, so an edge keeps one copy for all of them.A segment is the smallest unit in which the quality can change. With 60 seconds, a listener stays up to a minute on the wrong bitrate, and a jump in the song lands far from the target. With 2 seconds, a track becomes 105 requests where 21 would do, and every request has overhead. Five to ten seconds is the usual middle.
Goal: find a name from three letters within 200 ms, and change a playlist so that no edit is ever lost.
/v1/search?q=lan&limit=10Client → Search serviceNothing is written in this step.
Swipe to see all columns
| Phase 3 step by step (green arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | Alice types lan. After a short pause in typing, the app sends one search call. | Nothing |
| 2 | The search service asks the search index. lan is a stored token there, so this is one lookup. The answer: The Lanterns, and their track Night Drive, best match first. About 30 ms. The catalog database is not asked. | Nothing |
Why it is built this way
The first transaction raises the version to 13. The second one says "raise it if it is still 12", changes no row, and is answered with 409. That app reads the playlist again and repeats its change on version 13. Without the version, both would shift the positions from the same starting point: one track is lost, or two tracks end up at position 3.
Goal: show a personal home screen at once, with no model running while Alice waits.
play-eventsEvent log → Recommendation pipelineNothing is written in this step.
Swipe to see all columns
| Phase 4 step by step (purple arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | The recommendation pipeline reads the event log. It sees that Alice finished t42 and skipped t77 after 8 seconds. | Nothing |
| 2 | It builds Alice's home set and writes it into the feed store. Alice is active, so this is repeated every 15 minutes. The last run was at 08:45. | home:alice |
Why it is built this way
200 million listeners times 96 runs a day is 19 billion set builds a day, most of them for people who are not looking. So the pipeline sorts listeners by activity: someone who played in the last hour gets a new set every 15 minutes, everyone else every 6 hours. When a quiet listener opens the app, that event moves them to the fast group.
The deep dives are the four questions from the top of the page. Each one compares three designs for the same scenario: a Bad one, which is usually the answer that sounds right; a Good one, which still leaves a gap; and a Great one, which holds. The answers start covered. Read the scenario, decide what you would build, then click each card.
Swipe to see all columns
| Deep Dive Map | |||
|---|---|---|---|
| Deep Dive | Topic | Scenario | NFR |
Scenario: 80 million people listen at the same moment. At 160 kbps that is 12.8 Tbps of audio. One of them is Alice, who plays t42 on a train. At second 60 the train enters a tunnel and her network drops to about 133 kbps. Who sends the audio, and what does Alice hear?
Three ways to build it. Decide what you would do first. The answers are covered: click a card to reveal it.
The idea. The app asks the server for the song. The server opens the file in the audio store and streams it over a connection that stays open until the song ends.
Where it breaks. Every listener holds a connection to an app server for 3.5 minutes: 80 million open connections. All 12.8 Tbps pass through the app tier. With 10 Gbps of network per server, that is 1,280 servers that do nothing but copy bytes. A deploy or a crash cuts the music of everyone on that server.
The idea. Store each track as three files, one per bitrate, and put them on a CDN. The play call returns one URL, for example the 160 kbps file of 4.2 MB. The app downloads that file from the nearest edge.
What it fixes. The app tier. It answers with a URL and is out of the audio path. The bytes come from a server near the listener.
What it still misses. The tunnel. The quality was chosen once, for the whole song. At second 60 the 160 kbps file arrives at 133 kbps: slower than it plays. The buffer runs out and the music stalls. The app can switch to the 96 kbps file, but that is a new download, and it has to find second 60 inside it. Every change of quality is a small restart.
The key idea. Cut every track into pieces of 10 seconds, at every bitrate, before anyone plays it. Then a change of quality is not a restart. It is just a different URL for the next piece.
How it works
The three designs side by side, in one picture:
Play the three options. Switch between them with the tabs at the top of the figure.
the audio of t42Client → App serversNothing is written in this step.
Swipe to see all columns
| DD1 side by side | |||
|---|---|---|---|
| Bad: bytes through the app servers | Good: one file per bitrate | Great: a manifest of segments | |
| Who sends the audio | The app servers | The CDN | The CDN |
| Audio through our servers | 12.8 Tbps | None | None |
Check it against the scenario
| 80 million listeners, and a tunnel | |
|---|---|
| Situation | Outcome with the Great option |
| Alice presses play | A 10 KB manifest within 200 ms. The first 200 KB come from an edge near her |
| The tunnel at second 60 | Segment 7 takes 12 s. The app asks for segment 8 at 96 kbps and keeps playing from its buffer |
| The edge has no copy of a segment | The CDN fetches it from the audio store once and keeps it. Popular tracks at 160 kbps are nearly always there |
| The playback service is redeployed during the song | Nobody hears it. The app already holds the manifest and talks only to the CDN |
| Alice pulls the slider to 2:05 | |
The trade-off to name. Segments multiply the objects: 6.3 billion pieces where 300 million files would do. And the logic that picks the bitrate lives in the app, so every app version on every device has to get it right.
The server sees Alice's network only through what her app reports, and a report is old when it arrives. The app measures every download itself and decides every 10 seconds. The server only gives a hint for the very first segment.
"At 80 million concurrent listeners the audio is about 12.8 terabits a second, so it cannot go through my services. The playback service only resolves a manifest: it checks the session, reads the cached manifest for the track, signs the CDN URLs and returns them. The audio is pre-cut into 10-second segments at three fixed bitrates, and the client pulls them from the CDN edge. The client can switch bitrate at every segment boundary: if a segment downloads slower than it plays, the next one is requested one level lower. The service orchestrates, the CDN delivers."
Follow-up: "How do two songs play without a gap?" — The manifest of the next track is part of the answer. The client fetches that track's first segment while the last segment of the current one is playing, so no call is needed between the songs.
Scenario: Alice opens the app at 08:52 and expects a home screen made for her. Bob signed up today and has never played a song. Millions of people open the app in the same minutes. When is a home screen computed?
Three ways to build it. Decide what you would do first. The answers are covered: click a card to reveal it.
The idea. The home service calls the ranking model on every open. The model looks at Alice's history and ranks tracks for her, right now.
Where it breaks. The model has to choose from 100 million tracks. A run takes seconds, say 2. Alice looks at a spinner. In the morning peak every open costs a model run, and the runs queue up. And when the model servers are down, the home screen is blank. The slowest and most fragile part of the system sits on the read path.
The idea. A nightly job computes a set for every listener and writes it into a key-value store. Opening the app reads one key.
What it fixes. The read. One lookup, about 5 ms, and it works when the model is down.
What it still misses. Time. Alice has played jazz since 07:00, and her set from 02:00 knows nothing about it. An album released at 09:00 reaches the home screen tomorrow. Bob has no set at all, so his first home screen is empty.
The key idea. Keep the read as one lookup, and spend the computing where someone is listening. And never let the home screen depend on a set being there.
How it works
The three designs side by side, in one picture:
Play the three options. Switch between them with the tabs at the top of the figure.
/v1/homeClient → Home serviceNothing is written in this step.
Swipe to see all columns
| DD2 side by side | |||
|---|---|---|---|
| Bad: model on every open | Good: a nightly batch | Great: refreshed by activity | |
| Work while Alice waits | A model run | One lookup | One lookup and a filter |
| Age of Alice's set | None, after a 2 s wait | Up to 24 hours | At most 15 minutes |
Check it against the scenario
| Alice at 08:52, and Bob | |
|---|---|
| Situation | Outcome with the Great option |
| Alice opens the app at 08:52 | The set from 08:45 is read in about 5 ms. Night Drive, which she just heard, is filtered out |
| Alice plays jazz all morning | Her next set, at most 15 minutes away, knows it. The Recently played section is right within seconds |
| Bob opens the app for the first time | No set. He gets trending and editorial playlists, and his first plays start his history |
| The pipeline is down for an hour | Alice's set is 67 minutes old, not 7. The home screen opens as fast as ever |
| The feed store is down | |
The trade-off to name. Freshness costs computing: a run every 15 minutes for every active listener. Sorting listeners by activity spends it where it is seen. And what Alice did five minutes ago shows only through the filter, not in the ranking.
From the same events. A listener with an event in the last hour is in the fast group. When a quiet listener opens the app, that event moves them, and their next set comes within 15 minutes.
"I never run the model on the read path. Play events, skips and searches go to Kafka. An offline pipeline turns them into ranked candidate sets and writes one set per user into a serving store. Opening the app is one read by user id, plus a small filter for what was just played. Refresh is tiered: active users every 15 minutes, the rest every 6 hours. If a set is missing or too old, I serve trending and editorial playlists. So a recommender outage makes the home screen less personal, and never blank."
Follow-up: "What if the serving store itself is down?" — The home service keeps the trending lists in memory and returns those. Playback and search use other stores and are not affected.
Scenario: Alice types lan and expects The Lanterns after three letters. The catalog has 100 million tracks. At peak there are 200,000 queries a second, and each must answer within 200 ms. A moment later she types lantens, without the r.
Three ways to build it. Decide what you would do first. The answers are covered: click a card to reveal it.
The idea. The catalog is already in PostgreSQL. Search with WHERE name ILIKE '%lan%'.
Where it breaks. A pattern that starts with a wildcard cannot use a normal index, so the database reads its way through 100 million rows. That takes seconds, not 200 ms, and it happens on every keystroke. 200,000 such queries a second land on the database that also serves playlists and manifest misses, so those slow down too. And there is no ranking: love matches millions of rows, in no useful order.
The idea. Copy the catalog into a search index such as Elasticsearch. A background indexer copies every new or changed row, a few seconds after the write. Queries go only to the index.
What it fixes. Speed and load. The index maps each word to the tracks that contain it, so lanterns is one lookup of a few milliseconds. The catalog database is out of the search path.
What it still misses. Everything Alice actually types. The index stores whole words, so lan finds nothing. lantens finds nothing either: one letter is missing. And love returns millions of tracks ordered by text score alone, which says nothing about what she wants.
The key idea. Decide at indexing time what people will type, and store it. Then a half-typed word is an exact lookup too.
How it works
l, la, lan, lant and so on. Elasticsearch calls these edge n-grams. lan is now a stored token.lantens still finds The Lanterns.The three designs side by side, in one picture:
Play the three options. Switch between them with the tabs at the top of the figure.
/v1/search?q=lanClient → Search serviceNothing is written in this step.
Swipe to see all columns
| DD3 side by side | |||
|---|---|---|---|
| Bad: LIKE on the database | Good: a full-text index | Great: prefixes, typos, ranking | |
| lan | Found, after reading 100 million rows | Nothing | The Lanterns, one lookup |
| lantens | Nothing | Nothing | The Lanterns |
Check it against the scenario
| Three letters, 100 million tracks, one typo | |
|---|---|
| Situation | Outcome with the Great option |
| Alice types l, la, lan | The app waits for a pause, then sends one query. lan is a stored token: one lookup |
| She types lantens | One missing letter in a word of 7 is allowed: The Lanterns |
| A track was added 3 seconds ago | Not in the index yet. It appears about 5 s after the catalog write |
| A track was taken down, the index still lists it | The play call reads the catalog, finds nothing and refuses. The entry is removed |
The trade-off to name. Prefix tokens make the index larger: a word of 8 letters is stored 8 more times. Typo matching costs CPU on every query. So prefixes are stored only for names, and typos are allowed only in longer words. And the index is always a little behind the catalog: fine for search, not for deciding what may be played.
Because a short word with one letter changed is another real word. lan with one wrong letter also matches man, can, fan, lab and land. The result list fills with noise, and the query gets slower. In a longer word, one wrong letter still leaves enough to be sure what was meant.
"Search does not run on the primary database. Catalog changes land in PostgreSQL, and an asynchronous indexer copies them into Elasticsearch within seconds. For search-as-you-type I add an edge n-gram field on names, so a prefix like 'lan' is a plain term lookup and not a wildcard scan. Typos are handled at query time with fuzzy matching, edit distance one, on terms longer than four characters. Ranking combines text relevance with recent popularity and the user's own history. The index is a derived copy: I monitor its lag, and playback always checks the catalog."
Follow-up: "The index shows a track that was removed. What happens?" — Search may show it for a few seconds, but the play call reads the catalog, so it is refused. That refusal also removes the stale document.
Scenario: Alice is on the free tier: one stream. Her phone plays t42 and is at 1:12. Its last heartbeat reported 1:00. She sits down at her laptop and presses play. What should happen, and what if the phone's battery had died instead?
Three ways to build it. Decide what you would do first. The answers are covered: click a card to reveal it.
The idea. When a device starts to play, insert a row into a play_sessions table in the catalog database. Delete it when the device stops. If a row exists, a second device gets 403, already playing.
Where it breaks. A device does not always say "stop". The phone's battery dies, the row stays, and the laptop gets 403 today and tomorrow. Only support can free the account. Even when the phone is alive, Alice has to walk back to it and press pause. And 380,000 play starts a second become writes on the main database.
The idea. Keep the session in Redis with a lifetime of 60 seconds. The playing device sends a heartbeat every 20 seconds, which renews it. A second device is rejected while the key exists.
What it fixes. The dead phone. Without heartbeats the key is gone after 60 seconds, and the laptop may play. Nobody has to clean up, and the main database is not involved.
What it still misses. The living phone. This is the common case: Alice simply changes devices. The laptop gets 403, and she has to find the phone and pause it. The rule is kept, and the product is annoying.
The key idea. One stream does not mean "the first device keeps it". It means "one device at a time". Let the device that pressed play last have it, and tell the other one to stop.
How it works
session:alice with a new session, s-902 on laptop-1. The same Redis command returns the old value: s-901, t42, position 60 s.t42, starting at segment 7, which is 1:00.409, session moved.The three designs side by side, in one picture:
Play the three options. Switch between them with the tabs at the top of the figure.
/v1/tracks/t42/streamPhone → Playback serviceINSERT play_sessions (alice, phone-1)Playback service → Catalog DBalicenew rowSwipe to see all columns
| DD4 side by side | |||
|---|---|---|---|
| Bad: a permanent row, reject | Good: an expiring key, reject | Great: the newest device takes over | |
| Where the session lives | A row in the main database | A Redis key, 60 s | A Redis key, 60 s |
| The phone dies | The account is locked | Free after 60 s | Free at once: the laptop takes over |
Check it against the scenario
| The phone plays, the laptop presses play | |
|---|---|
| Situation | Outcome with the Great option |
| Alice presses play on the laptop at 1:12 | The session key now names laptop-1. The laptop plays t42 from 1:00, the last position the phone reported |
| The phone's next heartbeat, at 1:20 | 409, session moved. The phone pauses and shows where the music went |
| Both devices press play in the same second | Two writes to one key, and the later one stays. The other device learns it at its next heartbeat |
| The phone has no network | It cannot send a heartbeat or fetch segments. It plays what is in its buffer and stops |
The trade-off to name. The handoff is not exact. Both devices play until the phone's next heartbeat, at most 20 seconds, and Alice hears 12 seconds twice. A push message to the phone would stop it at once, at the price of one more channel to run. And "when unsure, allow" means that a few listeners sometimes get a second stream. That is cheaper than blocking people who did nothing wrong.
Because 1:00 is the last thing the server knows. The phone reports its position with every heartbeat, every 20 seconds, so the server is at most 20 seconds behind. Asking the phone at the moment of the handoff would be exact, but the phone may be the device with the dead battery. The design must work without it.
"I keep one small session record per user in Redis: session id, device, track and position, with a TTL of about a minute that the client refreshes with a heartbeat. For the free tier I do not reject the second device, I hand off: the new play call overwrites the record and gets the old one back, so the new device can continue from the last reported position. The old device finds out at its next heartbeat, gets a conflict and pauses. Session state is disposable: if Redis loses a record, I allow playback, and the worst case is two streams for a few seconds."
Follow-up: "What if the old device's heartbeat never arrives?" — Then it has no network, so it cannot fetch new segments or a new manifest either. It stops by itself when its buffer is empty. On the server there is nothing to clean up: the record already names the new device.
The design above treats the recommender as a box that fills the feed store. Some interviewers open that box.
| The ML side in one table | |
|---|---|
| Question | A sound first answer |
| What does the model predict? | The chance that Alice plays a track for more than 30 seconds |
| Where do the labels come from? | The play events. A full play or a save is a positive, a skip in the first 30 seconds is a negative |
| Which features matter? | Her recent plays, the artist and genre of the track, its popularity this week, the time of day, the device |
| Which model, simple first? | Two stages. Stage 1 picks a few hundred candidates: tracks liked by people with similar plays, artists she follows, new releases. Stage 2 ranks them with a small model, for example gradient-boosted trees |
Why no model runs on the read path. A model that runs offline can be slow, large, or down for an hour. Alice only sees a set that is a little older.
Cold start. Bob has no plays, so he gets trending and editorial playlists. The new track t99 has no plays either: it is described by its artist and genre, and gets one of a few slots kept for new releases.
The loop feeds itself. The model learns only from what it showed, so popular tracks look better and better. Keep a small share of every set for tracks the model is unsure about.
No, and the skip is the clearer one. It means: she heard it and did not want it. A song that played to the end may mean she liked it, or that she left the room. So an early skip is a strong negative, a full play a mild positive, and a save the strongest positive.
| If the interviewer keeps going | |
|---|---|
| Question | Short answer |
| Alice pauses for an hour and comes back | The signed URLs have expired. The app calls the play endpoint again with its position, and the new manifest starts at the segment that holds that second |
| The first second feels slow | The first segment decides it. Fetch it at 96 kbps, 120 KB, or publish a short first segment of 2 seconds. Then step up |
| A big album comes out at midnight | Millions ask for the same new segments at once. Push them to the edges before midnight, and fill the manifest cache early |
| A track must be taken down | Remove it from the catalog first: from then on no play call succeeds. Then purge the CDN and delete the index entry. Search may show it for a few seconds, play will not work |
80 million listeners are 12.8 Tbps. Return a manifest and let the client pull the audio from the CDN.
The quality is then chosen once, and a weak network means a stall or a restart. Cut the track into 10-second segments at three bitrates.
The server does not see the listener's network. The client measures every download and decides for the next segment.
It is slow, and its outage becomes an app outage. Compute the sets ahead of time and read them with one lookup.
A new listener or a late pipeline then means an empty screen. Keep trending and editorial playlists ready.
A LIKE query reads every row and takes capacity from playlists and playback. Search a separate index that is fed in the background.
The cache, the index and the home sets are copies and may be old. Rebuild them from the catalog and the event log, and let the catalog decide what may be played.
A phone with a dead battery then locks the account. Give the session a short lifetime, renew it with a heartbeat, and let the newest device take over.
The shape of a strong answer: start with the bandwidth and take the audio off your servers. Return a manifest, cut the audio into short segments, and let the client choose the quality. Keep one source of truth, with a cache, a search index and a feed store around it as copies. Compute home sets before anyone asks, and keep a fallback. Keep sessions short-lived, and let the newest device win.
Keep the bytes off your servers
The play call returns 10 KB of signed CDN URLs. The 12.8 Tbps of audio travel from the edge to the listener, in 10-second pieces that can change quality at every step.
One source of truth, and helpers that may lag
The catalog database is right. Redis, the search index and the feed store are fast copies. Each may be a little old, each can be rebuilt, and the design says what happens when each one fails.
Do the heavy work before the request
Segments are cut when a track is published. Home sets are built when events arrive. The index is updated when a row changes. A request is a few lookups.
| What the interviewer expects at each level | |
|---|---|
| Level | A strong answer shows |
| Junior | The entities: tracks, playlists, users. The basic flows: search, play, make a playlist. And the knowledge that audio does not go through the application servers |
| Mid-level | Explains why a CDN and a manifest are needed, with the bandwidth number. Says which store is the source of truth and which are copies: PostgreSQL, Elasticsearch, Redis |
| Senior | Makes manifest-based delivery the centre of the design and defends the 200 ms budget with caching, pre-cut segments and edge placement. Names what may lag or be rebuilt without breaking playback, and covers the home fallback, the device handoff and what to monitor |
These aren't toy problems — they reflect real infrastructure challenges at companies that stream media to millions of people at once. If you want to walk through this design in a mock interview or get feedback on your own approach, book a session with us. We're here to help you sharpen your thinking, build your confidence, and land your next offer.
Pick an answer for each question, and you see at once whether it is right. Show explanation opens the answer, why it is right, and why each of the other options fails.
Question 1 of 10
80 million people listen at the same moment at 160 kbps. How much audio is that in total?
Question 2 of 10
Alice presses play. What does the playback service send back?
Question 3 of 10
A segment of 10 seconds takes 12 seconds to download. What does the client do next?
Question 4 of 10
Where do the items on Alice's home screen come from?
Question 5 of 10
Bob signed up today. There is no home set for him. What does the home service return?
Question 6 of 10
Alice skips a track after 8 seconds. How should the recommender read that?
Question 7 of 10
The search index also stores l, la, lan, lant for the name Lanterns. Why?
Question 8 of 10
Alice's phone and laptop both add a track to the same playlist, and both saw version 12. What prevents a silent overwrite?
Question 9 of 10
Redis loses Alice's session key in the middle of a song. What happens?
Question 10 of 10
Alice is on the free tier. Her phone is playing, and she presses play on her laptop. What happens?
| DD3 | Alice types three letters. How do you find the artist among 100 million tracks? | A LIKE query on the catalog | It reads every row. A search index stores whole words, so it also needs prefix tokens, typo tolerance and a ranking |
| DD4 | A free account plays on one device. Alice moves to her laptop. What happens? | Reject the second device | A dead phone then locks the account. Use a session that expires, and let the newest device take over |
| 12.8 Tbps of audio. No cluster of our own can send that (DD1) |
| Free and premium? | Free: one stream at a time. Premium: several devices | The server must know, cheaply, which device is playing right now (DD4) |
| Recommendations are down. What does the listener see? | Music still plays. The home screen is less personal | Playback never depends on the recommender. The home feed needs a fallback (DD2) |
| How fresh must search be? | A new track is found within seconds | The search index is a copy of the catalog and may be a little behind (DD3) |
| The song started at 160 kbps | It can finish at 160 kbps | A phone's network changes within one song. The quality must be able to change every few seconds |
| The search index returned a track | The track exists | The index is a copy, a few seconds behind. A track can be removed after it was indexed |
| A home set is stored for Alice | The set is fresh | It was computed minutes or hours ago. It carries the time it was made |
| No session key is found | Nobody is playing | The cache may have lost the key. When unsure, let the listener play |
| Stored audio |
| About 15 MB per track over three bitrates: 1.5 PB, in 6.3 billion segments |
| Play starts | 80 million listeners, a new track every 210 s: about 380,000 a second |
| Manifests | About 10 KB per play start: 30 Gbps |
| Heartbeats | The app says "still playing" every 20 s: 4 million small writes a second |
| Search | 200,000 queries a second at peak |
| Playlist changes | 50,000 a second at peak |
| Manifests are cached in Redis, the database is the fallback |
| A play start touches only the cache, and a cache loss costs speed, not correctness |
| A session key that lives 60 s, renewed by a heartbeat | A device that dies frees the account by itself |
| The newest device takes over the session | Moving from phone to laptop works, and nothing can lock an account |
| Search runs on its own index, fed from the catalog in the background | 200,000 queries a second never reach the database |
| Home sets are computed offline and read with one lookup | No model runs while a listener waits, and a model outage is not an app outage |
| Every playlist change checks a version number | Two devices cannot overwrite each other without noticing |
STRING |
| The album this track belongs to |
title | STRING | For example Night Drive |
duration_ms | INT | 210,000 for a track of 3:30 |
manifest_url | STRING | Where the list of this track's segments is. The audio itself is never in the database |
STRING |
| For example Road Trip |
version | INT | Goes up by one with every change. A write must name the version it saw |
added_at |
TIMESTAMP |
| When the track was added |
| Session |
session:alice: session id, device, track and position. Gone 60 s after the last heartbeat |
| The one-stream rule (DD4) |
| Search document | A track with its title, artist, prefix tokens and its plays of the last 7 days | What the search index answers from (DD3) |
| Home set | home:alice: three ranked sections, and the time they were computed | Read with one lookup when the app opens (DD2) |
| Elasticsearch | A searchable copy of the catalog | A few seconds behind. Can be rebuilt from PostgreSQL |
| Feed store | One ready-made home set per listener, and their recent plays | Minutes old by design. Can be rebuilt from the event log |
| Kafka | Play events | Append only, kept for weeks |
| Search service |
| Ranked tracks, artists, albums and playlists, from the search index |
POST /v1/playlists | Playlist service | Creates a playlist and returns its id |
PUT /v1/playlists/{playlist_id}/tracks | Playlist service | Adds, removes or moves tracks. Carries the version the client saw. 409 if that version is no longer current |
GET /v1/home | Home service | The ready-made sections for this listener |
POST /v1/events | Event log | A batch of play events: started, completed, skipped, seek |
| Phase 3: Search and a playlist (FR1, FR3) | Green | Alice types three letters, finds the track and adds it to a playlist | The playlist, one version further |
| Phase 4: The home feed (FR4) | Purple | A pipeline builds Alice's home set before she asks. Opening the app is one lookup | Nothing new. The work was done earlier |
| 3 |
It reads the manifest of t42 from Redis: a hit, about 10 ms. Only on a miss does it read the track from the catalog database, about 30 ms, and fill the cache. |
| Nothing |
| 4 | It answers: session s-901, 21 segments at three bitrates as signed CDN URLs, start at 160 kbps, and the manifest of the next track t43. About 10 KB. | Nothing |
| 5 | The app asks the CDN for the first segment at 160 kbps. | Nothing |
| 6 | The CDN edge sends 200 KB: the first 10 seconds of audio. The music starts. | Nothing. No audio passed the playback service |
| A copy of the segment at the edge |
| 4 | Every 20 seconds the app sends a heartbeat with its position, now 80 s. The playback service renews the session. | session:alice: 60 s more, position 80 s |
| 5 | The network is back and the app is at 160 kbps again. While the last segment plays, it fetches the first segment of t43, using the manifest it already has. | Nothing |
| 6 | The app reports: t42 completed, 210 s. The event goes to the event log. | One event in the topic play-events |
| 3 |
| Alice adds Night Drive to her playlist Road Trip at position 3. The app sends the change with the version it saw: 12. |
| Nothing |
| 4 | The playlist service runs one transaction: raise the version from 12 to 13, only if it is still 12. Move positions 3 and up by one. Insert the new row. | playlists p7: version 13. playlist_tracks: p7, t42, position 3 |
| 5 | In the background: a label adds the new track t99 to the catalog at 09:00. The indexer copies the row into the search index about 5 seconds later. | Document t99 in the search index |
| 3 | At 08:52 Alice opens the app. It calls the home service. | Nothing |
| 4 | The home service reads home:alice and her recent plays from the feed store. One lookup. The set is 7 minutes old. | Nothing |
| 5 | It takes what she played in the last hour out of the recommendations and returns three sections: Made for Alice, Recently played, Trending. | Nothing. No model ran |
| DD1 |
| Who sends the audio |
| 80 million listeners, and a tunnel in the middle of a song |
| NFR1, NFR3 — Fast start, scale |
| DD2 | A personal home feed that opens at once | Alice opens the app at 08:52. Bob signed up today | NFR4 — Availability |
| DD3 | Search as you type | Three letters, 100 million tracks, one typo | NFR2 — Fast search |
| DD4 | One stream, and moving between devices | The phone plays, the laptop presses play | NFR4, FR5 — One stream |
| What the play call returns |
| 4.2 MB of audio |
| One URL |
| A 10 KB manifest |
| The network drops in the middle of a song | The stream stalls | It stalls, or another file is started | The next 10 seconds come at a lower bitrate |
| Segment 13 holds seconds 120 to 130. The app fetches it directly |
| Bob, a new listener |
| A slow, generic answer |
| No set: an empty screen |
| Trending and editorial playlists |
| The model is down | A blank home screen | Yesterday's set | An older set, then the fallback |
| The home service returns the trending lists it keeps in memory. Playback and search are not touched |
| love |
| Millions of rows, no order |
| Millions, by text score |
| The most played first, Alice's artists higher |
| Load on the catalog database | 200,000 scans a second | None | None |
| The search index is lost |
| It is rebuilt from the catalog database. Playback and playlists never depended on it |
| The phone is alive, the laptop presses play |
| 403 |
| 403 |
| The laptop plays, the phone pauses |
| Cost of a play start | A database write | A Redis write | A Redis write |
| Redis loses the key |
| The next heartbeat or play call writes it again. At worst two devices play for a moment |
| Alice moves to premium | The key holds a short list of sessions. Her plan says how many |
| Hide last week's plays. Does stage 1 find them (recall)? Does stage 2 put them near the top (NDCG)? |
| The online metric? | An A/B test: listening time, skip rate, saves |
| How is it served? | Offline, into the feed store. A request is one lookup and a filter |
| How is it watched and rolled out? | The age of the sets, the share of fallback answers, the skip rate. A new model first runs in the shadow: it builds sets that nobody sees, to compare with the live ones. Then it serves a few percent of listeners |
| Playlist positions with no gaps are costly for long lists |
| Moving a track rewrites every position after it. For very long playlists, use positions with gaps between them, so a move changes one row |
| 50,000 playlist changes a second on PostgreSQL | Split the playlist tables over several database servers by playlist id. One change touches one playlist, so it stays on one server |
| Redis is down | Each playback server keeps the hottest manifests in memory. The rest are read from the catalog database, 30 ms each, behind a limit that protects it. Sessions are not checked for a while: listeners play |
| The recommendation pipeline is down | Sets get older. After a day the home service switches to trending and editorial playlists. Nothing else notices |
| What do you monitor? | The share of plays that stall, the time to first audio, the cache hit rate at the edge, the lag of the search index, and the age of the home sets |