Skip to content

Design Spotify

A system design interview walkthrough for music streaming like Spotify: catalog search, tiered audio caching, playlists and accurate play counting.

Intermediate22 minUpdated 2 December 2026

Before this: Content Delivery Network (CDN), Caching, Search Systems (Elasticsearch)

"Design Spotify" looks like a smaller version of the video questions, because audio files are small. It is a different problem. A song is 4 MB, not 4 GB, so the bytes are cheap. The hard parts are that demand is extremely skewed toward a few songs, that a song must start instantly when tapped, that a playlist is a list many people can edit, and that every play can be worth money to somebody.

The interviewer is checking whether you adapt what you know about video to a workload with different economics. Do you notice that the whole popular catalog fits in memory-sized caches? Can you model playlist order under concurrent edits? And can you count plays accurately enough to pay royalties, which is a much stricter standard than a view counter?

The delivery layer builds on the CDN lesson, and the catalog search on search systems. For a long-form, adaptive-bitrate cousin of this problem, see Design Netflix.

Clarify the requirements

Functional requirements:

  1. Search the catalog for tracks, albums and artists.
  2. Play a track, with pause, seek, skip and a play queue.
  3. Create playlists, edit them, and share them. Some are collaborative.
  4. Save music to a library, and download playlists for offline listening.
  5. Record plays accurately for the user's history and for artist payments.

Out of scope, said aloud: podcast and video, social features, the recommendation engine (see Design a Recommendation System), payments and subscriptions, rights management logic.

Non-functional requirements: these decide the architecture.

  • Playback starts in under a few hundred milliseconds for a popular track, and gapless transitions are expected.
  • Streaming must survive a poor network. A short buffer and several quality levels let a phone in a tunnel keep playing.
  • Play counts are money. An artist's payment is derived from counted plays, so counting must be deduplicated, auditable and replayable. Eventual is fine. Wrong is not.
  • Playlists are consistent for editors. Two people adding songs to the same playlist should not lose each other's changes.
  • The catalog changes slowly and daily. New releases arrive in bulk, often at midnight on a Friday.

Estimate the scale

Assume 200 million daily active users, each listening to about 25 tracks a day. A track averages 3.5 minutes (210 s) at 160 kbps in the default quality.

Plays: 200M × 25 = 5 billion a day, which is 58,000 per second on average, and about 175,000 per second at peak.

Bytes per track: 160 kbps × 210 s ÷ 8 = 4.2 MB.

Egress: 5B × 4.2 MB = 21 PB a day, which is about 1.9 Tbps averaged over the day. That is a lot less than a video service, and a CDN carries it.

Catalog: assume 100 million tracks, each stored in about four qualities for a total of 15 MB per track: 100M × 15 MB = 1.5 PB.

The head: listening follows a steep curve. Suppose the top 1% of tracks, one million of them, receive most plays. Their audio is 1M × 15 MB = 15 TB, which fits on a handful of servers with SSDs.

Play events: each play produces about three events (start, a 30-second mark, end or skip), so 200M × 75 = 15 billion events a day, about 174,000 per second. At about 200 bytes each, that is 1.1 PB a year of raw events.

"The audio is small and the hot set is 15 TB, so caching works almost perfectly. The data plane is easy compared with video. What is hard is the control and money plane: 174,000 events a second that must be counted exactly once for royalties, and playlists that several people edit at once."

You can reproduce the event rate and the yearly volume in the capacity estimator.

API and data model

GET  /v1/search?q=...&type=track,album,artist
GET  /v1/tracks/{id}/stream-info       -> { audioUrls[quality], expiresAt, key }
GET  <cdn>/audio/{trackId}/{quality}/{chunk}   (data plane)
POST /v1/playlists/{id}/ops   [{ op: add|remove|move, trackId, afterItemId, opId }]
POST /v1/plays   [{ trackId, startTs, playedMs, deviceId, eventId }]
tracks     (track_id PK, album_id, artist_ids[], duration, isrc, rights_regions)
playlists  (playlist_id PK, owner_id, version)
items      (playlist_id PK, item_id CK, track_id, position_key, added_by)
play_events (user_id PK, ts CK, track_id, played_ms, event_id)   + stream to warehouse

The non-obvious choice: a playlist item's order is a position key that sorts as a string (for example a fractional rank between its neighbors), not an integer index. Inserting a track between two others then writes one row, and two concurrent inserts do not renumber the whole list.

High-level design

We simulate the playback path: the app fetches audio from CDN edges, which fall back to a playback service that reads audio from object storage and the catalog from a search cluster. Listening events are published to a stream and consumed by a counting service.

