AI System DesignRecommendation and Ranking SystemsPersonalized Music Recommendation
How to Design Spotify’s Discover Weekly Recommendation System
Question 2 of 47 · Updated
On this page
- 1. Clarify the product and requirements
- 2. Capacity planning
- 3. High-level architecture
- 4. Collect and prepare trustworthy interaction data
- 5. Candidate generation: retrieve hundreds, not millions
- 6. Ranking: predict discovery satisfaction
- 7. Reranking: relevance is necessary but insufficient
- 8. Practical implementation: constrained playlist selection
- 9. Weekly generation and storage
- 10. Online serving and failure handling
- 11. Evaluate quality before and after launch
- 12. Cold start, feedback loops and operational governance
- 13. Scalability, cost and trade-offs
- 14. Common interview mistakes
- 15. Interview-ready answer
- References and research transparency
A Discover Weekly-style recommendation system is a personalized, periodically generated playlist that retrieves promising tracks from a large catalog, ranks them for each listener, and applies discovery, diversity and eligibility constraints before publishing an immutable weekly playlist. Rather than running an expensive full-catalog recommendation query whenever the listener opens the app, I would precompute most of the playlist asynchronously and serve the result through a low-latency read API.
The original interview problem asks: How would you build a machine learning system to generate Spotify’s Discover Weekly playlist?
This is a proposed interview architecture, not a claim about Spotify's private production implementation. All workload figures and objectives below are illustrative design assumptions, not Spotify traffic, benchmarks or product guarantees.
1. Clarify the product and requirements#
The product is not simply a list of the 30 tracks a listener is most likely to play. Its purpose is discovery: find relevant tracks that the listener has not heard much, maintain variety, and encourage meaningful listening over multiple weeks.
Functional requirements
- Generate a personalized ordered playlist once per weekly release cycle for each eligible, opted-in listener.
- Retrieve tracks from a large, changing catalog using listening history, explicit preferences and content similarity.
- Prefer novel tracks while respecting blocked artists, market licensing, account restrictions and explicit-content settings.
- Support new users with limited history and new tracks without interaction data.
- Publish an atomic, versioned playlist; serve it to mobile and web clients without waiting for inference.
- Collect impression and listening feedback for future training and evaluation.
- Recheck track availability when serving or playing a previously generated playlist.
Non-functional requirements (illustrative)
| Requirement | Proposed interview target |
|---|---|
| Weekly output | Up to 30 playable tracks per eligible listener |
| Generation | Complete the cohort within a 24-hour batch window |
| Read latency | p95 below 100 ms within the service boundary; validate with load tests |
| Read availability | 99.9% monthly service SLO as a starting point |
| Freshness | Use a documented event watermark and current catalog eligibility snapshot |
| Consistency | Readers see a complete playlist version, never a partially written one |
| Privacy | Minimize retained behavioral data, enforce deletion and preference controls |
Clarify whether a listener can see previous versions, what counts as already known, whether the batch should be globally synchronized or staggered by region, and whether explicit opt-outs prohibit all personalized processing. These answers affect storage, scheduling and ranking.
2. Capacity planning#
Assume 100 million eligible listeners, 50 million catalog tracks, 500 candidates per listener after retrieval and a 30-track final playlist. Assume 2,000 million listening-related events per day, a 24-hour generation window, and 1 KB per raw event before compression.
- Average ingestion: 2,000,000,000 / 86,400 = approximately 23,148 events/second. If peak traffic is three times the average, provision for about 69,445 events/second plus replay and failure headroom.
- Raw event payload: approximately 2 TB/day or 60 TB/30 days before compression, replication, indexing and metadata.
- Playlist output: 100 million × 30 = 3 billion track positions per week. At 8 bytes per encoded track ID, bare identifiers alone occupy about 24 GB; actual storage includes playlist keys, serialization, metadata, replication and old versions.
- Required generation throughput: 100 million / 86,400 = approximately 1,158 users/second.
- Candidate scoring volume: 100 million × 500 = 50 billion scores per week, or about 578,704 scores/second across workers over the 24-hour window.
- A 128-dimensional float32 track embedding uses 512 bytes. For 50 million tracks, the raw vector matrix is 25.6 GB, excluding ANN index structures, IDs, copies and allocator overhead.
- Exhaustively scoring every track for every listener would require 5 quadrillion user-track pairs per weekly cycle. Candidate retrieval reduces this drastically.
These are capacity equations, not performance measurements. Benchmark candidate retrieval and ranker throughput with production-like vector distributions, batch size, hardware and network conditions. If a worker sustains 100 users/second at the required latency and quality, 12 workers provide the theoretical minimum for 1,158 users/second; provision additional capacity for stragglers, retries, regional variation and maintenance.
3. High-level architecture#
Separate data ingestion, model training, weekly generation and online serving. They have different freshness and reliability requirements.
DATA AND TRAINING
Listening clients / playback services
|
v
Event gateway -> Durable event log -> Stream validation / dedup
|
v
Object store / lake
|
Point-in-time features + labels
|
+------------------------+---------------------+
| | |
Collaborative model Content encoder Ranker training
| | |
+-------------> Model registry <---------------+
|
Versioned embeddings + ANN index
WEEKLY GENERATION
Scheduler -> User shards -> Candidate retrieval
|
Union / deduplicate / filter
|
Batch feature join + ranker
|
Diversity / novelty / policy checks
|
Versioned playlist store
|
Validate -> publish active version
ONLINE SERVING
Client -> Authenticated playlist API -> Cache / playlist store
|
Current catalog eligibility
|
Ordered playlist
Feedback -> Event log -> Evaluation / next generation cycleThe online request path does not depend on training, nearest-neighbor retrieval or the batch ranker. The batch pipeline can be retried independently while the API continues serving a previously committed valid version.
4. Collect and prepare trustworthy interaction data#
A minimal event contract includes event_id, pseudonymous listener_id, track_id, event_type, event_time, ingestion_time, session_id, impression_id, playlist_version, playback_position and context such as surface or device category. Separate account identity from recommendation identifiers.
Useful behavioral signals include intentional saves, repeated listens, follows, meaningful playback duration, explicit likes and dislikes, skips, and impressions. A skip is ambiguous: interruption, connectivity failure or accidental playback is different from rejection. Distinguish short skips, long listens and incomplete sessions rather than treating every incomplete play as negative.
Capture impressions even when no click or play occurs. Without exposure data, an unplayed song may be unknown rather than disliked, and training on only successful plays creates selection bias.
The data pipeline should:
- Validate schemas and discard malformed or unauthorized events into a controlled quarantine.
- Deduplicate using stable event IDs and retain both event-time and processing-time fields.
- Partition the event lake by date and optionally region; avoid millions of tiny user-level files.
- Build point-in-time aggregates with time windows such as 7, 28 and 90 days.
- Track late-event watermarks and use a reproducible weekly snapshot.
- Exclude events generated after the feature cutoff from training features.
- Apply consent changes, deletion tombstones and catalog removals to derived data.
For example, to train on a weekly playlist published at time T, construct user and track features strictly from data available before T; derive labels from impressions and interactions after T over a fixed outcome window. Do not include a future save count, future popularity rank or future listening history in the features.
Store feature definitions and versions with the model artifact. This reduces training-serving skew and makes an unexpected playlist reproducible.
5. Candidate generation: retrieve hundreds, not millions#
Use several complementary retrieval sources so the system is not limited to a single notion of similarity.
Collaborative filtering. Factorize the sparse user-track interaction matrix with implicit feedback. The model learns user and track vectors from co-consumption patterns. For weighted alternating least squares, define as a binary preference indicator and = 1 + alpha × as a confidence weight derived from non-negative interaction strength. Optimize the weighted squared reconstruction error plus regularization. A zero interaction is low-confidence missing evidence, not proof that a user dislikes a track. Bayesian Personalized Ranking (BPR) offers an alternative pairwise objective that encourages observed positives to score above sampled alternatives.
Content-based retrieval. Generate track embeddings from permitted audio features, genre, artist and text metadata. Build a user taste representation from a recency-weighted collection of positive listening signals. Content retrieval is particularly useful for new catalog tracks with no collaborative history. Audio similarity does not guarantee preference, so it remains one source rather than the only ranking signal.
Two-tower retrieval. At larger scale, train separate encoders for users and tracks into a common vector space. Train with positives and sampled negatives, accounting for popularity and exposure bias. Precompute track vectors; compute user vectors in batch. Use dot-product or cosine similarity consistently with training and index configuration.
Additional candidate sources. Artist and genre exploration, editorial pools, co-listening neighbors and region-appropriate popular discoveries can fill gaps. Retrieve from multiple sources with explicit quotas, deduplicate canonical track IDs, and preserve source indicators for the ranker. Quotas are tunable; for example, retrieve 250 collaborative, 200 content-based and 100 exploration candidates, then deduplicate and truncate or replenish to roughly 500.
An approximate nearest-neighbor (ANN) index makes top-K search practical without scoring all tracks. HNSW offers a graph-based approach with a memory/recall/latency trade-off; IVF with product quantization can reduce memory at the expense of approximation error. Exact inner-product search over a representative subset provides a useful ANN recall baseline.
Measure ANN recall@K against exact search, candidate coverage, catalog freshness, index build time and end-to-end quality. A fast index with poor candidate recall cannot be repaired by even an excellent ranker.
Use version-matched user embeddings, item embeddings and index artifacts. If the encoder changes embedding spaces, rebuild the index before switching. Avoid querying a new user vector against an incompatible old track space.
6. Ranking: predict discovery satisfaction#
Retrieval maximizes recall; ranking estimates how valuable each candidate is for a particular listener. Start with a simple linear or gradient-boosted model. Add a neural or multi-task ranker only when measured gains justify its inference cost and maintenance complexity.
Feature families include:
- User-track affinity: collaborative similarity, content similarity, recent genre interest and artist familiarity.
- Track context: catalog age, popularity trajectory, language and metadata completeness.
- Listener behavior: listening recency, preference diversity, recent repeated tracks and negative signals.
- Candidate source: retrieval channel and position within that channel.
- Discovery context: prior impressions, prior meaningful plays, artist exposure and market availability.
Possible supervised targets include meaningful playback, save or playlist addition, explicit positive feedback and short skips. Define label windows in advance. For example, a save within seven days is a delayed signal; a completed evaluation dataset must wait for that window to mature.
A conceptual utility can combine calibrated probabilities:
utility = 0.45 * P(meaningful play)
+ 0.30 * P(save)
+ 0.15 * P(repeat within evaluation window)
- 0.25 * P(early skip)
+ 0.10 * novelty_scoreThese are illustrative coefficients, not empirically established weights. The targets overlap, so utility is not a probability. Calibrate outputs per relevant cohort and tune the objective with offline evaluation and experiments. Do not reward raw listening time without considering user satisfaction, repeated exposure and the discovery goal.
Train on logged exposure with temporal splits. In a logged ranking dataset, the previous policy determines which songs were shown. A new model cannot reliably infer reactions to all unseen tracks from these data alone. Use carefully controlled exploration, randomized exposure where appropriate, and propensity-aware evaluation when the logging policy and statistical assumptions support it.
7. Reranking: relevance is necessary but insufficient#
A top-30 relevance ranking can contain 12 songs by the same artist and many tracks the listener already knows. A playlist should operate as a set with sequence-level constraints.
First enforce hard constraints: track availability for the listener's market, blocked artists, explicit settings, valid catalog IDs, and duplicate recording removal. Recheck mutable restrictions at serving time. For strict discovery, exclude previously heard recordings; a real product may instead define a configurable familiarity threshold.
Then optimize soft constraints such as genre and artist diversity, exploration, novelty and sequencing. A simple greedy approach picks the highest-scored eligible candidate while enforcing an artist cap. A more expressive option is maximal marginal relevance (MMR):
MMR(i) = lambda * relevance(i)
- (1 - lambda) * max similarity(i, selected_track)Choose the highest MMR score among eligible tracks at each step. Relevance and similarity must use compatible numerical scales. If the selected list is empty, define the redundancy term as zero. Smaller lambda generally increases diversity but can reduce relevance; validate it against listening satisfaction.
Use a ranked reserve pool to refill when tracks become unavailable. When a hard constraint leaves fewer than 30 candidates, return a shorter valid playlist or retrieve more eligible candidates. Never violate consent, licensing or blocked-artist constraints merely to hit a length target. Consider a soft artist cap relaxation only if product policy permits it, and measure its impact separately.
8. Practical implementation: constrained playlist selection#
This small, executable Python example represents the post-ranker selection stage. Inputs are (track ID, artist ID, score, playable), where scores have already been computed. The example deliberately uses a simple greedy policy rather than claiming to implement the full production ranker.
PYTHONfrom collections import Counter def select_playlist(candidates, heard, k=3, artist_cap=1): if k < 0 or artist_cap < 1: raise ValueError("Invalid limits") if k == 0: return [] selected = [] artists = Counter() seen = set(heard) for track, artist, score, playable in sorted( candidates, key=lambda x: (-x[2], x[0]) ): if not playable or track in seen or artists[artist] >= artist_cap: continue selected.append(track) seen.add(track) artists[artist] += 1 if len(selected) == k: break return selected c = [ ("a", "X", .99, True), ("b", "X", .95, True), ("c", "Y", .91, False), ("d", "Y", .85, True), ("e", "Z", .80, True), ("f", "W", .70, True), ("d", "Y", .84, True), ] assert select_playlist(c, {"a"}) == ["b", "d", "e"] assert select_playlist(c, {"a"}, k=2) == ["b", "d"] assert select_playlist(c, {"a", "b", "d", "e", "f"}) == [] assert select_playlist( [("a", "X", .9, True), ("b", "X", .8, True)], set() ) == ["a"] assert select_playlist( [("z", "A", .5, True), ("a", "B", .5, True)], set() ) == ["a", "z"] assert select_playlist(c, set(), k=0) == [] try: select_playlist(c, set(), artist_cap=0) except ValueError: pass else: raise AssertionError("invalid cap accepted") print("7 tests passed")
Expected output: 7 tests passed. These assertions were executed locally successfully. The tests cover novelty exclusion, availability, duplicate handling, artist diversity, deterministic tie-breaking, zero-length output and invalid limits. They do not establish production ranking quality. The sorting cost is O(C log C) for C candidates, with O(C + H) auxiliary space including a copied heard set of size H. In production, a preordered ranker output avoids sorting again, and a bounded history or exact membership service avoids copying huge listening histories per request. Canonical track IDs and multi-artist rules require additional catalog logic.
9. Weekly generation and storage#
Use an orchestrator to register a generation ID, fixed event watermark, catalog snapshot, feature versions and model versions. Divide users into deterministic shards, for example by hash(listener_id) modulo shard_count. Each worker retrieves candidates, joins features, scores, reranks and writes a staged playlist version. Use separate worker pools for retrieval-heavy and inference-heavy stages if their resource requirements differ.
A practical data model:
| Entity | Key | Important fields |
|---|---|---|
| generation_run | generation_id | week, watermark, model_version, catalog_version, status |
| playlist_version | listener_id, week_id, revision | ordered_track_ids, reserve_ids, generated_at, model_version |
| active_playlist | listener_id | active_version, published_at |
| impression_event | event_id | playlist_version, track_id, position, event_time |
A relational store with appropriate partitioning may be adequate at smaller scale. At large scale, a distributed key-value store is attractive for playlist reads by listener ID. Store the ordered IDs as one bounded playlist record to make atomic reads straightforward. Keep detailed generation lineage separately and limit retained versions.
Use an idempotency key (listener_id, week_id, generation_id) and conditional writes to prevent duplicate retries or stale worker output replacing a newer generation. A worker acknowledges a shard only after successful durable writes. Validate coverage, output length distribution, constraint violations, model version consistency and representative quality checks before publishing.
For each user, atomically switch the active pointer only after that playlist version is complete and validated. Cohort-level activation may be staggered by region. If all listeners must switch at a single boundary, use a generation manifest and a versioned read strategy; avoid assuming distributed transactions across 100 million records are practical.
10. Online serving and failure handling#
Example API: GET /v1/me/discover-weekly. Authenticate the requester, derive the listener ID from the session, check personalization settings, fetch the active version and hydrate its track IDs with current catalog metadata and eligibility. Return version, generated_at and ordered tracks. A cache key can include listener ID and playlist revision. Do not use a shared public cache for personalized responses.
Versioned records are effectively immutable except for legal/privacy erasure or invalidation requirements. The active pointer can use a shorter TTL and explicit invalidation on publication. Do not allow a stale cache to bypass a current block or restriction. Prefer a batch catalog check over one remote call per track.
| Failure | Response |
|---|---|
| Late or missing events | Use the last complete watermark; alert and quantify freshness |
| Candidate index unavailable | Use compatible last-known-good index or approved fallback pools |
| Ranker timeout | Retry within the batch deadline; use tested fallback ranker if permitted |
| Partial shard failure | Requeue failed shards; preserve active version |
| Track becomes unavailable | Remove it and fill from eligible reserve candidates |
| Playlist store outage | Serve permitted cached version if freshness and restrictions allow |
| No valid personalized result | Offer eligible regional discoveries or a shorter list, respecting opt-out |
| Poor model release | Stop activation and roll back pointers to valid previous versions |
Bound retries with exponential backoff and jitter; use leases, timeouts and a dead-letter workflow for repeatedly failing jobs. Track data and model versions in alerts, not raw listener histories. A previous playlist is a reliability fallback, not permission to ignore current content rights or deletion requests.
11. Evaluate quality before and after launch#
Offline metrics
- Recall@K for relevant held-out tracks in retrieved candidates.
- Precision@K and NDCG@K for ranked relevance with a documented definition of positives.
- Catalog and artist coverage, intra-list diversity and novelty relative to user history.
- Calibration, cohort performance, eligibility violations and candidate-source contribution.
- Batch completion time, playlist coverage and scoring throughput.
For NDCG, discounted cumulative gain rewards placing highly relevant tracks earlier. Normalize by the ideal achievable ordering for that example. Document treatment of users with no positive labels. Offline interaction metrics cannot directly measure the appeal of every previously unexposed song; use time-based splits and interpret selection bias.
Online metrics
Primary metrics could be saves per exposed listener or meaningful new-track listening per exposed listener. Secondary metrics include playlist completion, repeat listening and subsequent-week return. Guardrails include short-skip rate, hides/dislikes, artist concentration, opt-outs, unavailable-track rate, latency and system cost.
Randomize consistently at listener level to prevent the same listener seeing competing policies on multiple devices. Use intent-to-treat analysis for eligible randomized listeners, check sample-ratio mismatch, predefine metric windows and minimum detectable effects, and observe multiple release cycles if needed. Avoid stopping experiments merely when an early metric looks positive. Exposure-based metrics can be useful diagnostics but conditioning only on users who opened the playlist can introduce bias.
Monitor segments such as cold-start users, market, listening-history length, and catalog coverage. Do not assume aggregate improvement means every cohort improved.
12. Cold start, feedback loops and operational governance#
For a new listener, ask for optional favorite artists or genres, use consented early interactions, and offer a diverse regional catalog fallback. As meaningful behavior accumulates, progressively blend personalized retrieval. For new tracks, content embeddings and bounded exploration help overcome missing interaction history.
Popularity can become self-reinforcing: exposure causes plays, which cause more exposure. Counter it with exploration quotas, source diversity, propensity-aware learning where valid, and coverage dashboards. Avoid forcing equal exposure regardless of relevance. Track long-tail discovery alongside satisfaction.
Build alerts around event lag, schema changes, feature null rates, embedding drift, index recall, queue depth, shard completion percentiles, inference errors, playlist length, policy violations, save/skip trends and cohort regressions. A drift alert is a signal to investigate, not an automatic reason to retrain.
Protect listening data with least-privilege access, encryption in transit and at rest, purpose-limited retention, pseudonymous IDs, audited administrative access and deletion propagation to feature tables, caches and future training sets. Treat music tastes as private behavioral information. Avoid inferring sensitive personal attributes for unrelated targeting. A deletion policy must also define how already trained artifacts and backups are handled under applicable requirements.
13. Scalability, cost and trade-offs#
| Decision | Benefit | Cost or limitation |
|---|---|---|
| Weekly precomputation | Cheap online reads, deterministic release | Batch spikes, stale preferences within a week |
| Real-time full ranking | Immediate adaptation | Higher serving latency and compute cost |
| Hybrid retrieval | Better coverage and cold start | Multiple models, indices and calibration |
| ANN search | Much less candidate computation | Approximate recall and index maintenance |
| Gradient-boosted ranker | Strong baseline, relatively simple serving | Less expressive interaction modeling than some deep rankers |
| Deep multi-task ranker | Can model complex behavior and several objectives | Training, inference, calibration and debugging cost |
| Strict diversity cap | Predictable variety | Can remove relevant tracks or shorten playlists |
Use incremental feature aggregation and reuse item embeddings until they change. Batch ranker requests to amortize overhead; profile GPU versus CPU rather than assuming one is cheaper. Partition work by measured cost, not simply number of users, because heavy histories and large candidate pools create stragglers. Scale workers against remaining deadline and observed throughput. Separate hot playlist reads from training lake scans.
Optimize cost per successfully generated eligible playlist, not merely cost per inference call. Recompute affected cohorts selectively when catalog changes or model quality incidents justify it. Do not promise cost reductions without measurements. Version storage and index copies, inter-region transfer, event retention and exploration overhead should be included in the budget.
14. Common interview mistakes#
- Starting with a deep model before specifying discovery objectives and user constraints.
- Treating every unplayed track as a negative label.
- Randomly splitting time-dependent data and leaking future interactions.
- Scoring the entire catalog for every request.
- Optimizing only clicks, streams or popularity rather than discovery satisfaction.
- Ignoring market licensing, blocked artists and cold start.
- Replacing an active playlist with an incomplete result during batch failure.
- Claiming Spotify's private model, infrastructure or traffic figures as known facts.
15. Interview-ready answer#
I would design this as a weekly personalized retrieval-ranking-reranking pipeline. Listening impressions and interactions flow through a durable event log into a point-in-time feature pipeline. Collaborative filtering captures co-listening patterns, content embeddings support new songs, and ANN retrieval narrows a large catalog to hundreds of candidates. A supervised ranker predicts multiple satisfaction signals, followed by a constraint-aware diversity and novelty stage.
I would shard generation by user, pin the feature and model versions, and store immutable playlists with atomic active-version pointers. The online API would serve precomputed playlists quickly while checking current catalog eligibility. I would handle cold start with optional preferences and content or regional fallback, monitor batch health and recommendation quality, and roll out new rankers through listener-level experiments. The key trade-off is freshness versus inference cost: weekly generation makes the read path reliable and cheap, while bounded feedback and catalog checks preserve relevance and safety.
References and research transparency#
This article uses the explicitly authorized offline research exception. The following established papers, textbooks and official documentation links are supplied as technical references; their current availability and contents could not be live-verified in this session. They support general recommendation, retrieval, diversity, event streaming and evaluation techniques, not assertions about Spotify's current internal systems.
- Hu, Koren & Volinsky (2008) — Collaborative Filtering for Implicit Feedback Datasets
- Rendle et al. — BPR: Bayesian Personalized Ranking from Implicit Feedback
- Google for Developers — Recommendation Systems
- Johnson, Douze & Jégou — Billion-scale similarity search with GPUs
- Carbonell & Goldstein (1998) — The Use of MMR, Diversity-Based Reranking
- Apache Kafka — Documentation
- Kohavi, Tang & Xu — Trustworthy Online Controlled Experiments
References
- 1.
- 2.
- 3.Google for Developers — Recommendation Systemsdevelopers.google.com
- 4.
- 5.
- 6.Apache Kafka — Documentationkafka.apache.org
- 7.
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningMLOpsPython