Design Spotify
Design a music streaming service. Listeners search a catalogue of around 100 million tracks, press play and expect sound within a fraction of a second, skip freely, and build playlists they share with friends. Premium listeners can download playlists to listen on a plane or underground, and the app must stop playing those downloads if the subscription lapses.
Audio files are small compared with video, but listeners skip constantly, so start latency matters more than raw bandwidth. Playlists are edited from several devices and sometimes by several people at once. Every play also has to be counted reliably, because artists are paid from those counts.
In 45 minutes, cover playback, playlists, offline downloads and search, and explain where you would spend your complexity.
Sketch on the HLD board, write your answer in the Design doc, and size it with the Estimator. Start the mock interview from the timer for a 45-minute run.
Design Path · Media & Storage · problem 17 of 70
Ask before you design. Try answering each yourself, then compare.
- What scale are we designing for?
Typical answer
About 250 M daily listeners, 100 M tracks, roughly 40 plays per listener per day.
- Which audio qualities do we serve?
Typical answer
Three lossy bitrates (about 96, 160 and 320 kbps) chosen by settings and network; lossless is a follow-up.
- Can playlists be collaborative?
Typical answer
Yes, some playlists accept edits from several people. Last-second ordering races are acceptable as long as no added track is lost.
- How long can downloads play offline?
Typical answer
Up to 30 days without the app checking in, then playback pauses until it reconnects. Limit downloads to a few devices per account.
- What should search cover?
Typical answer
Tracks, artists, albums, playlists and podcasts, with typo tolerance and results as the user types.
- How accurate must play counts be?
Typical answer
Exact enough for payouts, computed daily; public counts can lag by a day.
Requirements
Functional
- Stream any track with start latency under a few hundred milliseconds and gapless transitions.
- Create, edit, reorder, follow and collaborate on playlists, synced across devices.
- Download playlists and albums for offline playback, with licence expiry.
- Search the catalogue with typeahead and typo tolerance.
- Record plays for royalties and statistics.
Non-functional
- Playback start p95 under 300 ms when online; skip-to-next under 150 ms if prefetched.
- 99.99% availability for playback; 99.9% for playlists and search.
- Search typeahead p99 under 100 ms.
- Play events must be counted at least once and deduplicated: no lost plays.
Out of scope
- Recommendation and radio algorithms.
- Artist upload and catalogue ingestion tools.
- Payments and subscription management (only the 'is premium' check).
Back-of-the-envelope estimates
- Plays: 250 M × 40 ≈ 10 B per day, about 115,000 starts per second and ~300,000 at peak.
- Bandwidth: an average track of 3.5 minutes at 160 kbps is ~4 MB. 10 B plays × 4 MB ≈ 40 PB/day, ~4 Tbps average. Device caching of repeat listens removes a large share of that.
- Catalogue: 100 M tracks × three bitrates ≈ 15 MB per track, so ~1.5 PB, of which the top 1–2 M tracks carry most plays and fit comfortably in CDN caches.
- Playlists: a few billion playlists; edits are ~2 per listener per day (≈ 6,000/s), reads about 100× that.
- Search: roughly 5 queries per listener per day, but typeahead fires per keystroke, so ~100,000 requests/s at peak.
Bandwidth is moderate for a CDN; the design is driven by start latency (prefetch, caching) and by correctness of playlists and play counting.
API
GET /v1/tracks/{id}/stream?quality=160 -> {cdnUrls[], fileKeyToken, expiresAt}
GET /v1/search?q=bohem&types=track,artist -> {tracks[], artists[], albums[]}
GET /v1/playlists/{id}?since=rev -> {rev, tracks[] | ops[]}
POST /v1/playlists/{id}/ops {baseRev, ops[]} -> {rev}
POST /v1/offline/{deviceId}/grants {ids[]} -> {licence, keys[], expiresAt}
POST /v1/plays {events[]} (batched, idempotent by eventId) -> 202Playlist edits are sent as operations against a revision rather than as a whole replacement list, so concurrent edits from different devices can be merged instead of overwriting each other.
Data model
tracks(track_id PK, title, artist_ids, album_id, duration, files{quality: object_key}, regions) in a relational catalogue store, replicated and heavily cached; audio files live in object storage and are immutable and encrypted.
playlists(playlist_id PK, owner, rev, name, collaborative) and playlist_items(playlist_id, position_key, track_id, added_by, added_at) in a wide-column store partitioned by playlist_id; position_key is a sortable fractional key so inserts never renumber the list. An op log per playlist lets devices catch up from their last revision.
device_grants(account_id, device_id, track_ids, expires_at) in a relational store (few writes, needs constraints on device count).
A search index (inverted index plus prefix n-grams) is built from the catalogue; play events go to a durable log, then a warehouse.
High-level design
Playback: when the listener taps a track, the app first checks its local cache. On a miss it calls the playback service through the gateway, which checks entitlement and region, and returns short-lived CDN URLs and a key token. The app fetches the first chunk of the encrypted file from the nearest CDN edge, starts decoding as soon as a few hundred ms are buffered, and fetches the rest in the background. While a track plays, the app prefetches the beginning of the next one or two tracks in the queue, which is why skips feel instant. CDN misses pull from the audio object store.
Playlists: edits go to the playlist service as operations with a base revision. The service applies them in order, assigns a new revision, and stores items and the op log in the playlist store. Other devices pull ops since their last revision when they open the playlist or get a push nudge.
Offline: the offline service records a grant for this device, enforces device limits, and returns a signed licence and wrapped keys; the app downloads encrypted files from the CDN.
Search: the search service queries an index built from catalogue changes. Plays: the app batches play events (including ones logged offline) to the gateway, which appends them to a durable stream for royalties and stats.
Open the HLD board and press Reference to see the architecture diagram.
Deep dives
Making playback start instantly
Latency, not bandwidth, is the enemy. Audio files are encoded so the first chunk can be decoded alone, and the client starts after a fraction of a second of data. Three tricks remove most waiting: a local LRU cache of recently played files (often several GB on a phone), prefetching the first 10–15 seconds of the next tracks in the queue, and keeping a warm connection to the CDN. Track URLs and file keys are fetched for the whole queue at once, so a skip needs no control-plane call. Because files are immutable, edge caches keep popular tracks indefinitely and the long tail falls back to a regional tier and object storage.
Offline downloads and licences
Downloaded files stay encrypted on the device. The offline service issues a licence bound to account, device and expiry date, plus the content keys wrapped for that device. The player refuses to decrypt once the licence expires, so a lapsed subscriber loses access even without a network connection. When the app comes online it renews licences and uploads plays recorded offline with their original timestamps. A per-account limit on devices and downloaded tracks is enforced in a relational table, where a transaction can check the count before inserting a new grant. Revoking a device just deletes its grants; it stops working at the next check-in or expiry.
Playlists edited from many devices
Represent a playlist as items with sortable fractional position keys and an op log: add(track, between a and b), remove(item_id), move(item_id, between a and b). Each op is applied in revision order by the service, which owns one playlist at a time through partitioning by playlist_id. Because ops reference stable item ids rather than indexes, two people adding tracks concurrently both succeed; a remove of an item already removed is a no-op. Clients keep the last revision they saw and fetch only newer ops. Very large playlists (10,000+ items) are paged by position key, and a snapshot is written every few hundred ops so catch-up stays cheap.
Counting plays for payouts
A play counts after about 30 seconds of listening. The client stamps each event with a unique id and sends batches; the gateway appends them to a replicated stream and acknowledges only after the write. Because clients retry, the stream may hold duplicates, so the aggregation job deduplicates by event id within a multi-day window. Offline plays arrive days late, so daily royalty totals are recomputed once late data settles. Public play counts are a cheap by-product of the same pipeline.
Failure modes
- If the playback service is down, cached and downloaded tracks still play, and prefetched URLs for the current queue keep working until they expire.
- If a CDN provider degrades, the playback service returns URLs from a second provider and the client retries the next URL.
- If the search cluster is degraded, serve results from a smaller cached index of popular entities rather than failing.
- If the play-event stream is unavailable, clients keep events on disk and retry with backoff; nothing is lost because events are idempotent.
- If a playlist partition is unavailable, the app shows the locally cached copy read-only and queues edits.
Trade-offs
- Prefetching upcoming tracks makes skips instant but spends mobile data and CDN bandwidth on audio that is never heard.
- Long offline licences (30 days) are convenient for listeners but delay revocation when a subscription ends.
- An op-log playlist model merges concurrent edits safely but is more complex than replacing the whole list, and needs periodic snapshots.
- Deduplicating play events in batch gives exact payouts but means public counts lag by up to a day.
What a strong answer shows
- Identifies start latency, not bandwidth, as the key playback metric and attacks it with client caching and prefetch.
- Designs offline playback with encrypted files and expiring device licences that work without a server.
- Models playlists so concurrent edits from devices or collaborators merge without losing tracks.
- Treats play events as a durable, idempotent pipeline because money depends on it.
- Sizes search for per-keystroke traffic and uses an index built asynchronously from the catalogue.
Mistakes to avoid
- Copying a video design with bitrate ladders and transcoding while ignoring skip latency.
- Storing downloads unencrypted or relying on the server to block expired offline content.
- Saving a playlist as one blob that the last writer replaces, silently losing collaborators' additions.
- Counting plays with a synchronous counter update on each play, or losing offline plays.
- Querying the relational catalogue with LIKE for search.
Follow-ups to expect
- How would you add lossless audio? (A fourth file per track, stricter network checks, mostly larger caches; no new architecture.)
- How would you build 'friends are listening to' activity? (Fan-out of now-playing events over persistent connections, heavily sampled.)
- How would you handle a new album that drops at midnight? (Pre-warm CDN, publish catalogue rows ahead with a release time, pre-build search entries.)
- How would you support podcasts with very long episodes? (Range requests, resume position per episode, different caching policy.)