The app streams audio via CDN edges and a playback service backed by S3 and Elasticsearch, with play events flowing through Kafka to a counter.appedge cachesplayback serviceaudio filescatalog searchplay eventscounting service
The app streams audio via CDN edges and a playback service backed by S3 and Elasticsearch, with play events flowing through Kafka to a counter.
  • The CDN serves most audio chunks from the edge and asks the playback service on a miss.
  • Play events go to Kafka, where a counting service tallies them for history and royalties.
Describe this diagram

Components

  • app (Client)
  • edge caches (Content delivery network)
  • playback service (Service)
  • audio files (Object storage (S3))
  • catalog search (Search cluster (Elasticsearch))
  • play events (Kafka)
  • counting service (Service)

Connections

  • app sends to edge caches
  • edge caches sends to playback service
  • playback service sends to audio files
  • playback service sends to catalog search
  • playback service sends to play events
  • play events sends to counting service

Run it, then try shrinking the edge cache or raising the load. Misses reach the origin first, and the catalog index is next.

The play path: the app asks for stream-info, which checks entitlement and returns signed CDN URLs. The app fetches the first chunks, starts playing and pre-fetches the next track while the current one plays.

The counting path: events go to a durable stream and are processed there, never on the playback request.

The interesting problem: serving a skewed catalog instantly

The catalog has 100 million tracks and 1.5 PB of audio, but demand for it is very uneven. The design should exploit that, and also cope with the long tail that is requested rarely and at random.

Approach A: serve every track from object storage

Each play reads the file from S3.

Good: simplest, with one place for all data.

Bad: 58,000 reads a second against storage with first-byte latency in the tens of milliseconds, each from a faraway region. Playback start suffers, egress from storage is priced far above CDN rates, and a release day creates a hot object.

Approach B: cache chunks at CDN edges with long TTLs

Audio files are immutable. Name chunks by content (track/quality/chunk-n), cache them for a long time at the edge, and let the CDN deal with demand.

Good: the head is served from the edge in milliseconds, and the origin sees only misses. Immutability means no invalidation problem.

Bad: the long tail has low hit rates, so each edge would have to hold the whole catalog to avoid origin trips, which is not economical. Every region's first play of a new release misses.

Approach C: tiered caching by popularity, plus prefetch

Treat the catalog in three tiers:

  • Head (about 1% of tracks, most of the plays): held at every edge, pre-loaded when a release is announced. About 15 TB.
  • Torso: held at a regional mid-tier cache that edges fall back to. A miss at the edge becomes a hit one hop away.
  • Tail: read from object storage on demand, then cached with a short TTL.

Add client-side prefetch and a short on-device cache: while a track plays, the app fetches the first 10 to 20 seconds of the next queued track, so the skip is instant and gapless. For an offline playlist, the app downloads the whole files in advance, encrypted with a per-device key.

The recommended answer is C: exploit skew with tiers, immutability for caching and prefetch for latency. State the key number: the hot set is 15 TB, so the head is cheap to replicate everywhere.

The second decision: counting plays for money

A play count that powers a "trending" row can be approximate. One that determines royalties cannot.

Define a play. A play is counted when a track has been played for a minimum duration, such as 30 seconds. Skips under that do not count, which stops accidental plays from creating payments, and it makes the rule a pure function of the event.

Make every event idempotent. The client creates an eventId for each play, and the counting job deduplicates on it. A retried upload, or one replayed from the stream, cannot count twice. Use a stream with at-least-once delivery and make the sink idempotent: this gives effectively-once counts without distributed transactions, as in stream processing.

Keep the raw log. Write every event to durable storage and compute counts from it. If a bug is found, you re-run the job over the log and correct the totals. Counts shown to users are an incremental view, and the payment run reads from the reconciled batch result.

Playlists and concurrent edits

A playlist is a small ordered list that many users read and a few edit. Two collaborators may add tracks at the same time, from phones with a poor connection.

Model each edit as an operation with an ID, such as "add track T after item X". The server applies operations in arrival order and returns the new version. Position keys mean an insert writes one row, and two inserts between the same neighbors stay distinct (ties broken by operation ID). Offline clients replay queued operations with the same IDs, and duplicates are ignored. See consistency patterns for last-writer-wins versus merging.

Bottlenecks and failures

A release-day spike. A huge album drops. If you did not pre-load the edges, every region misses on the same objects at once. Use pre-positioning, plus an origin shield that collapses concurrent misses into one fetch.

