The Problem#
Design a service where anyone can press play on almost any song ever recorded and hear it instantly, on any device, anywhere:
- A listener opens the app on a train, types
bohemian, taps the first result, and the song starts in well under half a second. When it ends, the next track in the queue starts with no gap at all. - The catalogue holds over 100 million tracks, plus millions of podcasts and audiobooks. New releases arrive every day from record labels and distributors, mostly on Friday at midnight local time.
- The service has hundreds of millions of monthly listeners. Each listens for an hour or more a day, which makes audio delivery one of the largest bandwidth bills on the internet.
- Listeners build playlists. Some are private, some are shared with friends and edited together, and some (editorial playlists) have tens of millions of followers.
- Every listener gets personalised playlists, such as a weekly mix of songs they have never heard but will probably like. These are generated for every user, every week.
- Premium listeners can download music to listen offline on a plane. The files must not be copyable to other devices, and the rights must expire if the subscription lapses.
- Every play that lasts long enough counts as a stream. Streams decide how billions of dollars a year are split between record labels, publishers, songwriters and artists. The counting must be correct, auditable and resistant to fraud.
Spotify, Apple Music, YouTube Music, Amazon Music, Deezer, Tidal, SoundCloud, JioSaavn and many regional services solve this problem. Spotify is the reference case here. Public sources say it has over 100 million songs and more than 750 million monthly active users. It ran its own data centres and an early peer-to-peer delivery system, ended that P2P system in 2014, and moved most of its infrastructure to Google Cloud from 2016. We use what Spotify has published (its help pages, engineering blog and a 2010 research paper on its P2P design) as anchors, and hedge anything that is not public.
What makes the problem interesting:
- It looks like video streaming, but the numbers are different. A song is small (about 3–10 MB) and short (about 3–4 minutes), and a listener plays many of them back to back. The hard part is not adaptive bitrate over a long movie. It is making every one of thousands of track starts per listener per week feel instant, and making track changes seamless.
- The workload is extremely skewed. A few hundred thousand tracks get most of the plays, while tens of millions of tracks are played a handful of times a year. Caches love the head and hate the tail. The design must serve both cheaply.
- Metadata is a rights problem as much as a data problem. Whether a track is playable depends on the listener's country, the date, the label's licence, the user's plan and the device. The same song can appear on many releases with different rights in different markets.
- Playback has to survive bad networks. Phones go through tunnels and planes have no network at all. The client therefore keeps its own cache, prefetches the next track and supports full offline mode. The client is a major part of the system, not a thin view.
- Personalisation is the product. A huge share of listening starts from recommendations, home-screen shelves and generated playlists. That means a big data pipeline: billions of listening events a day feed models, and the models feed playlists that must be ready on Monday morning for every user.
- The money pipeline is strict. Most of the system can be eventually consistent and approximate. Stream counting for royalties cannot: it must be deduplicated, explainable to auditors and labels, and defended against bots.
Analogy. Think of a gigantic record shop with a library card system and a radio station rolled into one. The warehouse (object storage) holds a master copy of every record ever pressed, in several sizes. Branch shops near every neighbourhood (CDN edge servers) keep copies of the records people in that area actually play. Each listener also carries a small crate of their favourites (the client cache). The card catalogue (the metadata service) says which records exist, who made them and whether this listener in this country may play them. Personal mixtapes (playlists) are lists of catalogue cards, not copies of records. A team of DJs who know every listener's taste (the recommendation system) makes a fresh mixtape for everyone each week. Every time a record is played for more than half a minute, a tally clerk (the event and royalty pipeline) makes a mark that later decides who gets paid.
Background: a few terms used in this design#
- Track (recording): one specific recorded performance of a song, identified by an ISRC (International Standard Recording Code). The same recording can appear on several releases.
- Work (composition): the underlying song as written, with its songwriters and publishers, identified by an ISWC. One work can have many recordings (covers, live versions).
- Release (album, single, EP): a product a label delivers, identified by a UPC/EAN barcode. It groups tracks in order and carries release dates and territories.
- Distributor / licensor: the label or aggregator (for example, a major label, or a service such as DistroKid or TuneCore for independent artists) that delivers audio, metadata and rights to the service. Deliveries usually follow the DDEX standards (Digital Data Exchange), such as the ERN (Electronic Release Notification) message.
- Master: the original lossless audio file the distributor supplies, usually WAV or FLAC at 16 or 24 bits and 44.1 kHz or higher.
- Codec: an algorithm that compresses audio. Lossy codecs (Ogg Vorbis, AAC, Opus, MP3) throw away sounds the ear is unlikely to notice. Lossless codecs (FLAC, ALAC) compress without losing anything.
- Bitrate: how many bits per second of audio a file uses, for example 160 kbps. Higher bitrates sound better and cost more storage and bandwidth.
- Encoding ladder: the set of renditions produced for each track, such as 24, 96, 160 and 320 kbps lossy plus lossless.
- Loudness normalisation: adjusting playback volume so all tracks sound about equally loud. It is measured in LUFS (loudness units relative to full scale) using the ITU-R BS.1770 standard.
- Gapless playback: playing consecutive tracks (for example, a live album) with no silence between them, which needs exact knowledge of each file's encoder delay and padding.
- CDN (content delivery network): a network of cache servers close to users. Audio files are served from the CDN, not from the service's own application servers.
- Signed URL / access token: a URL or token that grants time-limited access to one file, so the CDN can check permission without calling back to the service.
- DRM (digital rights management): encrypting content so that only an authorised app on an authorised device can decode it. Examples include Google Widevine, Apple FairPlay and Microsoft PlayReady.
- Content key / licence: the key that decrypts a file, and the signed permission that lets a device use it. Offline downloads need keys stored on the device with an expiry.
- Prefetch: downloading the start of the next track before the current one ends, so the transition is instant.
- Stream (royalty sense): a play that lasted at least 30 seconds. Streams, not raw plays, drive royalties and public play counts.
- Streamshare (pro-rata model): the way most services split royalties. A rights holder's share of the royalty pool equals their share of all eligible streams in the month.
- Collaborative filtering: recommending items that users with similar listening histories also played. Content-based methods use the audio itself or text about it.
- Embedding: a vector of numbers (say 128 values) that represents a user, track or artist so that similar items have nearby vectors.
- Event pipeline: the system that carries billions of small usage events (play started, skipped, completed, searched) from clients to storage and processing.
Clarifying Questions#
| Question | Why it matters | Assumed answer |
|---|---|---|
| How many users, and how active are they? | Drives bandwidth, event volume and capacity in every tier. | About 700 million monthly active users, 300 million daily, and about 2 hours of listening per daily user. Peak concurrency is about 50 million streams. |
| How big is the catalogue? | Drives storage, the long tail and cache sizing. | 100 million music tracks, growing by about 100,000 or more per day, plus podcasts. We focus on music and note where podcasts differ. |
| Which audio qualities and devices? | Sets the encoding ladder and DRM paths. | Phones, desktop, web, cars, smart speakers and TVs. Lossy 24–320 kbps plus lossless FLAC for Premium. |
| What does "fast" mean for playback? | The main latency goal for the whole client and edge design. | Tap-to-sound p50 under 250 ms, p99 under 1 s on a decent network. Next-track transition with zero gap. |
| Is there a free tier with ads? | Adds entitlements, shuffle limits and ad insertion. | Yes: free with ads and some limits, and Premium with no ads, any order, offline and higher quality. |
| Do we need offline listening? | Brings in download management, DRM licences and offline play reporting. | Yes, for Premium: up to 10,000 tracks per device on up to 5 devices, and the app must come online at least once every 30 days. |
| What about playlists? | Data model, concurrency and very large follower counts. | User playlists (private, public, collaborative) and editorial or algorithmic playlists. Billions in total. |
| How fresh must recommendations be? | Batch versus real-time pipelines. | Weekly generated playlists (for example, a Monday discovery mix) plus a home screen that reacts within minutes to recent listening. |
| Do we pay royalties from our own counts? | Requires an auditable, deduplicated stream ledger and monthly reports. | Yes. Streams of 30 seconds or more, counted per country and plan, reported monthly to labels, distributors and collecting societies. |
| Do we show public play counts? | Requires approximate, lagging counters per track. | Yes, per-track counts on album pages, updated roughly daily, not in real time. |
| Is search in scope? | Indexing, typo tolerance and ranking. | Yes: search across tracks, artists, albums, playlists and podcasts with prefix matching. |
| Do we cover multi-device control (play on a speaker from the phone)? | Adds a device-session service and real-time messaging. | Yes, briefly: one active playback device per account, controllable from others. |
Requirements#
Functional requirements#
- Ingest and encode music. Accept releases from distributors (audio masters, metadata and rights), validate them, and encode each track into the full quality ladder.
- Play any track instantly. Given a track ID, check rights and stream audio quickly, with seeking, gapless transitions and adaptive quality.
- Browse the catalogue. Show artists, albums, tracks and credits, respecting each listener's country and plan.
- Manage playlists. Create, edit, reorder, share and follow playlists, including collaborative ones and huge editorial ones.
- Search. Find tracks, artists, albums, playlists and podcasts by name as the user types, tolerating typos.
- Download for offline. Let Premium users download playlists and albums, play them without a network, and report the plays later.
- Recommend. Generate personalised playlists and home-screen shelves for every user.
- Count plays and pay royalties. Record every play, count 30-second streams, show public play counts and produce monthly royalty statements.
Out of scope, or mentioned only briefly: lyrics, social features (friend activity, shared listening sessions), podcast hosting and video podcasts, live audio, concerts and merchandise, the ad-serving system itself.
Non-functional requirements#
- Low playback latency: p50 tap-to-sound under 250 ms and p99 under 1 s. Rebuffering in under 0.5% of listening time.
- High availability: playback is the core product. Target 99.99% for "can I play what I asked for". Downloaded music must keep playing even when the whole backend is down.
- Scalability: about 50 million concurrent streams at peak and tens of terabits per second of egress, plus about a million or more client events per second.
- Cost efficiency: bandwidth and storage dominate cost. Cache hit ratios at the edge and on devices are first-class goals.
- Content protection: files are encrypted, URLs expire, offline keys are bound to the device and expire.
- Correctness of money paths: stream counts used for royalties must be exactly-once after deduplication, reproducible and auditable. Public play counts may lag and be approximate.
- Freshness: a new release must be playable everywhere at its release time, often midnight local time on Friday. Rights changes (takedowns) must apply within minutes.
- Durability: masters and encoded files must never be lost (eleven nines of durability, as object stores give).
- Global reach: listeners in almost every country, with very different networks and devices.
Capacity Estimation#
Sizing tells us where the money and the risk are. The method is the one from Back-of-the-Envelope Estimation: state assumptions, multiply, round, and then ask what each number means for the design.
Assumptions.
- 700 million monthly active users (MAU) and 300 million daily active users (DAU).
- A daily user listens for about 100 minutes a day on average. Music listening is long-session and repeat-heavy.
- An average play lasts about 2.5 minutes, because many plays are skipped and full tracks average about 3.5 minutes.
- The catalogue holds 100 million tracks, averaging 210 seconds each. Industry reports put new uploads to streaming services at roughly 100,000 or more tracks a day; we assume 100,000.
- The average delivered bitrate is about 160 kbps across all users (many mobile users on 96 kbps, many Premium users on 320 kbps, a small share on lossless).
Listening and concurrency.
- Daily listening = 300 M × 100 min = 30 billion minutes a day, which is 500 million hours.
- Average concurrent streams = 30 B min ÷ 1,440 min/day ≈ 21 million.
- Peak-to-average is about 2.4 for a global service with strong regional evening peaks, so peak ≈ 50 million concurrent streams.
Plays.
- Play starts = 30 B min ÷ 2.5 min ≈ 12 billion plays a day.
- That is ≈ 140,000 play starts per second on average and ≈ 330,000 per second at peak.
- Every play start needs a rights check, a file lookup and a key. The playback control path must therefore handle hundreds of thousands of requests per second, which is high but ordinary for a sharded, cached service.
Bandwidth (the dominant cost).
- Bytes per minute at 160 kbps = 160,000 × 60 ÷ 8 = 1.2 MB, so a 3.5-minute track at 160 kbps is about 4.2 MB.
- Without any device cache, daily delivery = 30 B min × 1.2 MB = 36 PB a day.
- Music is repeat-heavy: people replay favourites and downloaded playlists. Assume 35% of listening is served from the device (offline downloads plus the streaming cache). Network delivery is then about 23 PB a day.
- Peak egress ≈ 50 M × 160 kbps × 0.65 ≈ 5.2 Tbps. That is why audio comes from CDNs with edge servers inside ISP networks, and why every percentage point of device or edge hit ratio is worth real money.
Storage for audio.
Each track is stored as a ladder of renditions. Using Spotify's published quality levels as a guide:
| Rendition | Bitrate | Size for 210 s |
|---|---|---|
| Low (HE-AAC or Vorbis) | 24 kbps | 0.6 MB |
| Normal (Vorbis) | 96 kbps | 2.5 MB |
| High (Vorbis) | 160 kbps | 4.2 MB |
| Very high (Vorbis) | 320 kbps | 8.4 MB |
| Web (AAC) | 128 and 256 kbps | 3.4 + 6.7 MB |
| Lossless (FLAC, 16-bit) | about 900–1,100 kbps | about 26 MB |
| Master (WAV or FLAC, kept in cold storage) | 1,411 kbps (16-bit) to 2,117 kbps (24-bit) | 37–56 MB |
- The lossy renditions total about 26 MB per track. Lossless adds about 26 MB and the master about 45 MB on average, so each track costs about 95–100 MB in total.
- 100 M tracks × 100 MB ≈ 10 PB of logical audio. With erasure coding at about 1.5× overhead and two regions, that is about 30 PB of physical storage.
- Ingest adds 100,000 tracks × 100 MB ≈ 10 TB a day, which is easy for an object store.
The audio store is big but not extreme. A large video service stores far more. What stands out is the number of objects: 100 M tracks × about 8 renditions ≈ 800 million files, each read in small ranges.
Encoding compute.
- A modern encoder runs at roughly 100× real time per core per rendition. Eight outputs plus loudness and fingerprint analysis is about 10 passes of 210 s ÷ 100 ≈ 20 core-seconds per track.
- 100,000 new tracks a day × 20 core-seconds = 2 M core-seconds ≈ 25 cores busy all day. Daily encoding is cheap.
- Re-encoding the whole catalogue (for a new codec or to fix an encoder bug) is 100 M × 20 = 2 B core-seconds. On 20,000 cores that takes about 28 hours, so the pipeline must support big backfill campaigns, not just the daily trickle.
Metadata.
- Tracks: 100 M × about 2 KB (titles in several languages, credits, IDs, durations, file references) ≈ 200 GB. Albums (about 10–20 M) and artists (about 10 M) add tens of GB.
- Market availability: 184 markets per track fit in a 23-byte bitmap per rights window, which is a few GB in total.
- The whole catalogue fits in a few hundred GB. It can be replicated everywhere and cached heavily.
- Read load is large. Every screen shows dozens of entities. 300 M DAU × 300 entity reads a day ≈ 90 B reads a day ≈ 1 M per second on average and 2–3 M per second at peak. Almost all must hit a cache.
Playlists.
- Public figures mention around 4 billion playlists. Assume 50 tracks on average and about 40 bytes per entry (track ID, added-by user, timestamp), so about 2 KB per playlist. Total ≈ 8 TB plus playlist headers.
- Edits: about 200 M a day ≈ 2,300 writes per second on average and about 6,000 at peak.
- Reads: 300 M DAU × 30 playlist loads a day ≈ 9 B a day ≈ 100,000 per second on average and about 250,000 at peak, heavily skewed towards a few thousand huge editorial playlists.
Search.
- 300 M DAU × 5 searches × about 6 typeahead requests per search ≈ 9 B requests a day ≈ 100,000 QPS on average and about 250,000 at peak.
- The index holds about 100 M tracks, 10–20 M albums, 10 M artists, several hundred million public playlists and millions of podcast shows and episodes. That is a few TB of index, which needs a sharded search cluster.
Usage events.
- Each play produces several events (start, progress or heartbeat, pause, seek, skip, end). UI actions add more. Assume about 10 events per play: 12 B × 10 = 120 B events a day ≈ 1.4 M events per second on average and 3–4 M at peak. For comparison, Spotify wrote in 2016 that its event delivery system pushed more than 700,000 events per second, and it load-tested its replacement at 2 M per second.
- At about 200 bytes each, that is about 24 TB a day of raw events, or roughly 5 TB compressed in a columnar format.
Streams and royalties.
- Plays of at least 30 seconds are perhaps 75% of starts, so about 9 B streams a day, or about 270 B a month.
- Aggregated per (track, country, plan, day), that is roughly 1 B ledger rows a day, because only tens of millions of tracks are played on a given day. That suits a warehouse, not an OLTP database.
Recommendations.
- A weekly 30-track discovery playlist for 700 M users is 21 B track slots, about 170 GB of output, which is small.
- The cost is in computing it: candidate retrieval and ranking for 700 M users in one weekly batch. At 2 ms of model time per user, that is 1.4 M CPU-seconds, so the job is spread across a cluster over a day or two before release.
What the numbers say.
- Bandwidth is the cost centre. Design the client cache, prefetching and CDN first.
- Play starts at 330,000 per second need a fast, cacheable control path (rights, file IDs, keys), separate from the bulk audio path.
- Metadata is small and very hot. Replicate it and cache it in layers.
- Events are huge but simple. Use a partitioned log and batch plus stream processing, not a database.
- Royalties are a correctness problem, not a scale problem. The volume is manageable in a warehouse; the hard part is deduplication, fraud filtering and auditability.
Core Entities#
- Artist:
artist_id, name and localised names, images, genres, verified flag, follower count. - Release (album, single, EP, compilation):
release_id, UPC, title, type, label, release date per territory, artwork, track list with disc and track numbers. - Track (recording):
track_id, ISRC, title, duration, explicit flag, artists and roles, the release(s) it appears on, popularity, audio features (tempo, key, loudness). - Work (composition):
work_id, ISWC, songwriters, publishers and splits. Used for publishing royalties. - AudioFile (rendition):
file_id(derived from a content hash),track_id, codec, bitrate, size, duration, encoder delay and padding, loudness (LUFS and true peak), encryption key ID. - Availability (rights window):
track_idorrelease_id, licensor, markets, start and end dates, plan restrictions (free or Premium), and flags for downloads or previews. - User:
user_id, country, plan, settings (quality, normalisation, explicit filter), devices. - Device:
device_id, type, DRM capability and security level, offline licence state. - Playlist:
playlist_id, owner, name, description, visibility, collaborative flag, current revision (snapshot_id), follower count. - PlaylistEntry:
playlist_id, position key,track_id,added_by,added_at. - PlayEvent:
event_id,user_id,device_id,track_id,file_id, context (playlist, album, radio, search), start time,ms_played, end reason (finished, skipped, paused), offline flag. - Stream: a deduplicated, validated play of 30 seconds or more, with country and plan, as it enters the royalty ledger.
- OfflineLicence:
device_id, list offile_idand key IDs, issued-at, expires-at (30 days), signature. - RecommendationSet:
user_id, surface (weekly discovery, daily mixes, home shelves), generated-at, ordered track IDs and reasons. - RoyaltyStatement: licensor, month, country, plan, streams, streamshare, amount, plus the line items behind it.
API Design#
The client talks to two very different planes. The control plane (HTTPS, JSON or protobuf) handles metadata, rights, playlists, search and events. The data plane is plain HTTPS range requests against CDN hostnames for audio bytes. Spotify's public Web API has a similar shape for its metadata and playlist endpoints; the internal playback protocol is not public, so the playback endpoints below are our own design.
Metadata.
GET /v1/tracks/{track_id}?market=IN
GET /v1/albums/{release_id}?market=IN
GET /v1/artists/{artist_id}/top-tracks?market=IN
Responses include only what this market may see. A track the listener cannot play is returned with is_playable: false and a reason, or relinked to an equivalent playable track (see Deep Dive 5).
Playback (control plane).
POST /v1/playback/resolve
{ "track_id": "t_123", "context": "playlist:p_9", "device_id": "d_7",
"quality": "auto", "max_quality": "very_high" }
200 OK
{ "track_id": "t_123", "duration_ms": 213000,
"files": [ { "file_id": "f_ab12", "codec": "vorbis", "kbps": 160 },
{ "file_id": "f_cd34", "codec": "vorbis", "kbps": 320 } ],
"cdn_urls": { "f_ab12": "https://audio-cdn-3.example.net/f_ab12?tok=..." },
"key_token": "...", "gain_db": -3.2, "gapless": { "delay": 1024, "padding": 576 },
"expires_at": "2026-12-03T19:30:00Z" }
The client then fetches audio with GET {cdn_url} and a Range: bytes=0-131071 header, and asks for the content key with the key token:
POST /v1/keys { "file_id": "f_ab12", "key_token": "...", "device_id": "d_7" }
Playlists. Every write carries the revision the client last saw, so concurrent edits are detected:
POST /v1/users/{user_id}/playlists { "name": "Road trip", "public": false }
GET /v1/playlists/{playlist_id}?fields=...&offset=0&limit=100
POST /v1/playlists/{playlist_id}/tracks { "uris": ["t_1","t_2"], "position": 5, "snapshot_id": "r41" }
PUT /v1/playlists/{playlist_id}/tracks { "range_start": 3, "insert_before": 10, "range_length": 2, "snapshot_id": "r42" }
DELETE /v1/playlists/{playlist_id}/tracks { "tracks": [ { "uri": "t_2", "positions": [6] } ], "snapshot_id": "r43" }
PUT /v1/playlists/{playlist_id}/followers
Each write returns the new snapshot_id.
Search.
GET /v1/search?q=bohem&type=track,artist,album,playlist&market=IN&limit=10&offset=0
Offline downloads.
POST /v1/devices/{device_id}/downloads { "container": "playlist:p_9", "quality": "high" }
-> { "files": [...], "licence": { "licence_id": "...", "expires_at": "...", "keys": "<wrapped for device>" } }
POST /v1/devices/{device_id}/licences/renew { "licence_ids": [...], "offline_plays": [...] }
Events. Events are sent in batches, compressed, with client-generated IDs for deduplication:
POST /v1/events
{ "device_id": "d_7", "batch_seq": 9812,
"events": [ { "event_id": "e_7f3...", "type": "play_end", "track_id": "t_123",
"ms_played": 187000, "reason": "trackdone", "ts_client": 1764781200123,
"offline": false, "context": "playlist:p_9" } ] }
Personalisation.
GET /v1/home?market=IN&time_zone=Asia/Kolkata
GET /v1/me/made-for-you -> weekly discovery, daily mixes, new-release radar
Ingestion (partners). Labels and distributors deliver DDEX ERN messages plus audio files to a partner bucket or SFTP drop. A partner API reports status:
GET /partner/v1/deliveries/{delivery_id} -> { "status": "encoded", "tracks": [...], "issues": [] }
High-Level Design#
We build the design one requirement at a time, then combine the pieces. The key architectural split is between the control plane (small requests: rights, metadata, playlists, search, events) and the data plane (bulk audio bytes from CDNs and device caches). They scale differently and fail differently.
1) Labels deliver music, and it is encoded and stored#
A distributor drops a delivery: a DDEX message describing the release, its tracks, contributors, territories and dates, plus the master audio files and artwork. The ingestion service validates it (are all files present, do durations match, are the ISRCs well formed, is the artwork big enough), then writes a release draft to the catalogue store. Each track goes on a queue to the encoding pipeline.
Encoding workers fetch the master, decode it to PCM (raw samples), measure loudness and true peak, compute an audio fingerprint (to catch duplicates and stolen uploads), and produce every rendition in the ladder. Each output file is named by a hash of its content, encrypted with a fresh content key, and written to the audio object store. The key goes to the key service. When all renditions of all tracks exist, the release becomes ready, and at its release time it becomes live in each market.
Masters are kept in a cold storage class. If a better codec appears, or an encoder bug is found, we can re-encode from the master rather than from a lossy copy.
2) Listeners play a track instantly#
Playing a track has two steps that run almost in parallel:
- Resolve. The client calls the playback service with the track ID. It checks the user's plan and country against the track's availability, picks the files for the requested quality, and returns file IDs, CDN URLs with short-lived signed tokens, a key token, the loudness gain and gapless information. This response is small and cacheable per (track, market, plan) for a few minutes.
- Fetch. The client requests the first chunk of the file from the nearest CDN edge using an HTTP range request, and at the same time fetches the content key from the key service. As soon as the first chunk (about 128 KB, which is several seconds of audio at 160 kbps) and the key arrive, decoding starts.
The CDN edge either has the file (most plays, because popular tracks are very popular) or fetches it from a regional shield cache, which in turn fetches from the object store.
The client is smart. It keeps an encrypted local cache of recently played tracks, so a repeat play makes no network request at all. It also prefetches the start of the next track in the queue about 10–30 seconds before the current one ends.
3) Listeners browse the catalogue#
Artist pages, album pages and track lists come from the catalogue (metadata) service. Its source of truth is a strongly consistent database of entities and rights, written only by ingestion and the rights team. Reads are served from replicated read stores and several layers of cache: an in-process cache in the API servers, a distributed cache such as Redis or Memcached, and a CDN for public, non-personalised responses such as album pages per market.
The response is filtered per market. The same album may have 12 tracks in one country and 11 in another, or a different cover. Filtering happens in the service, never in the client, so unlicensed data is never shown.
4) Listeners manage playlists#
The playlist service stores each playlist as a header (name, owner, flags, current revision) plus an ordered list of entries. It is sharded by playlist_id. Every change creates a new revision; the client sends the revision it last saw, so two people editing a collaborative playlist cannot silently overwrite each other.
A user's library (the list of playlists they own or follow, saved albums and liked songs) is a separate per-user store sharded by user_id. Following a playlist adds a row to the user's library and increments an approximate follower counter. It never copies the playlist.
Huge editorial playlists are read millions of times a day. They are served from cache and the CDN, keyed by playlist ID and revision, so a new revision automatically gets a new cache key.
5) Listeners search#
The search service queries a sharded search index (Elasticsearch, OpenSearch, Vespa or a custom Lucene-based system). The index holds tracks, artists, albums, public playlists and podcasts, with fields for names, aliases, transliterations and popularity. It is fed by a change stream from the catalogue and playlist stores, so a new release becomes searchable within minutes and a takedown disappears quickly.
Because so many queries are short and popular (taylor, bad bunny, lofi), a query result cache keyed by (normalised query, market, type) absorbs most of the load. A short TTL keeps results fresh. Personal ranking (boosting artists the user listens to) is applied after the shared, cached result is fetched.
6) Premium listeners download for offline#
The user marks a playlist or album for download. The download service checks the plan and device limits (up to 5 devices and 10,000 tracks per device), returns the list of files for the chosen download quality, and issues an offline licence. The licence holds the content keys for those files, encrypted for this device's DRM keys and set to expire after 30 days. The client downloads the encrypted files from the CDN in the background, on Wi-Fi by default, and stores them in its encrypted cache.
Offline plays are logged locally. When the device reconnects, it uploads the stored events and renews the licence. If it does not reconnect within 30 days, the licence expires and the files stop playing.
7) Everyone gets recommendations#
Recommendations come from two loops:
- A batch loop trains models on months of listening history and produces outputs such as track and user embeddings, similar-artist graphs, and the weekly discovery playlists for every user. These are written to a recommendation store keyed by user.
- A real-time loop consumes the live event stream to update recent-listening features (what you played in the last hour, what you skipped). The home service blends precomputed candidates with these fresh features to rank shelves when the app opens.
8) Plays are counted and royalties are paid#
Every client sends batched events to an event gateway, which stamps a server timestamp and writes them to a partitioned log (Kafka or a managed equivalent such as Google Cloud Pub/Sub). From there:
- A stream processor deduplicates events by
event_id, applies the 30-second rule, filters obvious fraud, and updates approximate play counters for public display and for trending charts. - Every event also lands in the data lake, partitioned by hour. A daily and monthly batch pipeline recomputes streams exactly from the raw data, joins them with rights and plan information, runs heavier fraud models, and writes the royalty ledger.
- At month end the royalty engine computes each rights holder's streamshare and produces statements and payment files.
The full high-level design#
The arrows show the main direction of dependency: clients call control-plane services, services read and write stores, and stores feed the pipelines. Two flows close the loop and are left off the diagram to keep it readable. Audio bytes go from the object store to the CDN and then to clients. Pipeline outputs (encoded files, recommendations, counters) flow back into the stores that serving reads.
Components:
- Client apps (mobile, desktop, web, TV, car, speaker): the player, decoder, prefetcher, encrypted cache, offline store, event buffer and DRM module. They do a large share of the work, including hiding network problems.
- API gateway: authentication (OAuth tokens), routing, rate limiting and request shaping for all control-plane calls. See API Gateway and Backend-for-Frontend.
- CDN edges and shields: serve encrypted audio files by
file_id, validate signed tokens, and cache by popularity. Commercial CDNs are often used, sometimes mixed with the service's own edge servers inside ISPs. - Event gateway: accepts batched events from clients, stamps a server timestamp, and writes them to the event log. It must stay up even when everything downstream is slow.
- Playback service: resolves a track into playable files for this user, market, plan and device, and issues signed URLs and key tokens.
- Key and licence service: stores content keys, hands them out for streaming, and wraps them into time-limited offline licences bound to a device.
- Metadata service: serves artists, releases and tracks filtered by market, including relinking to an equivalent playable track.
- Playlist service: playlists, revisions, collaborative editing, and following.
- Search service: typeahead and full search over all entity types, with a query cache.
- Home and recommendation services: assemble personalised shelves and serve precomputed generated playlists.
- Download service: manages offline downloads, device limits and licence renewals.
- Entitlements and user service: plans, family and student accounts, country, device registry and settings.
- Catalogue and rights database: the source of truth for entities, availability windows and licensor data.
- Distributed caches: Redis or Memcached clusters for metadata, playback resolves, playlists and search results.
- Playlist and library stores: a wide-column or key-value store (Cassandra, Bigtable or similar) sharded by playlist and by user.
- Search index: a sharded inverted index with replicas.
- Recommendation and feature stores: per-user precomputed recommendations and real-time profile features. Spotify described using Cassandra for its user profile store.
- Audio object store: immutable encrypted renditions plus cold-stored masters, replicated across regions.
- Ingestion and encoding: partner delivery, validation, encoding and publishing.
- Event log: a partitioned, replicated log for all usage events.
- Data lake and batch jobs: hourly-partitioned columnar files (for example, Avro or Parquet) for analytics, model training, charts and royalties.
- Royalty ledger and engine: the auditable record of streams and the monthly calculation of payouts.
Key Flows#
Flow 1: tap play on a track that is not on the device#
This is the flow we optimise hardest. The goal is sound within about 250 ms. The trick is to overlap everything that can overlap: the resolve call, the key fetch and the first audio chunk.
Notes:
- On a warm connection (TLS already set up), the resolve takes one round trip of 20–60 ms plus about 5 ms of server time. The edge, when the file is cached, returns the first bytes in another 10–40 ms. The key fetch runs in parallel. Typical tap-to-sound is 100–250 ms.
- A cold edge miss adds a shield or origin round trip, typically 30–150 ms more. This is why popular and newly released tracks are pre-positioned at the edge.
- The client can go further. When the user opens an album page or a search result list, it can call resolve in advance for the visible tracks, so a tap only needs the audio bytes. When the user's finger lands on a track, the app can even start fetching the first chunk before the tap is complete.
Flow 2: the next track starts with no gap#
The prefetch window is a trade-off. Too early wastes bandwidth when users skip. Too late risks a gap on a slow network. A common rule is to start prefetching when the remaining time of the current track is about 2–3 times the expected fetch time on this network, with a floor of 10 seconds.
Flow 3: two people edit a collaborative playlist at the same time#
The service does not reject Bob's edit just because it is stale. It rebases the operation (shifts his positions to account for Alice's insert), much like operational transformation in a collaborative editor. If the operation can no longer be applied safely (the tracks he moved were deleted), it rejects it and the app reloads. See Deep Dive 6.
Flow 4: a new album goes live at midnight on Friday#
Big releases are known days in advance, so the scheduler pre-warms: it pushes the encrypted audio to edge caches and pre-builds the album and artist pages. The files are useless without keys, and the metadata is not served until the release time, so pre-warming leaks nothing. At release time, flipping availability is a tiny metadata change, and cache invalidation events make the album visible within seconds.
Flow 5: playing offline and reconnecting#
Flow 6: a play becomes a counted stream#
The stream processor gives fast, approximate numbers for the app and charts. The batch job is the source of truth for money, because it can recompute everything from raw data and apply late-arriving offline plays and fraud decisions.
Data Model#
The catalogue is relational in shape (artists, releases, tracks, rights) and changes slowly, so a strongly consistent relational database (PostgreSQL, Spanner, or MySQL with Vitess) suits the source of truth. Serving copies are denormalised documents in caches. Playlists, libraries and events have very different access patterns and live in different stores.
Each track has its encoded files and its rights windows:
User-side data: accounts, devices, saved items and offline licences:
Playlists are stored as a header, entries and a revision log:
The rights table is the heart of "can this user play this track here and now":
CREATE TABLE availability (
track_id TEXT NOT NULL,
licensor_id TEXT NOT NULL,
markets BIT(256) NOT NULL, -- one bit per market code
starts_at TIMESTAMPTZ NOT NULL, -- release time, often per time zone
ends_at TIMESTAMPTZ, -- licence end or takedown
plans TEXT[] NOT NULL, -- {'free','premium'}
allow_offline BOOLEAN NOT NULL DEFAULT true,
PRIMARY KEY (track_id, licensor_id, starts_at)
);
-- Playable check done when the serving document is built, not per request:
SELECT bool_or(get_bit(markets, :market_idx) = 1
AND now() >= starts_at
AND (ends_at IS NULL OR now() < ends_at)
AND :plan = ANY(plans))
FROM availability WHERE track_id = :track_id;Playlists live in a wide-column store, so one partition holds one playlist and its rows are ordered by a sortable position key:
-- Cassandra-style CQL
CREATE TABLE playlist_entries (
playlist_id text,
position_key text, -- fractional index, e.g. 'a0', 'a0V', 'a1'
track_id text,
added_by text,
added_at timestamp,
PRIMARY KEY ((playlist_id), position_key)
) WITH CLUSTERING ORDER BY (position_key ASC);
CREATE TABLE playlist_header (
playlist_id text PRIMARY KEY,
owner_id text, name text, collaborative boolean,
revision bigint, snapshot_id text, entry_count int
);
-- writes use a lightweight transaction on the header:
-- UPDATE playlist_header SET revision = 43 ... WHERE playlist_id = ? IF revision = 42;| Data | Store | Why |
|---|---|---|
| Catalogue entities and rights | Relational (PostgreSQL, Spanner, Vitess) | Strong consistency, joins for ingestion and rights, modest size |
| Serving metadata documents | Redis or Memcached, plus CDN for public pages | About 2–3 M reads per second; denormalised per market |
| Audio renditions and masters | Object store (GCS, S3) with erasure coding | Immutable, huge, cheap per GB, multi-region |
| Content keys | Dedicated key store with an HSM or KMS-wrapped master key | Small, highly sensitive, audited access |
| Playlists and libraries | Cassandra, Bigtable or DynamoDB | Billions of partitions, simple key access, high write rate |
| Search index | Elasticsearch, OpenSearch, Vespa or Solr | Inverted index, typo tolerance, ranking |
| Events | Kafka or Pub/Sub, then data lake (Avro or Parquet on GCS or HDFS) | Append-only, very high volume, replayable |
| User profiles and features | Cassandra or Bigtable plus a feature store | Low-latency reads, bulk loads from batch jobs |
| Recommendations output | Key-value store keyed by user and surface | Written in bulk weekly, read once per session |
| Royalty ledger | Warehouse (BigQuery, Snowflake) plus immutable monthly snapshots | Big aggregates, audit trail, reproducibility |
For the general method of matching access patterns to stores, see Choosing a Database: A Decision Guide.
Deep Dives#
1. Audio encoding: from a master file to a quality ladder#
Why encode at all? A CD-quality stereo master is 44,100 samples per second × 16 bits × 2 channels = 1,411 kbps, about 37 MB for a 3.5-minute song. Streaming that to 50 million concurrent listeners would be roughly 70 Tbps. A good lossy codec at 160 kbps sounds close to transparent to most listeners on most equipment, at about one-ninth the size. Encoding is therefore the single biggest bandwidth optimisation in the system.
How lossy audio codecs work (the intuition). Ogg Vorbis, AAC, MP3 and Opus all rely on psychoacoustics, the study of what the ear can and cannot perceive:
- Absolute threshold of hearing. Very quiet sounds, especially at very low and very high frequencies, are inaudible. There is no need to spend bits on them.
- Simultaneous masking. A loud tone hides quieter tones at nearby frequencies. The louder the masker, the wider the band it hides.
- Temporal masking. A loud sound also hides quieter sounds just after it (for up to about 100–200 ms) and, briefly, just before it (a few ms).
The encoder slices the audio into short overlapping frames and transforms each into frequencies using the MDCT (modified discrete cosine transform). AAC uses long blocks of 1,024 frequency coefficients and switches to short blocks of 128 at sharp attacks such as drum hits. Vorbis uses two block sizes, typically 256 and 2,048 samples. Short blocks stop "pre-echo", where quantisation noise spreads before a sharp sound and becomes audible.
For each frame, a psychoacoustic model estimates the masking threshold in each frequency band. The encoder then quantises each band just coarsely enough that the resulting noise stays under that threshold. Bands that are fully masked get almost no bits. Finally, the quantised values are entropy coded (Huffman coding in AAC and MP3, vector quantisation codebooks in Vorbis), so common values take fewer bits.
Bitrate modes. Most music services use variable bitrate (VBR): a quiet acoustic passage needs fewer bits than a dense rock chorus, so the encoder aims at a constant quality instead of a constant bitrate. Vorbis is usually configured by a quality setting; settings around 5 and 9 give roughly 160 and 320 kbps on typical music. The ladder bitrates are therefore averages, and file sizes vary by genre.
Very low bitrates. At 24 kbps, plain transform coding sounds muddy. HE-AAC v2 adds two tricks:
- Spectral band replication (SBR): encode only the lower half of the spectrum, plus a few bits describing the envelope of the upper half. The decoder recreates the highs by transposing the lows and shaping them.
- Parametric stereo (PS): send one mono channel plus a few parameters describing the stereo image.
This is why a "low" data-saver setting can still sound acceptable on a phone speaker.
Why not just use Opus? Opus (IETF RFC 6716, 2012) is excellent at low and medium bitrates and is royalty-free. The hesitation for a music service is practical: decades of old devices (cars, speakers, TVs) only decode AAC, MP3 or Vorbis, and adding a codec means re-encoding the whole catalogue (about 2 billion core-seconds by our estimate) and storing another ladder. A sensible strategy is to add new codecs only for new device classes or for the low-bitrate tier where the gain is biggest.
Lossless. FLAC predicts each sample from the previous few samples using linear prediction, then stores only the small prediction error (the residual) with Rice coding. Typical music compresses to about 50–70% of the PCM size, so CD-quality FLAC averages roughly 700–1,000 kbps, and 24-bit masters more. Spotify's help pages describe lossless playback up to 24-bit/44.1 kHz FLAC for Premium.
Always encode from the master. Transcoding one lossy format into another ("generation loss") stacks two sets of artefacts. Every rendition is produced directly from the master, and the master is kept forever so that any rendition can be rebuilt.
The pipeline, step by step.
- Validation and QC. Partners make mistakes: truncated files, the wrong track uploaded, a 30-second silence at the end, mono files labelled stereo, heavy clipping. Automatic checks catch most of them. Problems go back to the partner through the delivery status API.
- Loudness measurement. Loudness is measured with ITU-R BS.1770. The signal passes through a K-weighting filter that roughly matches how the ear weights frequencies. Its power is averaged over 400 ms blocks, and blocks are gated: quieter than −70 LUFS absolute, or more than 10 LU below the ungated average, are ignored, so silence and fade-outs do not drag the number down. True peak is estimated by oversampling 4× to catch peaks between samples.
- Normalisation is applied at playback, not baked into files. Spotify's artist documentation says it measures loudness on upload and adjusts playback to −14 LUFS by default (with "loud" −11 and "quiet" −19 options). It normalises a whole album at once so that quiet tracks stay quiet relative to loud ones. It only raises quiet tracks as far as their headroom allows, keeping about 1 dB for lossy formats. For example, a track at −20 LUFS with a true peak of −5 dBFS is only lifted to −16 LUFS, because lifting it by the full 6 dB would push its peak above −1 dBFS. Storing a gain value in metadata keeps the files untouched and lets users switch the feature off.
- Gapless information. Transform codecs add priming samples at the start (encoder delay, often around 1,000–2,000 samples for AAC) and padding at the end to fill the last frame. If the player plays them, a live album gets a tiny click or gap between tracks. The pipeline records the exact delay and padding for each file, and the player trims them. Vorbis carries exact sample positions in its container, which helps.
- Fingerprinting. An acoustic fingerprint summarises the audio robustly, so the same recording matches even after re-encoding or slight edits. A classic approach is the landmark method from "An Industrial-Strength Audio Search Algorithm" (Avery Wang, ISMIR 2003). It hashes pairs of spectrogram peaks with their time difference. Matches reveal duplicate deliveries, stolen uploads of someone else's recording, and the same recording appearing on several releases.
- Audio analysis. Tempo, key, beat positions and a learned audio embedding are computed once and stored. They power crossfades, DJ-style features, and cold-start recommendations for tracks nobody has played yet (Deep Dive 9).
Orchestration.
- One job per track, with steps as a small DAG. Each output is keyed by its content hash, so retries are idempotent: re-running a step that already succeeded writes the same object.
- Priority queues. Scheduled big releases and takedown re-encodes go first, the daily trickle next, and catalogue-wide backfills last. Backfills run on cheap preemptible machines and can be paused when the cluster is busy.
- Encoder changes are product changes. A new encoder version is tested with objective quality metrics (ViSQOL, or PEAQ from ITU-R BS.1387) on a large sample, plus blind listening tests by trained listeners. It is then rolled out gradually, like any risky deployment, with the old files kept until the new ones are proven.
Trade-offs.
| Choice | Benefit | Cost |
|---|---|---|
| More rungs in the ladder | Better fit to each network and plan | More storage, more encode time, lower CDN hit ratio per file |
| VBR instead of CBR | Better quality per bit | Less predictable bandwidth; seeking needs an index |
| Normalise at playback | Masters untouched; users can opt out | Every client must apply gain correctly |
| Keep masters | Re-encode anytime, add lossless later | About 4–5 PB of extra cold storage |
2. Storing hundreds of millions of audio files#
Content-addressed file IDs. Each rendition's ID is derived from a cryptographic hash of its bytes (for example, the first 160 bits of SHA-256). This gives several properties for free:
- Immutability. A file ID always means exactly the same bytes, so CDNs and clients can cache it forever (
Cache-Control: max-age=31536000, immutable). There is no cache invalidation for audio, ever. - Safe re-encodes. A new encoder produces new bytes and therefore new IDs. The catalogue switches the track's file pointers atomically. Old clients holding old IDs keep working until the old files are deleted.
- Deduplication. If two releases carry the identical recording, the master and renditions are stored once.
- Integrity. Any layer can verify that the bytes match the ID.
Garbage collection. Old renditions cannot be deleted the moment a re-encode finishes. Offline licences and client caches still reference them, for up to 30 days plus clock drift. A mark-and-sweep job deletes a file only when no catalogue pointer references it and the last licence that could reference it has expired, plus a safety margin. Takedowns are different: the rights are removed instantly (Deep Dive 5), so the files become unplayable at once, even though the bytes are deleted later.
Object store layout.
- Keys are spread by hash, such as
audio/ab/12/ab12f9..., so no single prefix becomes hot. Object stores partition their key space by prefix and limit request rates per partition. Amazon S3, for example, documents at least 3,500 writes and 5,500 reads per second per prefix, scaling by adding prefixes. - Objects are 0.5–60 MB, a good size for object storage. Each is read in ranges, but almost always through the CDN, so the origin sees only cache-miss traffic.
Encryption for seekable streaming. Each file gets its own random content key, for example AES-128 or AES-256. A counter mode (CTR, or the cenc and cbcs schemes of Common Encryption used with Widevine and FairPlay) lets the player decrypt any byte range independently. The counter for a block is derived from its offset, so seeking to minute 2 does not require decrypting minutes 0–2. Content keys are stored wrapped (encrypted) by a master key held in a KMS or HSM. The key service hands out a content key only to an authenticated session with a valid key token, and logs every issue.
Durability and regions.
- Object stores replicate or erasure-code data. A Reed–Solomon scheme such as 6 data + 3 parity fragments survives any 3 lost fragments at 1.5× overhead, compared with 3× for triple replication.
- The renditions are replicated to at least two regions, so a regional outage does not stop playback from origin.
- Masters are written once to an archive class with object lock (write once, read many) and periodic checksum verification. Masters are the irreplaceable asset: losing a rendition costs CPU, but losing a master may mean asking the label to deliver again.
Tiering by popularity. Plays follow a steep power law. The top 1% of tracks get the large majority of plays, and many tracks are played a few times a year. That opens a cost option:
- Hot tier (standard storage class) for renditions of tracks played often, and for the low and normal rungs of everything, because those are needed for fast starts.
- Cooler tier (infrequent-access class) for the 320 kbps and lossless renditions of long-tail tracks. Retrieval still takes milliseconds in most clouds, but costs a per-GB retrieval fee. That is fine if a file is fetched rarely, and the CDN absorbs repeats.
- Archive tier for masters.
The break-even is simple. A cooler class saves roughly half or more of the storage price per GB, but charges for each GB retrieved. If a file's expected monthly origin reads (after CDN caching) times the retrieval fee is less than the storage saving, it should be cool. A nightly job recomputes this from play counts and moves objects, using lifecycle rules where the provider supports them.
Worked example. Take a long-tail track with 20 plays a month, all at 320 kbps, and with a CDN that misses on all of them because the track is so rarely played. Origin reads are 20 × 8.4 MB = 168 MB a month. At a retrieval fee of about $0.01 per GB, that costs well under a cent. Its 320 kbps and lossless files total about 34 MB. Moving them to a class about $0.01 per GB-month cheaper saves about $0.0003 a month. Both numbers are tiny, but across 50 million such tracks the storage saving is about $17,000 a month, and the retrieval cost about $84,000. For this track, cooling does not pay. It pays only for tracks with almost no plays, roughly fewer than 3–4 high-rung plays a month at these prices. The lesson: tiering helps for the truly dead tail, and the decision must be driven by measured play counts, not intuition. Exact prices vary by provider and change over time, but the method does not.
3. Instant playback: the client, the first chunk and prefetching#
Listeners judge a music app by one number they never see: the time from tap to sound. Users notice delays above about 200–300 ms, and tracks change every few minutes, so a small delay repeats thousands of times a month. Video services accept a 1–2 second start because users start a video rarely; a music service cannot.
The latency budget for a tap on a track that is not on the device.
| Step | Cold app (first play) | Warm app (typical) |
|---|---|---|
| DNS for API and CDN hosts | 20–100 ms | 0 (cached, prefetched at app start) |
| TCP + TLS 1.3 handshake | 1–2 round trips, 40–200 ms | 0 (connection reused; HTTP/2 or HTTP/3) |
| Resolve call (rights, files, token) | 1 round trip + about 5 ms server | Often 0: resolved in advance for visible tracks |
| Key fetch | In parallel with audio | In parallel, or cached for the session |
| First audio chunk: time to first byte from the edge | 10–40 ms on hit, +30–150 ms on miss | Same |
| First chunk transfer (about 2–3 s of audio, 40–60 KB at 160 kbps) | 10–250 ms depending on bandwidth | Same |
| Decoder start and audio output latency | 10–100 ms (platform dependent) | Same |
Three lessons come out of the table:
- Connections must already be open. On a cold connection the handshakes alone can exceed the budget. The client opens and keeps warm connections to the API and to its current CDN host at app start, and uses HTTP/2 or HTTP/3 (QUIC, which can do 0-RTT resumption) so many requests share one connection.
- The first chunk must be small and fast, then the rest can be big. On a 2 Mbps mobile link, 128 KB takes about 0.5 s to transfer. Asking first for just the bytes covering about 2–3 seconds of audio (plus the Ogg or MP4 headers) lets playback start sooner. A second, much larger range request follows immediately.
- Do work before the tap. When an album page or a search result list is shown, the client can resolve the visible tracks in the background. A tap then needs only the audio bytes. When a track is very likely next (the next item in the queue, or the top search result), even the first chunk can be fetched early.
Choosing the quality. On "automatic", the client keeps a running estimate of throughput (an exponentially weighted average of recent downloads) and picks the highest rendition it can download several times faster than real time. A conservative choice for the first track of a session avoids a slow start. Some services upgrade within a track: if renditions are packaged as aligned segments (HLS or DASH), the player can switch at a segment boundary, exactly as in video. Others pick the quality per track, because a track is short and usually fully downloaded within seconds. Per-track selection keeps one simple file per rendition and makes range requests trivial. Segment packaging adds many more small objects but allows mid-track switches. Both are reasonable; the bigger win is in the buffering policy.
Download in bursts to save battery. A phone's cellular radio stays in a high-power state for several seconds after each transfer. Trickling audio at exactly the playback rate keeps the radio awake all the time. Downloading the whole track, or large slices of it, as fast as possible and then going quiet uses far less energy. A 4 MB track at 10 Mbps arrives in about 3 seconds. The client therefore fetches aggressively up to a buffer target (for example, the rest of the current track plus the start of the next), then lets the radio sleep.
Seeking. For VBR files, the player needs a map from time to byte offset. The pipeline can store a small seek table (byte offset every second or every few seconds) in the file metadata, so a seek becomes one range request. Without it, the player must bisect the file using container timestamps, which costs several round trips.
Prefetching the next track. The next track is resolved and its first part fetched when the current one has some time left (Flow 2). Shuffle mode chooses the next random track in advance, so it can be prefetched too. The cost of prefetching is waste: if the user skips or changes context, the prefetched bytes were useless. The client measures prefetch waste and tunes how early it starts, per network type.
Failure handling.
- If a CDN host is slow or failing, retry the same range on another host or another CDN provider. The resolve response lists alternatives.
- If the token expires mid-track (long pauses), refresh it with a new resolve; the bytes already cached remain valid.
- If the network drops, keep playing from the buffer and from the local cache, show a gentle "offline" state, and resume fetching when the network returns.
What to measure. Time to first audio (p50, p90, p99) per platform, network type and country. Stutter rate (rebuffer events per hour of listening). Prefetch waste. Edge hit ratio as seen by clients. Error rate per CDN host. Treat these as product metrics; a regression of 50 ms at p90 is worth an incident review.
4. Caching at every layer: device, edge and control plane#
Caching is how this system stays affordable. There are two kinds of caching here. Audio bytes are immutable and large, and are cached on devices and at the CDN. Control-plane data (metadata, rights, playlists, search results) is small, mutable and read millions of times a second, and is cached in Redis, Memcached and process memory.
Why the head of the catalogue is so cacheable: a Zipf calculation. Suppose track popularity follows a Zipf law with exponent about 1: the r-th most popular track gets plays proportional to 1/r. Then the share of all plays that go to the top k of N tracks is about H(k)/H(N), where H(n) ≈ ln n + 0.577 is the n-th harmonic number.
- N = 100 million: H(N) ≈ 18.4 + 0.58 ≈ 19.0.
- Top 1 million (1% of tracks): H ≈ 13.8 + 0.58 ≈ 14.4, so about 76% of plays.
- Top 10 million (10%): H ≈ 16.1 + 0.58 ≈ 16.7, so about 88% of plays.
Real listening is often steeper at the head, and it differs by region: what is popular in Seoul differs from Lagos or Mumbai. So each edge PoP learns its own head, and the hit ratio for audio at a busy PoP can be well above 90%. Storing the top 1 million tracks at the three rungs most used (96, 160 and 320 kbps, about 15 MB per track) takes about 15 TB, which fits on one or two cache servers with NVMe drives.
Device cache. The client keeps an encrypted on-disk cache of recently played tracks, separate from the offline store (explicitly downloaded, never evicted automatically). Music is repetitive: people replay the same favourites daily. A cache of a few GB therefore turns a large share of plays into zero-network plays. The eviction policy matters:
- LRU (least recently used) is simple and works well for "what I listened to this week".
- LFU (least frequently used) keeps long-term favourites even after a week of exploring something new, but adapts slowly.
- Hybrids such as ARC or a frequency-aware LRU tend to do best. They are implemented on the client, so they can be A/B tested like any feature.
CDN cache key and tokens. The audio URL carries a signed token so that only authorised clients can fetch files. The token must not be part of the cache key, otherwise every user's request would be a different cache entry and the hit ratio would collapse. The edge validates the token (an HMAC over the file ID, expiry and maybe a client hint, checked with a shared secret that rotates) and then looks up the cache by file_id alone. Because files are immutable, the edge can keep them as long as space allows.
Range requests and slices. Clients ask for byte ranges. The edge should not forward every small range to origin. Instead it fetches the file in large slices (for example, 1 MB) or whole, caches them, and serves any range from the cached slices. Request collapsing ensures that when 10,000 clients miss on the same new file at the same moment, the edge sends one origin request and makes the rest wait for it. This is the CDN version of preventing a cache stampede.
Multi-CDN and ISP caches. Large services usually buy from several CDNs and steer traffic using real-user measurements (time to first byte and throughput per CDN, per ISP, per region). Steering avoids an outage at one provider, and lowers cost by sending bulk traffic to the cheapest provider that meets the targets. The biggest services also place their own cache servers inside ISP networks, as Netflix does with Open Connect. The ISP saves transit costs and users get faster starts.
Release-day pre-warming. For a big scheduled release, the files are known hours ahead. Pushing them to every PoP before midnight means the first million plays all hit. Since the files are encrypted and the metadata is not yet published, nothing leaks early.
Control-plane caching, done systematically. The same rules that apply to any read-heavy service apply here. The interview-friendly way to introduce caching is to name the bottleneck, decide what to cache, choose the pattern, choose eviction, and address the downsides.
- Identify the bottleneck with numbers. Metadata reads are about 2–3 million per second at peak. A database read takes 1–10 ms and a Redis read about 0.5–1 ms, while an in-process cache read takes microseconds. Without caching we would need thousands of database replicas.
- Decide what to cache. Data that is read often, changes rarely, and is expensive to assemble:
- Track, album and artist documents per market:
meta:track:{id}:{market}. - Playback resolves per (track, market, plan, device class):
resolve:{id}:{market}:{plan}:{class}, for a few minutes. - Playlist pages keyed by revision:
pl:{id}:{snapshot}:{page}. A new revision means a new key, so no invalidation is needed. - Search results per (normalised query, market, type):
q:{hash}:{market}:{type}. - User entitlements (plan, country) for the session.
- Track, album and artist documents per market:
- Choose the pattern.
- Cache-aside (the default): check the cache, on a miss load from the store and populate the cache. Used for metadata and resolves.
- Write-through: the writer updates the store and then the cache synchronously. It fits per-user data such as library and settings, where a user expects to see their own change at once. It still suffers from the dual-write problem: if one write succeeds and the other fails, they disagree. So we still use TTLs and invalidation as a safety net.
- Write-behind (write-back): accumulate in the cache and flush to the store asynchronously. It suits public play counters and follower counts, where losing a few increments in a crash is acceptable. It does not suit royalties, which come from the event log instead.
- Read-through: the cache itself loads missing data. The CDN is a read-through cache for both audio and public API responses.
- Choose eviction and expiry. LRU is the safe default. LFU suits stable hot sets such as the top editorial playlists. FIFO is rarely right because it evicts hot items just because they are old. TTL is not an eviction policy but a freshness bound. Combine TTLs with LRU: minutes for resolves, hours for album documents (with explicit invalidation on change), seconds to a minute for search results.
- Address the downsides.
- Stampede (thundering herd). At midnight, millions of users open the same new album, whose cache entry has just been created or invalidated. Use request coalescing (single flight: one loader per key, everyone else waits for its result) and pre-warming (build the document before the release flips). Probabilistic early refresh helps for TTL-based keys.
- Consistency. A takedown or a rights change must not be hidden by a cache. On a rights change, the catalogue publishes an invalidation event (via change data capture), and every cache layer deletes the affected keys. Short TTLs bound the damage if an invalidation is lost.
- Hot keys. A playlist with 30 million followers, or a global superstar's artist page, can overload one Redis shard. Replicate hot keys under several suffixes (
pl:123#0topl:123#7) and read a random copy, add an in-process cache with a short TTL in each API server, and put public pages behind the CDN. - Cache failure. If a Redis cluster is lost, the database would receive the full read load. Circuit breakers and per-key request coalescing in the service, together with in-process caches, keep the database alive while the cache warms up again.
See Caching Strategies: Cache-Aside, Read-Through, Write-Through, Write-Behind, Cache Eviction and Invalidation and Cache Failure Modes: Stampedes, Hot Keys and Penetration for the general patterns.
5. The catalogue: identifiers, rights and per-market views#
The catalogue is mostly a rights system. Storing 100 million titles is easy. The hard part is answering, for every request, "may this user, on this plan, in this country, right now, play this recording?", and showing the right version of every album page in 184 markets.
Identifiers. Industry identifiers connect the service to labels and collecting societies:
- ISRC identifies a recording. It is assigned by the label, so it can be wrong or reused by mistake.
- UPC/EAN identifies a release (the product).
- ISWC identifies a composition (the work). It is needed for publishing royalties.
- IPI/ISNI identify writers and artists, although coverage is patchy.
The service adds its own stable internal IDs (Spotify uses 22-character base-62 IDs in URIs such as spotify:track:...). Internal IDs are needed because industry IDs are not unique enough to be primary keys. The same ISRC can appear on a dozen releases (album, deluxe edition, compilation, single), and occasionally two different recordings carry the same ISRC by mistake.
Entity resolution. There are several bands called "Nirvana". A new delivery from a small distributor might credit "Nirvana" and mean a different act. Ingestion must decide whether a credited artist is an existing profile or a new one, using the distributor's artist ID, other releases, ISNI codes and human review for ambiguous cases. Mistakes are visible and painful (a stranger's track appearing on a famous artist's page), so there is a workflow for artists and labels to report and fix mismatches.
How rights arrive. A DDEX ERN message carries deals for each release or track: territories, usage types (on-demand streaming, non-interactive, download), commercial models (subscription, ad-supported), and start and end dates. Updates arrive as new messages, including takedowns (a deal ending now). Ingestion must:
- Apply messages for one release in order. A takedown processed before an older update would be undone by it. Each message carries a creation timestamp, and ingestion keeps a per-release sequence.
- Be idempotent. Partners resend messages, so processing the same message twice must have no effect.
- Diff the new state against the old one, so only actual changes produce downstream events.
Precompute playability. Evaluating raw deals on every play would be slow. A rights compiler turns deals into a compact serving form for each track: for each plan, a bitmap of markets where it is playable now, plus the timestamp of the next change (for example, Friday 00:00 in each time zone for an upcoming release). A scheduler wakes up at each next-change time and recompiles the affected tracks. Releases often go live at midnight local time, so a global release produces about 40 scheduled flips, one per distinct time-zone offset.
Per-market documents. A projector consumes the catalogue's change stream (change data capture from the source-of-truth database) and builds denormalised documents per (entity, market): an album page for India lists only the tracks playable in India, in the right order, with localised names and the right artwork. These documents go to a key-value store and the caches, versioned so that a reader never mixes two versions.
Track relinking. Suppose a user's playlist contains the deluxe-edition version of a song, which is not licensed in their new country, while the standard edition is. Showing it greyed out is poor. Relinking substitutes an equivalent playable recording (same ISRC, or a recording linked as the same audio) at read time, while keeping the original in the playlist. Spotify's public Web API documents this kind of relinking. The response flags it, so the client can show the original information.
Takedowns must win quickly. When a label pulls a track, the requirement is minutes, not hours. Defence in depth:
- The rights compiler marks the track unplayable and publishes an invalidation.
- Caches holding resolves and documents for that track delete them. Short TTLs bound the damage if an invalidation is missed.
- The key service consults the same rights cache and refuses keys for that track's files. Even a client holding a stale signed URL cannot decrypt the audio.
- Offline licences that include the track are revoked at the next licence check.
Consistency model. The source of truth is strongly consistent. Serving documents are eventually consistent, usually within seconds. That is acceptable for an album page. For rights it is also acceptable, because the key service gives a second, fresher check on the money and legal path. See Change Data Capture and the Outbox Pattern for keeping derived stores in step.
6. Playlists: ordering, revisions and collaboration#
Shapes of playlists. Most user playlists are small (tens of tracks). A few are long (thousands of tracks). A small number of editorial and algorithmic playlists are followed by tens of millions of users. The system must make small playlists cheap, long playlists efficient to page through, and huge-follower playlists cacheable.
How to store order. Three common designs:
| Design | How it works | Good at | Bad at |
|---|---|---|---|
| Whole list as one blob | The playlist is one value (a list of entries) with a revision. Every edit reads, modifies and writes it. | Simple; one read loads everything; atomic edits | Big playlists cost a big write per edit; hot write contention |
| Integer positions | One row per entry with position 0, 1, 2 ... | Easy paging | Inserting at the top renumbers every row |
| Fractional position keys | One row per entry with a sortable string key. A new entry between a0 and a1 gets a0V. | Insert or move touches one row; paging by key | Keys grow with repeated inserts in one spot; needs occasional rebalancing |
A practical hybrid uses fractional keys in a wide-column store, with one partition per playlist and rows sorted by position key (the CQL in the Data Model). A background job rebalances the keys of a playlist when they get long. For small playlists, storing the whole list as one blob is also fine and simpler. The choice can even differ by size.
Revisions and the snapshot ID. Every successful change increments the playlist's revision and returns a new snapshot_id. Clients send the snapshot they based their edit on. The header write is a conditional write (a compare-and-set on the revision, for example a lightweight transaction in Cassandra or a condition expression in DynamoDB). This is optimistic concurrency control: no locks, and conflicts are detected rather than prevented.
Rebasing instead of rejecting. The service keeps a short operation log per playlist: insert, remove and move operations with the revision that produced them. When a stale edit arrives, the service transforms it over the operations it missed (Flow 3):
- Bob's "move entries 7–8 to before 2", based on r41, arrives after Alice inserted at position 3 in r42. In r42 coordinates, Bob's entries are now at 8–9, so the move becomes "move 8–9 to before 2".
- If Bob's operation refers to entries that were deleted, or the log no longer reaches back to his base revision, the service rejects it, and the client reloads and asks the user to retry.
Referring to entries by a stable entry ID (or by the position key plus the track ID) rather than by bare index makes rebasing much safer. This is a light form of the operational transformation used in collaborative editors. Playlists need far less than a text editor, because operations are coarse and conflicts rare.
Offline edits and sync. A user edits a downloaded playlist on a plane. The client queues the operations with their base revision. On reconnect, it sends them in order. The server rebases them over whatever happened meanwhile, applies them and returns the new snapshot.
When a client opens a playlist it has cached, it sends its snapshot. If the operation log covers the gap, the server returns just the delta (the operations since then); otherwise it returns the full playlist. For a huge editorial playlist updated weekly, that is one small download a week.
Following, libraries and counts.
- Following a playlist writes a row into the follower's library partition (
user_id, item, added-at). It never copies the playlist. - The follower count is a sharded counter (several sub-counters summed on read), or is updated by the stream processor from follow events. It is displayed approximately ("12,345,678 saves"), so a few seconds of lag do not matter.
- A user's library is read on every app start. It is cached on the device and synced with the same snapshot-and-delta approach.
Generated playlists at scale. The weekly discovery playlist and daily mixes are playlists owned by the system, one set per user. Writing 700 million playlists a week through the normal API would be wasteful. A batch job writes them in bulk directly into the storage format: Spotify described bulk-loading Cassandra by building SSTables from HDFS and streaming them into the cluster, using a tool it open-sourced called hdfs2cass. Clients see the new version on Monday because the playlist's revision changes.
Hot editorial playlists. A top editorial playlist might get many thousands of reads per second. Because pages are cached by (playlist, snapshot, page), a new revision needs no invalidation: readers simply ask for the new key. The previous pages expire naturally. The CDN can serve the public, non-personalised page per market.
Limits and abuse. Cap playlist length, the edit rate per user, and the number of collaborators. Rate-limit follows (follower count manipulation is a known form of promotion fraud). Strip injected text from names and descriptions before indexing them for search.
7. Search: short queries, many scripts, popularity first#
What makes music search different from web search.
- Queries are short and navigational. Most queries are names: an artist, a song, an album, a playlist. The user usually knows what they want, and the answer is usually popular.
- Typeahead is the main interface. Results update on every keystroke, so a single search is 5–10 requests, and the first few characters must already give good answers.
- Names are messy.
P!nk,$uicideboy$,MØ,beyoncétyped asbeyonce,AC/DCtyped asacdc, Korean artists searched in Hangul or in Latin letters, Hindi songs searched in Latin transliteration (tum hi ho). Normalisation and aliases matter more than clever linguistics. - Popularity is the strongest signal. For the query
hello, there are thousands of tracks named "Hello", and the user almost certainly wants one of the two or three most played. - Mixed entity types. One result list holds artists, tracks, albums, playlists, podcasts and audiobooks, plus a single "top result".
The index. One document per entity, with fields such as:
name,name_folded(lowercased, accents removed, symbols mapped:!toi,$tos,Øtoo),aliases,transliterations.artist_namesfor tracks and albums, soqueen bohemianmatches.popularity: a log-scaled score from recent streams, updated daily by partial updates.markets: a filter field. Unplayable items are filtered out per market rather than scored down.type,release_date,explicit.
Analysers produce edge n-grams of each name token (b, bo, boh, ...) so prefix queries are cheap lookups. Fuzzy matching (edit distance 1 for medium words, 2 for long ones, using Levenshtein automata as in Lucene) catches typos such as eminen.
Ranking in two stages.
- Retrieve a few hundred candidates per type by text match (BM25 over the name fields, with exact and prefix matches boosted) combined with the popularity prior.
- Re-rank with a learned model that uses query–entity features (exact match, prefix match, edit distance, which field matched), entity features (popularity, recency, type), aggregated click-through rate for this query and entity, and personal features (does this user follow the artist, did they play it recently, their language and genre mix).
Choosing the top result across types is a separate decision. For drake it is the artist; for drake hotline it is the track.
Caching: share what can be shared. The expensive part, retrieving and scoring candidates, is the same for every user in a market. Personalisation is a cheap re-rank of the top 50. So:
- The query result cache (a distributed cache next to the search service) stores the shared top candidates keyed by (normalised query, market, type set). A short TTL, under a minute, keeps new releases and takedowns visible quickly. New posts in social search have a similar freshness bound, and the same short-TTL pattern applies.
- Very short prefixes are precomputed. For every market, the top results for all one-, two- and three-character prefixes (and the most common longer ones) are built offline and served from memory, much like autocomplete tables in Design Search Autocomplete (Typeahead).
- Edge caching. The non-personalised response for a popular query can carry
Cache-Control: public, max-age=30and be cached at the CDN. A hit there takes tens of milliseconds instead of a round trip through the gateway, search service and cache. - Query cache sizing. Classic search-engine query caches keep the most recent queries in an LRU map from query to result list. If the top 10 million (query, market) pairs cover most traffic and each entry is about 2 KB, the cache is about 20 GB, which a small Redis or Memcached cluster holds easily. Query frequencies follow a power law like track plays, so hit ratios of 70–90% are common for typeahead.
Indexing. The indexer consumes catalogue and playlist change streams, so a new release becomes searchable in minutes. Popularity is updated in a daily partial-update job. Big changes (a new analyser, a new field) use a rebuild and swap: build a new index offline, warm it, then switch an alias atomically, which makes a bad build easy to roll back.
Sharding. A few TB of index fit on tens of shards. Queries need high QPS rather than huge fan-out, so the index is split into a moderate number of shards (for example 20–40) with many replicas per region. Entity types can live in separate indexes with their own replica counts: tracks and artists are queried most.
Learning from logs. Search logs (query, results shown, clicks, the play that followed) drive spelling suggestions, synonym and alias discovery (acdc is followed by a click on AC/DC), the ranking model, and a zero-results dashboard that reveals catalogue gaps and new slang. See Elasticsearch and Search Systems for the index internals.
8. Offline downloads and DRM#
What DRM can and cannot do. No DRM stops a determined person from recording the analogue output. The realistic goals are narrower but important:
- Files copied off a device are useless elsewhere.
- Downloads stop working when the subscription lapses or the rights end.
- Bulk extraction of keys is hard and detectable.
- The terms in label contracts are enforced (for example, device limits and periodic online checks).
The key hierarchy.
- Each file has its own content key. Leaking one key exposes one rendition of one track, not the catalogue.
- At rest in the service, content keys are wrapped by a master key in a KMS or HSM.
- For streaming, the key is delivered to an authenticated session over TLS and held only in memory.
- For offline, keys are wrapped with a key that belongs to this device: a key in the platform's secure storage (Android Keystore, the iOS Secure Enclave) or the device key of a DRM module. On the web, browsers expose DRM through Encrypted Media Extensions (EME) with a content decryption module such as Widevine. Widevine has security levels: L1 does decryption and decoding inside a hardware trusted execution environment, and L3 does it in software. Services may offer the highest qualities only on stronger levels.
The licence policy. Spotify's help pages describe the policy for Premium:
- Downloads of up to 10,000 tracks on each of up to 5 devices.
- The app must go online at least once every 30 days to keep downloads. The stated reason is so that play data can be collected to pay artists.
- On the free plan, only podcasts can be downloaded.
The design maps this onto an offline licence per device: a signed object with the device ID, the key IDs covered, an issue time and an expiry 30 days later.
Renewal. On reconnect, the client:
- Uploads queued offline play events (Flow 5), with their original timestamps and an
offlineflag. - Sends its licence IDs and a monotonic counter.
- The server checks that the subscription is active, that the device is still registered, and that each track is still licensed in the user's country. It then issues a new expiry and lists any keys to delete (takedowns, lapsed rights).
Clock tampering. Setting the device clock back would extend a licence. The client therefore stores, in protected storage, the last server time it saw and a monotonic counter. If the local clock goes backwards relative to these, it treats the licence as needing an online check. Hardware DRM modules keep their own secure clocks.
Device limits. The device registry per account enforces at most 5 offline devices. Registering a sixth asks the user to remove one, and the removed device's licences are revoked at its next check. If the removed device never comes online again, its licences simply expire within 30 days.
The download manager.
- A queue of files with priorities. The first tracks of a playlist come first, so the user can start listening before everything is done.
- Resume via range requests: the content hash tells the client exactly which bytes it has and lets it verify them.
- Wi-Fi only by default, with an option for mobile data.
- Quality chosen separately from streaming quality (download quality uses more space but no data while listening).
- Storage checks before starting, and clear errors when space runs out.
- Background transfer APIs so downloads continue when the app is not in the foreground, within platform limits.
Free versus Premium at playback. Entitlements also shape streaming. Free users get ads between tracks, shuffle-based playback on some surfaces, and lower maximum quality. The playback service enforces these when it resolves a track: it returns the quality cap and, for free users, tells the client when to fetch an ad. Enforcement lives on the server because a modified client cannot be trusted.
Trade-offs. Hardware DRM gives the strongest protection but is not available on every device. Strict policy (short licence periods, frequent checks) annoys legitimate users on long trips. The 30-day window, plus small per-file keys and server-side entitlement checks, is a common compromise between label requirements and user experience.
9. Recommendations and personalised playlists#
Why this is central. With 100 million tracks, nobody can browse the catalogue. Personalised surfaces (the home screen, weekly discovery playlists, daily mixes, radio, autoplay after an album ends) decide much of what people hear. Spotify launched Discover Weekly in July 2015, updated every Monday, and Release Radar in 2016, updated every Friday. Its engineers wrote that Discover Weekly was built on playback data and quickly became one of the most used features.
Signals. Almost all signals are implicit:
- Positive: a play that lasts beyond 30 seconds, a completed play, a repeat, a save to the library, an add to a playlist, an artist follow, a share.
- Negative: a skip in the first few seconds, "hide this song", removing a track from a playlist.
- Context: time of day, day of week, device (car, speaker, phone), activity playlists (workout, sleep), and the context the play came from (search, album, radio).
Context matters. Spotify's personalisation team gave the example of a metal fan who plays children's music at bedtime: recommending a metal album at that moment is wrong, even though it fits the long-term taste.
Collaborative filtering with implicit feedback. The classic method is from "Collaborative Filtering for Implicit Feedback Datasets" (Yifan Hu, Yehuda Koren and Chris Volinsky, ICDM 2008). Let r(u,i) be how much user u played item i. Define:
- a preference p(u,i) = 1 if r(u,i) > 0, else 0. Not having played something is weak evidence of dislike.
- a confidence c(u,i) = 1 + α · r(u,i). Many plays mean we are sure of the preference. The paper found α around 40 worked well on its data.
Then find a vector x(u) for each user and y(i) for each item (say 100–200 dimensions) that minimise
Σ over all (u,i) of c(u,i) · (p(u,i) − x(u)·y(i))² + λ · (Σ ‖x(u)‖² + Σ ‖y(i)‖²).
The sum runs over all pairs, including unplayed ones, which looks impossible at 700 M × 100 M. The trick is alternating least squares (ALS). Fix all item vectors and solve for each user in closed form, then fix users and solve for items, and repeat. For one user, the solution is x(u) = (YᵀC(u)Y + λI)⁻¹ YᵀC(u)p(u). Because c(u,i) = 1 for unplayed items, YᵀC(u)Y = YᵀY + Yᵀ(C(u) − I)Y. Here YᵀY is shared by all users and computed once, and the correction involves only the items this user actually played. Each user update therefore costs time proportional to the user's own history, not the catalogue size. The whole job parallelises across users, then across items, on a cluster (Spark, Beam or MapReduce).
Playlist co-occurrence embeddings. Billions of user-made playlists are a huge, free signal of which tracks "go together". Treat each playlist (or listening session) as a sentence and each track as a word, and train a word2vec-style model (Mikolov and colleagues, 2013): tracks that appear in similar contexts get similar vectors. This captures mood and scene ("songs for a rainy Sunday") that plain co-listening misses.
Content-based models for the cold start. A track uploaded yesterday has no plays, so collaborative methods know nothing about it. "Deep content-based music recommendation" (Aäron van den Oord, Sander Dieleman and Benjamin Schrauwen, NIPS 2013) trained a convolutional network on audio spectrograms to predict a track's collaborative-filtering vector from its audio. A new track can then be placed in the same embedding space as everything else. Text about artists (reviews, blogs, descriptions) and metadata (genre, label, era, credits) add more cold-start signals.
From embeddings to playlists: the pipeline.
- Candidate retrieval uses approximate nearest neighbour (ANN) search over track embeddings, starting from the user vector or from tracks the user loves. Spotify open-sourced Annoy, a tree-based ANN library, and later Voyager, which is based on HNSW graphs. See Vector Databases and Similarity Search for HNSW, IVF and product quantisation.
- Filtering "already heard". A discovery playlist must contain only tracks the user has never played. The batch job joins candidates against each user's full play history. A per-user Bloom filter of heard tracks (about 10 bits per track at a 1% false-positive rate, so about 12 KB for a 10,000-track history) makes this cheap in online surfaces. A false positive only drops a good candidate; it never repeats a heard track. See Probabilistic Data Structures for Big Data.
- Ranking predicts outcomes we can measure: will this be streamed past 30 seconds, saved, or skipped? A gradient-boosted tree or a neural network uses user, track and context features plus cross features (affinity to the artist, genre match).
- Re-ranking fixes what a pointwise model ignores: at most one or two tracks per artist, a mix of familiar-adjacent and adventurous picks, and a pleasant order (no jarring jumps in tempo or energy).
Batch generation at scale. The weekly discovery playlist is a batch job over all users. It must finish before Monday morning in the earliest time zone, so it runs from the weekend with checkpoints, and users are processed in shards. Outputs are bulk-loaded into the recommendation store and the playlist store (Deep Dive 6). Failure handling is simple and important: if the job fails for some users, serve last week's playlist rather than an empty one, and alert.
The home screen: real time, bandits and explanation. The home screen is ranked when the app opens, using precomputed candidates plus fresh context. Spotify's 2015 personalisation stack used Kafka for event collection, Storm for real-time processing, Crunch on Hadoop for batch jobs, and Cassandra for a user profile store and an entity metadata store. A modern equivalent would use Flink or Beam with a feature store, but the shape is the same: stream processing keeps "what did this user do in the last hour" fresh, and batch jobs provide long-term taste.
Choosing which shelves to show is an explore–exploit problem. Showing only what is known to work narrows taste over time and never learns about new shelves. Contextual bandits reserve a small share of impressions for exploration and learn from the results. Spotify researchers described a bandit approach for explainable home-screen recommendations in "Explore, Exploit, and Explain: Personalizing Explainable Recommendations with Bandits" (McInerney and colleagues, RecSys 2018).
Measuring. Offline metrics (recall at k on held-out plays, NDCG) guide development, but decisions come from A/B tests on stream rate, saves, retention and long-term listening diversity. Spotify has written that most of its product decisions are based on A/B test results, which in turn depend on complete, accurate event data. The case study Design an A/B Testing and Experimentation Platform covers how such tests are run.
Risks and responsibilities.
- Popularity bias and feedback loops. Recommending what is already popular makes it more popular. Exploration, diversity constraints and fresh-content quotas counteract this.
- Fairness to new artists. Cold-start content models give new tracks a chance to be recommended.
- Promotion transparency. If labels can pay to be boosted, users and regulators expect disclosure.
- Generative features. Text-prompted playlists ("sad songs for a rainy commute") add a language model that maps the prompt to embeddings and constraints, then reuse the same retrieval and ranking stack. See Designing LLM and AI-Powered Systems.
The case study Design a Recommendation System (Twitter For You) covers candidate generation and ranking architecture in more general depth. See also ML System Design and Feature Stores.
10. The event pipeline: a million events a second, reliably#
Events are the raw material for almost everything: royalties, charts, play counts, recommendations, A/B tests, year-end summaries (the "Year in Music" feature, later known as Wrapped), fraud detection and product analytics. Spotify has written that its usage data is one of the sources for Billboard charts.
On the client.
- Every event has a schema registered centrally (Avro or protobuf), a client-generated event ID (a UUID), a per-device sequence number and a client timestamp.
- Events are written to an on-device queue first, then sent in compressed batches every few seconds, when the app goes to the background, or when the queue gets big.
- Delivery from the client is at least once: if a batch upload times out, it is retried, so duplicates are expected and removed downstream by event ID.
- Offline plays can sit in the queue for up to 30 days. The queue must survive app restarts and be bounded in size, dropping low-value events (UI impressions) before play events.
Which timestamp? Spotify's 2016 post explains that its event delivery used the timestamp assigned when an event reached its gateway, not the client's, because the system cannot control events before they reach its servers. Server time lets the pipeline say "the 14:00 hour is complete". The design keeps both:
- Receive time for partitioning and completeness.
- Client (event) time for analysis such as "what did this user play at 7 am".
Lessons from a real redesign. Spotify's posts describe its first-generation system, built on Kafka 0.7. A producer daemon on every server tailed log files and sent lines through brokers and Spotify-written "groupers" to a consumer that wrote hourly files to a central Hadoop cluster. A line counted as delivered only once it was on HDFS. An ETL job then converted tab-separated text to Avro, adding about 30 minutes of latency. To decide when an hour was complete, producers sent end-of-file markers, and a liveness monitor tracked which machines were alive. The lessons generalise well:
- Hand over durably close to the producer. Waiting for an acknowledgement from a data centre on another continent made delivery fragile. Handing events to a durable queue in the local data centre is much simpler.
- Separate streams per event type. Sending everything through one channel meant no per-type quality of service, and real-time consumers had to filter the whole firehose.
- Send structured data. Unstructured lines forced a slow ETL step; structured Avro is usable as soon as it lands.
- Do not make senders responsible for completeness. A dead machine cannot send its end-of-file marker, and the hour waits forever.
The system pushed more than 700,000 events per second across continents. It was replaced by one based on Google Cloud Pub/Sub, which was load-tested at 2 million events per second, with Dataflow consuming the events.
Completeness versus latency. Most batch jobs read an hourly partition once. If late data arrives after the hour was "closed", those jobs will not see it unless someone reruns the whole chain, which is very expensive. So the pipeline must decide when an hour is complete, using watermarks based on receive time across all gateways, and publish it. Data that arrives later (mainly offline plays) goes into the partition of the hour it was received. That matches how Spotify says it counts streams from downloads: when the listener goes online. Royalty and chart jobs then never need to rewrite closed periods; they just see the offline plays in a later period.
Exactly once where it matters. End to end, the pipeline is at least once. Deduplication by event_id happens in two places: approximately, in the stream processor (a TTL-bounded set of recent IDs per partition), and exactly, in the batch job (a DISTINCT on event ID over the period, joined with the previous period to catch boundary duplicates). Lake files are committed atomically (write a temporary file, then rename or commit to a table format), so a retried writer does not produce half files. See Delivery Guarantees: At-Most, At-Least and Exactly-Once.
11. Play counts, streamshare and royalties#
Why this is the most sensitive pipeline. Every count here is money. Rights holders audit it, regulators and courts look at it, and fraudsters attack it. The design goal is a reproducible ledger: given the same input events and the same rules, the monthly result must be identical every time it is recomputed.
Step 1: what counts as a stream. Spotify says a song stream is counted when a listener plays it for at least 30 seconds, and that streams from downloaded music are counted when the listener goes online (which they must do at least once every 30 days). Stats are recorded in UTC. In the pipeline this becomes a rule applied to playback events:
- A play session starts with a
play_startevent and ends withplay_end, a skip, a track change or a timeout. The client also sends a heartbeat every few seconds, so a crash still leaves evidence of how long a track played. - Listened milliseconds are summed from the events, ignoring time spent paused or seeking forward. A play becomes a stream when this total reaches 30,000 ms.
- The rule version is stored with every computed stream, so a future rule change never silently changes past months.
Step 2: cleaning. Before streams enter the royalty pool, an artificial-streaming system removes suspicious ones. Spotify describes its detection as industry leading but keeps the details private, which is normal: published rules get gamed. Typical signals in any such system:
| Signal | Why it is suspicious |
|---|---|
| One account plays the same track hundreds of times a day | Humans do repeat songs, but not around the clock |
| Plays last 31–35 seconds, again and again | Just over the threshold, the pattern of a bot |
| Many new free accounts from one IP range, device model or payment card | Account farms |
| A small catalogue with almost all listeners from playlists of unknown origin | Paid "playlist placement" schemes |
| No skips, no saves, no searches, no other activity | Real listeners interact with the app |
| Listening at a constant rate 24 hours a day | Humans sleep |
Fraud scoring runs at two speeds. Streaming jobs catch obvious bots within minutes so they can be throttled. Batch models score each month with full context (graphs of accounts, devices and tracks) before the close. Removed streams are kept with a reason code, because distributors and labels may appeal.
Step 3: eligibility. Since April 2024, a recording (identified by its ISRC) must have had at least 1,000 streams in the previous 12 months, and a minimum number of unique listeners, to be included in the recorded-music royalty pool. Spotify keeps the listener minimum private. Its published reasons: tracks below 1,000 annual streams averaged about $0.03 a month, made up about 0.5% of streams, and often never reached the artist because distributors have withdrawal minimums and fees. In data terms this is a rolling 12-month count per ISRC plus an approximate distinct-listener count. A HyperLogLog sketch per ISRC per month, merged over 12 months, gives the distinct count cheaply (about 1.6% standard error with 4 KB sketches), and exact counts are computed only for tracks near the threshold.
Step 4: streamshare. Spotify says it does not pay a fixed rate per stream. Instead, each month and each market:
- Take net revenue from Premium subscriptions and ads in that market (after taxes, card fees, billing costs and some other deductions).
- The royalty pool is roughly two-thirds of what Spotify earns from music, according to Spotify. That pool is split between recording rights (labels and distributors) and publishing rights (songwriters and publishers).
- Streamshare = a rights holder's eligible streams ÷ all eligible streams in that market and month. If a track gets 1% of streams, it gets 1% of that month's recording pool, which is then passed on under each label or distributor contract.
Spotify calculates separate pools for each of its 180+ markets.
A worked example: pro-rata versus user-centric. Consider a tiny market with two Premium users, each paying $10, and a pool of $13.
- User A plays 1,000 streams a month, all by artist X.
- User B plays 10 streams a month, all by artist Y.
| Model | Artist X gets | Artist Y gets |
|---|---|---|
| Pro-rata (streamshare across the market) | 1,000/1,010 × $13 ≈ $12.87 | 10/1,010 × $13 ≈ $0.13 |
| User-centric (each user's money follows their own listening) | $6.50 (A's share) | $6.50 (B's share) |
Pro-rata rewards whatever is played most overall, including by heavy listeners. User-centric follows each subscriber's money, so it treats B's light listening as more valuable per stream. User-centric is debated in the industry, but costs more to compute: it needs a per-user split rather than one global ratio. That means a join of 700 million users' listening with their own payments, about 10⁹–10¹⁰ (user, track) pairs a month, instead of a simple aggregate per track. Both are feasible on a batch cluster. The real argument is about policy, and about fraud: under pro-rata, a bot account's streams dilute everyone; under user-centric, a bot only redistributes its own subscription.
Step 5: the publishing side. Publishing royalties go to publishers, collecting societies and mechanical agencies, depending on the territory. In the United States, mechanical royalties from streaming services are administered by the Mechanical Licensing Collective (MLC). The data problem is joining recordings (ISRC) to compositions (ISWC) and to writer shares (IPI numbers). Those links are often missing or conflicting, so unmatched usage is reported and held until it is claimed. That is why catalogue identity (Deep Dive 5) matters to money and not only to search.
Step 6: the monthly close. The pipeline must be designed for audit.
- Inputs are frozen. The close records the exact snapshot IDs of the event partitions, catalogue, deals and revenue it used. Re-running with those snapshots gives the same output bit for bit, which is how disputes are answered.
- Corrections are new rows. If fraud is found after a month closed, the next month carries an adjustment entry. Nobody edits a closed month.
- Money is decimal. Store amounts as integer micro-units with currency codes. Floating-point sums in a different order give different cents.
- Totals must reconcile. The sum paid to all rights holders in a market must equal the pool for that market, to the cent, and the job fails if it does not. See the case study Design a Payment System for ledger design.
Public play counts are approximate on purpose. The counter on an album page (Deep Dive 6 mentioned sharded counters for followers; play counts work the same way) is updated from the streaming pipeline with a lag of hours or a day and rounded for display. It is not the royalty number, and Spotify says the counts in Spotify for Artists do not always equal royalty-eligible streams. Keeping the two separate lets the public counter be cheap and eventually consistent, while the ledger is exact and slow. If a recording becomes unavailable, Spotify keeps its all-time count for 90 days, so a short takedown does not reset an artist's numbers.
12. Devices, entitlements, ads and staying up#
Multi-device control (Spotify Connect). A user can start music on their phone, move it to a speaker, and control it from a laptop. The phone is only a remote; the speaker fetches and plays the audio itself. A design for this:
- Each logged-in device holds a persistent connection (WebSocket or a long-lived push connection) to a connect state service, keyed by user.
- The service stores one player state per user: active device, track, position, a timestamp, the queue, shuffle and repeat. Position is stored as "position p at server time t, playing", so every device can compute the current position without a stream of updates.
- Commands ("pause", "next", "transfer to kitchen speaker") are sent to the service, which orders them with a version number per user and forwards them to the active device. The device applies the command and publishes its new state. Two people tapping "next" at the same moment produce two versioned commands, and both are applied in order, rather than half-applied.
- The data is small: perhaps 2 KB per active user, so 50 million active sessions fit in about 100 GB of memory across a cluster of Redis-style nodes, sharded by user ID. See Redis in Practice.
- If the state service is down, each device still plays locally. Only cross-device control fails, which is the right failure mode.
Concurrency limits. A Premium Individual account may stream on one device at a time. When a second device starts, the connect service tells the first one to stop and shows a message that the account is in use elsewhere. Family and Duo plans are several accounts, each with its own limit. This is enforced by the same per-user state, not by the CDN.
Entitlements. Which features a user has (free with ads or Premium, plan type, market, audiobook hours, lossless audio) lives in an entitlement service fed by billing.
- The playback path needs this on every play, so it is embedded in the signed session token with a short lifetime (for example one hour) and refreshed in the background. A downgrade then takes effect within the token lifetime, which is acceptable.
- Billing events (renewal failed, plan changed, refund) are published as events, and the entitlement service updates the user and pushes a token refresh to connected devices.
- Free-tier rules (shuffle-only on some surfaces, limited skips, ads) are enforced by the server where they matter commercially: the resolve API refuses "on-demand" requests the plan does not allow, and the ad decision is made on the server.
Audio ads. On the free tier, audio ads are inserted between tracks. The client asks an ad decision service for the next break a few tracks ahead, so there is time to choose and download the ad. Ads are audio files on the same CDN, loudness-normalised so they are not louder than the music (a common complaint about radio). Impressions are events with their own topic and stricter deduplication, because advertisers are billed per impression. Spotify has also described inserting ads on the server for podcasts. The counting problems are the same as in the case study Design an Ad Click Aggregator.
Reliability: deciding what can fail. A music service's core promise is "press play and it plays". Rank the dependencies by what the user notices:
| Tier | Components | If it fails |
|---|---|---|
| Must work | Login token validation, resolve, CDN, key service, client cache | Nothing plays. Keep these simple, multi-region and over-provisioned. |
| Should work | Search, catalogue pages, playlists | Show cached versions. Played music keeps playing. |
| Can degrade | Home recommendations, lyrics, canvases, social features | Show a generic home screen or hide the shelf. |
| Can be late | Events, play counts, royalties, Wrapped | Queue on the client and in the pipeline. Catch up later. |
Techniques that follow from that table:
- Static fallbacks. If the home service is down, serve a precomputed regional home screen from the CDN.
- Client resilience. The app already holds the next tracks, cached playlists and recent search results, so a short outage shows up as "can't load new things" rather than silence. Downloaded music keeps working for up to 30 days offline.
- Timeouts and bulkheads. The resolve API calls rights, key and CDN-token services with strict timeouts (tens of ms) and separate connection pools, so a slow lyrics service never steals capacity from playback. See Resilience Patterns: Timeouts, Retries and Circuit Breakers.
- Multi-region active-active. Read paths (catalogue, rights, keys) are replicated to every region. Write paths for user data (playlists, library) have a home region per user, with asynchronous replication for reads elsewhere. See Designing for High Availability and Multi-Region and Global Data.
- Release-day load. Big album releases happen at midnight local time on Fridays. The load is predictable, so capacity is added in advance and the CDN is pre-warmed (Flow 4). See Capacity Planning and Load Testing.
- Safe deploys. Client apps ship to a small percentage first, with remote feature flags that can turn off a broken feature without a store release. Server changes use canaries watched on the "time to first audio" and "playback error rate" metrics, not just CPU. See CI/CD and Deployment Strategies and Observability: Logs, Metrics and Traces.
The metrics that matter. Track user-facing service levels, not machine health:
- p50/p95/p99 time to first audio, split by cached and uncached plays, by country and by network type;
- stutter rate: the share of plays with a buffer underrun, per 1,000 minutes played;
- playback error rate split by cause (rights, keys, CDN, decode);
- search success: the share of searches followed by a play within 30 seconds;
- event pipeline lag and completeness: the share of expected events received for each closed hour.
Bottlenecks and Failure Modes#
| Failure / hotspot | Impact | Mitigation |
|---|---|---|
| Friday midnight release of a superstar album | Millions request the same new files within minutes, and CDN caches are cold | Pre-warm the CDN and origin shield from the release schedule; request collapsing at the shield; extra origin capacity booked in advance |
| CDN provider outage in a region | Playback starts fail for uncached tracks | Multi-CDN with health-based steering in the resolve response; clients retry the next URL; device caches cover repeat listening |
| Rights service slow or wrong | Plays fail, or tracks play where they are not licensed | Precompiled rights bitmaps cached in every region; fail closed for new releases, keep the last good snapshot for the rest; reconciliation alerts |
| Key service unavailable | Encrypted audio cannot be decrypted, so nothing new plays | Keys cached on devices for cached tracks; multi-region key service with HSM-backed roots; short timeouts and fast failover |
| Hot editorial playlist (tens of millions of followers) | Read load on one partition when the playlist changes | Serve the playlist from cache and CDN by snapshot_id; push only "new snapshot" notifications; keep the header small |
| Collaborative playlist write conflicts | Lost adds or reordered tracks | Operations with snapshot_id checks, rebase on the server, fractional ordering keys; clear "updated elsewhere" handling |
| Search cluster overload during a viral moment | Slow or failed searches | Query cache with a short TTL, CDN caching of popular prefixes, load shedding of fuzzy and rare queries first |
| Event pipeline backlog | Late play counts, stale recommendations, late royalties | Durable regional queues absorb bursts; autoscale consumers; watermarks so hours close correctly; clients buffer events |
| Offline devices flooding events on reconnect (for example after a long flight landing) | Spikes at the gateways | Client jitter and batching; gateway rate limits per device; events accepted into the hour they arrive |
| Artificial streaming farms | Royalties diverted from real artists; skewed charts and recommendations | Real-time throttling plus monthly batch fraud models; eligibility thresholds; keep removed streams with reason codes for appeals |
| Weekly personalised playlist job fails part-way | Users get no new discovery playlist on Monday | Checkpointed sharded jobs; serve last week's playlist on failure; start early enough to rerun |
| A bad client release (for example a player bug that breaks gapless playback) | Millions of users affected, and app store fixes take days | Staged rollouts, remote feature flags and kill switches, client crash and stutter metrics per version |
What Interviewers Expect#
Mid-level. Separate the control plane (catalogue, playlists, search) from the data plane (audio files on a CDN). Estimate storage and bandwidth correctly, notice that bandwidth (terabits per second) is the real cost and that popular tracks dominate, and propose a CDN plus a device cache. Design simple APIs for play, search and playlists, and a reasonable data model. Mention that plays are recorded as events for counts and recommendations.
Senior. Explain how to make playback feel instant: a resolve call that returns URLs and keys together, burst downloads of the first seconds at a lower bitrate, prefetching the next track, and a latency budget. Pick and justify stores for each data type (a relational store for rights and deals, a wide-column store for playlists and user data, a search engine, object storage for audio). Handle collaborative playlists with versioning, offline downloads with licences that expire, the 30-second stream rule, and an event pipeline with deduplication and late data. Discuss release-day load and multi-CDN.
Staff and above. Treat the business rules as design inputs. Royalty calculation needs a reproducible, auditable ledger with frozen inputs, and streamshare and eligibility rules shape the data pipeline. Fraud resistance must be built in. Reason about the economics: storage tiers versus retrieval costs, CDN cost per GB against a custom edge, and the cost of user-centric payouts. Talk about organisation and evolution: Spotify's move from its own data centres and Kafka-based delivery to a managed cloud pipeline, and why separate event types and local durable handover mattered. Define service levels from the user's view (time to first audio, stutter rate) and decide which parts may degrade, so that "press play and it plays" survives most failures.
Deep Dive: sizing every tierShow
This walk-through turns the capacity numbers into machines, so each tier can be checked for "is this realistic?". The numbers are rough, but the method is what matters.
Edge and CDN (audio delivery).
- Peak egress is about 5.2 Tbps. One modern CDN edge server with 2 × 100 Gbps NICs and NVMe caches can serve about 100–150 Gbps of cached small-object traffic. Plan for 50–60 Gbps per server to leave headroom for failover and cache misses.
- 5.2 Tbps ÷ 50 Gbps ≈ 100 servers busy at peak worldwide, spread over perhaps 100–200 locations. With N+1 redundancy per site and spare capacity for release days, a few hundred edge servers, which is small next to a video service.
- Cache size: the top 10% of the catalogue (10 M tracks) at the two most common renditions (about 7 MB together) is about 70 TB. Each large edge site can hold that in NVMe. Small sites keep only the head of the distribution (top 1 M tracks, about 7 TB) and fill misses from a regional shield.
- Origin traffic: with a 95% edge hit ratio by bytes, about 260 Gbps reaches the shields, and with a 90% shield hit ratio about 26 Gbps reaches object storage. Object storage serves that easily, but the request rate matters: 26 Gbps of 512 KB range reads is about 6,500 requests per second, which needs keys spread across many prefixes.
Playback control (resolve, rights, keys).
- 330,000 play starts per second at peak, plus prefetches for the next track (about 1.5× total) ≈ 500,000 resolve calls per second.
- One resolve does an in-memory lookup of rights and file IDs plus a key wrap. With everything cached in-process, a server core handles 5,000–10,000 calls per second. At 32 cores per server and 50% target utilisation, that is about 100,000 per server, so 5–10 servers do the work. Deploy 20–40 per region across 4–6 regions, for latency and failure tolerance rather than throughput.
- The key service must wrap a content key for each request. Software AES key wrap takes microseconds; root keys live in HSMs, but per-request work uses derived keys in memory, so the HSM is not on the hot path.
Catalogue metadata.
- 2–3 million entity reads per second at peak. With a 98% hit ratio in a local in-process cache and a distributed cache behind it, about 60,000 reads per second reach the cache cluster. At 100,000 operations per second per Redis-style node, that is a handful of nodes per region, plus replicas.
- The source store (a few hundred GB) is a relational database with read replicas, or a wide-column store, and almost never sees user traffic directly.
Playlists.
- 250,000 reads per second at peak, mostly for the same popular playlists. Serving by snapshot ID through caches cuts the store load to maybe 20,000–30,000 reads per second.
- 6,000 writes per second at peak with a write amplification of about 3 (header, entries, operation log) ≈ 18,000 row writes per second. A wide-column cluster of 30–60 nodes per region handles this comfortably, with room for the 8 TB × 3 replicas of data (24 TB) at 1 TB per node or less.
Search.
- 250,000 queries per second at peak, with about 60% served by the CDN or query cache. That leaves 100,000 per second for the search cluster.
- The index holds about 130 M documents (tracks, albums, artists, playlists, podcasts). At about 1 KB each with edge n-grams, the index is roughly 150–300 GB. That fits in memory on a few nodes, so search is sized by query throughput: at about 2,000 QPS per node for short queries, about 50 nodes per region, organised as several replicas of a few shards.
Event pipeline.
- 1.4 million events per second at peak, about 500 bytes each compressed in batches ≈ 700 MB/s into the gateways, or about 60 TB a day.
- A Kafka-style cluster or managed pub/sub at that rate needs a few dozen brokers per region, at about 50–100 MB/s each with replication.
- The data lake grows by 60 TB a day before columnar compression (perhaps 10–15 TB after). A year of raw events is a few PB, which is why old raw events move to colder tiers and older periods are kept only as aggregates (see Data Lifecycle, Tiering and Retention).
Batch compute.
- The monthly royalty close reads about 360 B plays (12 B a day × 30), sessionises them, scores fraud, and aggregates by ISRC and market. On a cluster that scans 1–2 GB/s per hundred cores, a full pass over about 400 TB of compressed events finishes in several hours on a few thousand cores.
- Weekly personalised playlists for 300 M+ users with ANN retrieval and ranking take a large but bounded job: at 1 ms of CPU per user for retrieval and 5 ms for ranking, about 500,000 core-seconds, or a couple of hours on a thousand cores. Model training is usually the bigger bill.
Device caches.
- Each device keeps a streaming cache of perhaps 1–10 GB plus downloads. With 300 M daily devices, the aggregate device cache is over 1 EB, much larger than the whole CDN. That is why a 35% device-served share is plausible, and why changing cache policies on clients is one of the biggest cost levers.
Deep Dive: real-world systems comparedShow
Public details about these services vary. What follows sticks to well-known product facts and general architecture, and hedges where details are not public.
| Service | Notable product choices | Architecture notes (public or widely reported) |
|---|---|---|
| Spotify | Free tier with ads plus Premium; Ogg Vorbis and AAC streams, with lossless for Premium in many markets; Connect for multi-device control; heavy personalisation (weekly discovery playlists, daily mixes) | Early desktop clients used a peer-to-peer network alongside servers, which was phased out around 2014. Event delivery moved from Kafka 0.7 on its own data centres to Google Cloud Pub/Sub and Dataflow. Cassandra was widely used for user data. Open-sourced Luigi (batch workflows) and Annoy and Voyager (nearest-neighbour search). |
| Apple Music | Subscription only; AAC streams with lossless (ALAC) and spatial audio (Dolby Atmos) at no extra cost | Integrated with the iTunes catalogue and device ecosystem; the library is shared with users' own uploaded or matched music, which adds a large user-content matching problem. |
| YouTube Music | Shares a catalogue with YouTube, so official tracks, music videos, live versions and user uploads live together | Has to switch between audio-only and video renditions of the same song, and inherits YouTube's video delivery stack and Content ID-style matching. |
| Deezer | Offered lossless early; publicly backed an artist-centric royalty model with partners in 2023 | Shows that payout models are a product choice as well as a data-engineering one. |
| Tidal | Positioned around high-fidelity audio (lossless and hi-res FLAC) | Larger files per stream shift the cost balance towards bandwidth and edge storage. |
| SoundCloud | Mostly creator uploads, with comments on the waveform and reposts | A very long tail of rarely played tracks makes cache hit ratios lower and storage tiering more important; moderation and copyright matching happen at upload time. |
What the comparison teaches.
- The catalogue source changes everything. Licensed catalogues (Spotify, Apple Music, Tidal) need DDEX ingestion, rights windows and label reporting. Upload-heavy services (SoundCloud, YouTube) need content matching, moderation and a long-tail storage strategy.
- Fidelity is a cost decision. Lossless streams are about 6× larger than 160 kbps lossy streams. Offering them to everyone raises egress costs sharply, and the device cache share matters even more.
- The free tier shapes the architecture. An ad-supported tier needs ad decisions, impression counting, stricter fraud detection, and server-side limits on features.
- Payout models are system requirements. Pro-rata, user-centric and artist-centric models need different pipelines and data retention, and each would change the monthly close.
Deep Dive: a 45-minute interview planShow
| Minutes | What to do | What to say or draw |
|---|---|---|
| 0–5 | Clarify scope | Streaming of licensed music, playlists, search, offline; free and Premium; global. Confirm recommendations and royalties are in scope or "mention only". |
| 5–10 | Requirements and estimates | 300 M DAU, 50 M peak concurrent streams, 330,000 play starts per second, about 5 Tbps peak egress, 10 PB of audio, catalogue metadata under 1 TB. Conclude: bandwidth and latency dominate; metadata is small and cacheable. |
| 10–15 | APIs and entities | Resolve (track → URLs, key, rendition), playlists with snapshot IDs, search, events. Track, AudioFile, Availability, Playlist, Entry, Play. |
| 15–25 | High-level design | Two planes: control (gateway, catalogue, rights, playlists, search, users) and data (object storage, shield, CDN, device cache). Ingestion and encoding pipeline on the side. Event pipeline to the lake. |
| 25–40 | Two or three deep dives | Instant playback (latency budget, burst, prefetch, caches); playlists (ordering, versioning, collaboration); counting and royalties (30-second rule, dedupe, streamshare). Pick what the interviewer leans towards. |
| 40–45 | Failures and evolution | Release-day pre-warm, multi-CDN, degrade recommendations first, offline fallback; what you would build next. |
Common mistakes.
- Spending ten minutes on audio codecs and never reaching the system. One sentence on the bitrate ladder is enough unless asked.
- Streaming audio through the application servers. Audio goes from the CDN to the client; servers only hand out URLs and keys.
- Designing the play counter as a database row incremented on every play. At 330,000 plays a second that is a hot-row disaster; counts come from the event pipeline.
- Forgetting rights. "Is this track playable for this user in this country now?" is checked on every play.
- Treating offline as "just download the file". Licences, expiry, device limits and delayed play reporting are the real design.
Deep Dive: follow-up questions and strong answersShow
How do you make playback start in under 300 ms? Combine the resolve call (rights, file choice, key, CDN URLs) into one round trip from a nearby region. Download the first few seconds at a lower rendition in a burst, with the CDN already holding the file. Most plays are cached on the device or prefetched as "next track", so the true cold start applies to a minority of plays.
A huge artist drops an album at midnight. What breaks? Cold caches and a thundering herd on the origin, plus spikes in catalogue and search reads. Use the release schedule to pre-warm the CDN and shields, collapse identical requests at the shield, pre-load metadata caches, and scale search and playlist reads in advance. Keep the release hidden by rights windows until the exact time, and make sure every region's rights snapshot flips correctly.
How would you count plays exactly once? Clients attach event IDs and buffer events; the pipeline is at least once and removes duplicates by event ID in the stream processor (approximately) and in the batch close (exactly). A play becomes a stream at 30 seconds of listening. Offline plays are counted when they arrive.
Two people edit a shared playlist at the same time. What happens? Each sends an operation against the snapshot it saw. The server applies operations in order, rebasing operations from older snapshots: adds always survive; a move of a track the other person deleted becomes a no-op. Fractional ordering keys mean an insert does not rewrite other rows. Both clients then receive the new snapshot.
How do you stop someone from copying downloaded music? You cannot stop a determined attacker with a rooted device, but you can make copying hard and limited: encrypted files, content keys wrapped per device, keys in hardware-backed storage where available, licences that expire if the device does not check in within 30 days, and a limit on the number of devices with downloads.
How would you design the weekly discovery playlist? Embeddings from collaborative filtering on implicit feedback plus playlist co-occurrence and audio models for new tracks; candidates by nearest-neighbour search; filter out anything already heard; rank by predicted stream and save; re-rank for diversity. Run as a sharded batch job over the weekend and fall back to last week's playlist on failure.
How would you move from pro-rata to user-centric payouts? Keep per-user listening for each month (or at least per-user per-rights-holder aggregates), join with each user's net payment, and split per user. Run both models in parallel for several months to compare, because the change moves money between artists and must be explained and agreed with licensors.
What would you monitor? Time to first audio and stutter rate by country, network and client version; playback error rates by cause; CDN hit ratios by tier; search success; event pipeline lag and completeness for closed hours; and reconciliation of royalty totals.
Deep Dive: the peer-to-peer era and what replaced itShow
Spotify's early desktop client, from its 2008 launch, did not get all music from servers. A desktop user could play from three sources: a cached file on the computer, a Spotify server, or other subscribers through a peer-to-peer (P2P) network. Spotify stopped this in April 2014, saying it could now deliver music through its growing number of servers.
How a streaming P2P design works. It is different from file-sharing networks like BitTorrent, because playback must start immediately and play in order:
- Start from the server, then switch to peers. The first part of a track comes from a server, for a fast start. While it plays, the client looks for peers that hold the rest of the track and downloads ahead of the playhead from them.
- Fall back to the server near the deadline. If peers are slow and the buffer drops below a safety margin, the client fetches from the server again. Playback never waits for a peer.
- Peers are found through a tracker and neighbours. A server-side tracker remembers which clients have recently cached which tracks, and clients also ask the peers they are already connected to.
- The cache is the peer store. Clients served from their local cache, which already existed for repeat listening. No separate "seeding" was needed.
Gunnar Kreitz and Fredrik Niemelä described this design in "Spotify – Large Scale, Low Latency, P2P Music-on-Demand Streaming" (IEEE P2P, 2010). They reported that most data came from local caches and peers, with only a small share from Spotify's servers, and a median playback start of a few hundred milliseconds. Exact percentages are left out here because the paper could not be re-checked.
Why it made sense in 2008.
- Bandwidth from data centres was much more expensive per GB than it is today, and CDN edges inside ISP networks were less common.
- The catalogue was small, so popular tracks had many peers.
- Desktop computers had always-on connections, spare upload capacity and large disks.
Why it went away.
- Mobile took over. Phones on cellular data should not upload to strangers: it drains the battery and uses the user's data plan. A mobile-heavy user base cannot be a good peer network.
- Bandwidth got cheaper and CDNs got closer to users, so the savings shrank.
- Operational simplicity. P2P adds NAT traversal, abuse handling, privacy concerns (peers learn each other's IP addresses and what they play) and hard-to-debug performance.
The lesson for system design. The best architecture depends on cost curves and on what users' devices are like, and both change. Spotify's main idea survived the switch: the device cache is the first and biggest tier, and most plays should never need the network. Today's design (device cache, CDN, shield, object storage) is the same layered idea with peers removed.
Deep Dive: per-user listening history and year-end summariesShow
Several features need each user's own history: "recently played", "jump back in", the filter that removes already-heard tracks from discovery playlists, and the year-end summary. They need it in very different shapes.
| Need | Shape | Freshness | Store |
|---|---|---|---|
| Recently played (last 50 items) | Small list per user | Seconds | Wide-column row per user, capped list, written by the stream processor |
| Heard-before filter | Set of track IDs per user | Hours to a day | Bloom filter or sorted ID list per user, rebuilt in batch |
| Taste profile for ranking | Aggregates (top artists and genres over 4 weeks, 6 months, all time) | Daily | Feature store keyed by user |
| Year-end summary | Counts and rankings over 11–12 months | Once a year | Batch job over the lake, results in a key-value store |
| Data export on request (privacy law) | Every event for one user | Days | Batch extraction from the lake |
The hard case: one user's raw history from a lake partitioned by time. The lake is laid out by hour, which is perfect for jobs that scan everything (royalties, training) and terrible for "give me everything user u did". A naive query reads every hourly file for a year, about 8,760 partitions, each with many files.
Ways to make it cheap, in order of effort:
- Bucket by user within each partition. Write each hour's events into, say, 1,024 files by hash of user ID, sorted by user. A lookup then reads one file per hour rather than all of them. That cuts the files read by about 1,000×, but still touches thousands of hours.
- Add a Bloom filter per file on user ID (table formats such as Parquet support this). A reader can skip files that certainly do not contain the user. For a light listener active on 20 days of the year, almost all hours are skipped after checking a small filter.
- Build a per-user index. A batch job writes an index from user ID to the (file, offset) locations of that user's rows. A lookup becomes a key-value read plus a few targeted range reads from object storage.
- Materialise per-user aggregates. For most features, the raw events are not needed at all: daily per-user, per-track play counts are about 100× smaller than raw events and can be rolled up into weekly and monthly tables.
The year-end summary as a batch problem. It is computed once for hundreds of millions of users, then served for a few weeks with a huge launch-day spike.
- Use the daily per-user, per-track aggregates (step 4), not raw events. For 300 M users with perhaps 500 distinct tracks each a year, that is about 150 B rows, a few TB compressed.
- Group by user and compute top tracks, artists, genres and minutes listened. This is one big shuffle by user ID, which a cluster handles in hours.
- Write the results to a key-value store keyed by user (a few KB each, about 1 TB total), and pre-render shareable images in the background.
- The launch spike is a pure read workload of precomputed values, so caches and a horizontally scaled read service handle it. The risk is not the store but the dependencies the summary pages call (catalogue images, artist pages), which must be cached too.
Privacy and retention. Per-user history is personal data. Keep raw events for a limited period, keep aggregates longer, honour deletion requests by deleting from the serving stores and rewriting or tombstoning lake files, and keep access to raw history behind strict controls. See Data Lifecycle, Tiering and Retention.
Key Takeaways#
- Two planes. A small, highly cached control plane (catalogue, rights, playlists, search) hands out URLs and keys. A huge data plane (object storage, shields, CDN and device caches) moves the bytes. Audio never goes through application servers.
- Bandwidth is the cost, latency is the experience. About 5 Tbps at peak is the main bill. Popular tracks dominate (Zipf), so every cache tier, especially the device, saves real money.
- Instant playback is engineered. One resolve round trip, burst downloads of the first seconds, prefetching the next track, and caches at every level give a start time of a few hundred ms or less.
- Encode once, serve many. A bitrate ladder (from 24 kbps to lossless), loudness metadata and gapless information are made at ingestion, with content-addressed files and backfills for new codecs.
- The catalogue is a rights problem. DDEX deliveries, identifiers (ISRC, UPC, ISWC), windows per market and takedowns compile into fast lookups checked on every play.
- Playlists are versioned documents. Snapshot IDs, operations with rebasing, and fractional ordering keys make collaboration and offline edits safe.
- Offline is licensing. Encrypted files, keys per device and licences that expire after 30 days without a check-in protect content while keeping downloads usable.
- Events are the source of truth. Deduplicated, schema-checked events in hourly partitions feed counts, recommendations, experiments and royalties. Hand them over durably and close to the client, and separate them by type.
- A stream is a business rule. 30 seconds of listening, offline plays counted on reconnect, fraud removed, a 1,000-stream and unique-listener threshold, streamshare per market, and an auditable ledger with frozen inputs.
- Recommendations drive listening. Implicit-feedback collaborative filtering, co-occurrence and audio embeddings, nearest-neighbour candidates, ranking and diversity, built in batch and refreshed in real time.
- Decide what may fail. Playback must survive; recommendations and social features can degrade; counts and royalties can be late but must never be wrong.