Entitlement checks. Every play asks "is this user allowed to listen, in this region, at this quality?". Cache the answer for a short period in Redis keyed by user, and sign the CDN URL with a short expiry so that sharing a URL does not give permanent access.

The event stream falls behind. History and "recently played" lag, but playback is unaffected because events are asynchronous. Alert on consumer lag.

What if the counting service is down? Events accumulate in the stream, and counts catch up when it returns. Nothing is lost, which is the reason to write to a log first.

Trade-offs to name aloud

  • Tiered caching: a small, cheap hot tier and more complexity, in exchange for fast starts on the head and acceptable ones on the tail.
  • Prefetching the next track: instant skips and gapless playback, paid for with a few megabytes of wasted download when the user changes their mind.
  • Real-time versus reconciled counts: two numbers to explain, in exchange for fast displays and accurate payments.

What interviewers listen for

  • A working answer: search over the catalog, audio in object storage behind a CDN, playlists in a database and a play history.
  • A strong answer: quantifies the skew and the 15 TB hot set, uses immutable chunks with long edge TTLs, prefetches the next track, and counts plays through an idempotent stream rather than a row update.
  • A standout answer: also tiers edge, regional and origin caches, pre-positions releases, defines a play precisely, keeps a replayable raw log for royalty correction, models playlist edits as operations with position keys, and handles regional rights.

Check your understanding

Common mistakes

Treating it as a video platform. Audio is small and the head is tiny. The interesting parts are counting, search and playlists, not adaptive bitrate.

Counting plays with a counter column. It cannot be deduplicated, audited or replayed. Keep events and derive counts.

Storing playlist order as an integer index. Inserting in the middle renumbers everything and conflicts with any concurrent edit. Use position keys.

Forgetting prefetch. Without it, every skip waits for the network, and gapless playback is impossible.

Practice

A major artist releases a surprise album at midnight and 8 million listeners press play within 10 minutes. Estimate the load, and say what you would have done in advance.

Write your own answer first, on paper or in a note. Then compare.

Show a hint

Convert listeners into requests per second and compare with what a cold cache and a pre-loaded cache would do.

Show a strong answer

Estimate. 8 million starts in 600 seconds is about 13,000 starts per second, each fetching the first chunk of a track. Spread over, say, 12 popular tracks, that is more than a thousand requests a second for each of the same few objects.

Without preparation, each edge misses once per object, and a thousand concurrent requests on a cold edge all go to the origin at once. Across many edges and regions that is a herd on a few files.

With preparation, the label delivers the album days before. Transcode it to all qualities and push the files to every edge and the regional tier before midnight, so the release is only a metadata change. An origin shield collapses any remaining misses.

The pattern worth keeping: a planned spike should be absorbed by pre-positioning, and a surprise spike by request collapsing.

An artist claims their play count is 4% lower than their own tracking suggests. How does your design let you investigate and fix it?

Write your own answer first, on paper or in a note. Then compare.

Show a hint

Think about what you stored, and how you could recompute the number.

Show a strong answer

Because you kept the raw events, you can recompute. Re-run the counting job over the log for that artist and period, using the same rules, and compare to the stored totals. If they match, the difference is in the definition (for example, the 30-second threshold). If they differ, the real-time view has a bug or lost events.

Look for dropped events. Compare event counts by client version and platform with expected volumes. A client version that fails to send the 30-second mark would undercount exactly one group of users.

Correct the books. Because payments use the reconciled batch, fix the job, re-run it and issue an adjustment. The log is the evidence.

The pattern worth keeping: when a number carries money, keep the immutable inputs, derive the number from them, and make the derivation replayable.

Key takeaways

  • Audio is small and demand is skewed. The hot set is about 15 TB, so edge caching is very effective.
  • Tier the cache: edge for the head, a regional layer for the torso and storage for the tail, with prefetch for instant skips.
  • A play is a precise, idempotent event, and royalty counts come from a replayable log.
  • Model playlists as operations with position keys, not as a replaced list.
  • Check rights and entitlement on the control plane, and sign short-lived URLs.
  • Pre-position planned releases and shield the origin from the rest.

Further reading

  • R. Pantos and W. May, RFC 8216 "HTTP Live Streaming" (2017): chunked delivery of media as plain cacheable files.
  • J. Kreps, N. Narkhede and J. Rao, "Kafka: a Distributed Messaging System for Log Processing", NetDB workshop (2011): the durable log behind replayable play counts.
  • Martin Kleppmann, "Designing Data-Intensive Applications", O'Reilly (2017), the chapters on stream processing and exactly-once effects.

Check yourself

3 questions in this lesson. Answer each once to complete it.

Practice this

Lessons in this track