← Knowledge Base

Spotify

A deep dive into the technology behind the world's largest music streaming platform — from audio encoding to recommendation algorithms.

📖 17 Sections ⏱ 45 min read 📈 Engineering deep dive

1 Digital Audio Basics

How sound waves become the ones and zeros your phone understands

Sound is a pressure wave propagating through a medium (usually air). When a speaker vibrates, it creates compressions and rarefactions in air pressure. Your ear's tympanic membrane translates these oscillations into nerve impulses. Digital audio's job is to capture this continuous, analog phenomenon as a discrete sequence of numbers—and then recreate it faithfully enough that your brain can't tell the difference.

Analog-to-Digital Conversion (Sampling)

Time → Amplitude

Green dots = sample points captured at regular intervals. Orange staircase = quantized digital representation. Smooth curve = original analog signal.

Key Concepts

Sampling Rate determines how many times per second we measure the analog signal. CD-quality audio uses 44,100 Hz (44.1 kHz)—meaning 44,100 snapshots of air pressure every single second. Why 44.1 kHz? The Nyquist-Shannon sampling theorem states that to faithfully reproduce a signal, you must sample at at least twice the highest frequency you want to capture. Human hearing tops out around 20 kHz, so 2 × 20,000 = 40,000 Hz minimum. The extra 4,100 Hz provides headroom for the anti-aliasing filter.

Bit Depth defines the precision of each sample. At 16-bit depth, each sample can be one of 216 = 65,536 possible amplitude values, yielding a theoretical dynamic range of ~96 dB. 24-bit depth (used in studio recording) provides 16,777,216 levels and ~144 dB dynamic range—far exceeding the capabilities of any playback hardware.

PCM (Pulse Code Modulation) is the raw, uncompressed digital audio format. A stereo 44.1 kHz / 16-bit PCM stream requires: 44,100 × 16 × 2 = 1,411,200 bits/second (~1.4 Mbps, or about 10 MB per minute). This is why compression is essential for streaming.

Nyquist Theorem: A bandlimited continuous signal can be perfectly reconstructed from its samples if the sampling rate is at least twice the maximum frequency component. Aliasing occurs when this condition is violated, creating audible artifacts.

2 Audio Codecs

Compressing 1.4 Mbps of raw audio into something your phone can stream over 4G

Audio codecs exploit two fundamental strategies: lossless compression (like ZIP for audio — perfectly reversible) and lossy compression (permanently discarding information the human ear is unlikely to notice). Lossy codecs use a psychoacoustic model — a mathematical model of human hearing — to decide what to throw away.

Psychoacoustic Masking

The psychoacoustic model is the secret weapon of lossy codecs. It exploits two phenomena:

Simultaneous masking: A loud sound at one frequency makes nearby quieter sounds inaudible. If a 1 kHz tone is playing at 80 dB, a 1.1 kHz tone at 40 dB is completely masked — the codec doesn't need to encode it.

Temporal masking: A loud sound makes quieter sounds inaudible for a short time before (pre-masking, ~5ms) and after (post-masking, ~100ms) it occurs. The codec can reduce precision during these masked windows.

By dividing audio into frequency bands and applying masking thresholds, codecs allocate more bits to perceptually important frequencies and fewer (or zero) bits to masked regions. This is why 320 kbps Ogg Vorbis can sound nearly identical to 1,411 kbps PCM—it's only encoding the ~23% of data your ears actually process.

CodecTypeTypical BitrateQualityUsed ByNotes
MP3 (MPEG-1 Layer III)Lossy128–320 kbpsGood at 256+Legacy, podcastsPatented until 2017. Modified DCT.
AAC (Advanced Audio)Lossy128–256 kbpsBetter than MP3 at same bitrateApple Music, YouTubeMore efficient psychoacoustic model.
Ogg VorbisLossy96–320 kbpsExcellentSpotifyOpen source, royalty-free. MDCT-based.
OpusLossy32–512 kbpsBest lossy codecDiscord, WebRTCHybrid: SILK (voice) + CELT (music).
FLACLossless~800–1400 kbpsPerfectTidal, Spotify HiFi~50-60% of PCM size. Fully reversible.

What Spotify Actually Uses

Spotify encodes all music in Ogg Vorbis at multiple quality tiers, selected based on your subscription and settings:

SettingQualityBitrateAvailable To
Low~AM Radio24 kbps (HE-AAC on mobile)Free + Premium
NormalStandard96 kbps (Ogg Vorbis)Free + Premium
HighHigh Quality160 kbps (Ogg Vorbis)Free + Premium
Very HighNear-CD320 kbps (Ogg Vorbis)Premium only

The choice of Ogg Vorbis over MP3 or AAC comes down to licensing: Ogg Vorbis is completely royalty-free and open-source. At 320 kbps, double-blind ABX tests consistently show it is transparent (indistinguishable from the original) for the vast majority of listeners and audio material.

3 Audio Streaming Protocol

Getting audio from datacenter to headphones without interruption

Unlike video streaming, which commonly uses adaptive bitrate protocols like HLS or DASH with manifest files describing multiple quality segments, audio streaming is simpler in some ways (smaller files, lower bandwidth) but more demanding in others (listeners are extremely sensitive to gaps, and gapless playback between tracks is essential for albums).

HTTP-Based Chunked Delivery

Spotify uses a proprietary protocol built on top of HTTP. Each track is divided into small chunks (typically a few seconds each). The client requests chunks via standard HTTP range requests from Spotify's CDN edge servers. This approach works through firewalls and proxies (unlike the UDP-based P2P protocol they used in early years).

The client maintains a playback buffer—typically 3–10 seconds of decoded audio ahead of the current playback position. If the buffer drops below a threshold, the client may switch to a lower bitrate. If bandwidth is abundant, it buffers further ahead. This adaptive bitrate strategy prevents interruptions on variable connections.

CDN Edge
→
HTTP Chunks
→
Network Buffer
→
Decode (Vorbis)
→
PCM Buffer
→
Audio Output

Gapless Playback

Many albums are designed with seamless transitions between tracks (think Pink Floyd's Dark Side of the Moon). Spotify achieves gapless playback by pre-fetching and pre-decoding the next track before the current one ends. The codec metadata includes precise sample counts, allowing the player to trim encoder padding and stitch PCM buffers with sample-level accuracy.

Crossfade

Optional crossfade (0–12 seconds) overlaps the end of one track with the beginning of the next. This requires decoding both tracks simultaneously and mixing their PCM output with complementary fade curves (typically equal-power or linear). The client handles this entirely locally—no server involvement needed.

How Audio Streaming Differs from Video

Video protocols like HLS and DASH are built around manifest files (e.g., m3u8) listing segment URLs at various quality levels. The player downloads the manifest, then requests segments. Audio streaming at Spotify skips this complexity: the access point server tells the client the track's storage key and available bitrates directly. The client fetches chunks from the CDN using that key. Switching quality is seamless because all chunks are independently decodable Ogg pages. There is no need for I-frames or GOP structures like in video.

4 System Architecture Overview

From a single Python monolith in 2006 to 4,000+ microservices on Google Cloud

Spotify's architecture has undergone a dramatic evolution. When Daniel Ek and Martin Lorentzon started the company in 2006 in Stockholm, the backend was a monolithic Python application. As the user base grew from thousands to millions to hundreds of millions, the system was gradually decomposed into what is now one of the largest microservice architectures in the world.

Architecture Evolution

Monolith 2006-2012 SOA + Libraries 2012-2017 Microservices 2017-present GCP + Backstage 2018-present

Microservices at Scale

Today Spotify runs 4,000+ microservices developed by autonomous "squads" (their take on agile teams). The tech stack is polyglot:

  • Java — the backbone, running most backend services
  • Python — data pipelines, ML training, internal tooling
  • Go — performance-critical infrastructure services
  • C / C++ — native client codecs, audio processing
  • TypeScript / React — web player, internal dashboards

In 2018, Spotify migrated from self-managed datacenters to Google Cloud Platform (GCP), one of the largest cloud migrations in history. They now use GKE (Google Kubernetes Engine) for container orchestration, BigQuery for analytics, Cloud Pub/Sub for messaging, and Cloud Storage for audio files.

Backstage: Spotify built an internal developer portal called Backstage to manage the complexity of 4,000+ services. It was so useful they open-sourced it in 2020. Now a CNCF incubating project, Backstage provides a unified catalog of all services, documentation, CI/CD status, and infrastructure in one place. It's used by hundreds of companies worldwide.

5 Content Delivery

Storing and serving 100M+ tracks to 600M+ users across the globe

Spotify's catalog exceeds 100 million tracks, each stored at multiple quality levels. Every track is encoded in Ogg Vorbis at several bitrates (at minimum 96, 160, and 320 kbps), plus potentially HE-AAC for the lowest quality tier on mobile. The raw storage footprint is enormous, but the real engineering challenge is delivering the right bytes to the right user with minimal latency.

CDN Architecture

Spotify operates a hybrid CDN strategy: they use Google Cloud CDN combined with partnerships with third-party CDN providers (historically including Fastly and Akamai) plus their own edge caching infrastructure in key markets. Audio files are stored in Google Cloud Storage as the origin, with multiple cache tiers:

GCS Origin
→
Regional Cache
→
CDN Edge PoP
→
User Device

Popular tracks are cached at edge Points of Presence (PoPs) close to users. Long-tail tracks may require fetching from regional caches or even the origin. The cache hit ratio for popular tracks exceeds 95%—music consumption follows a power law where a small percentage of tracks account for the majority of plays.

Pre-fetching

When you're listening to a track, Spotify's client begins fetching the next track in your queue proactively. By the time the current song ends, the next one is already buffered. This works for queue, album, and playlist contexts. The client uses predictive models to decide what to pre-fetch—if you're listening to a playlist on shuffle, it pre-fetches the most likely next track.

Offline Mode (Encrypted Cache)

Premium users can download tracks for offline listening. Downloaded files are stored in an encrypted local cache using a device-specific key derived from the user's credentials. Files are Ogg Vorbis wrapped in Spotify's proprietary container format. The DRM prevents copying files to another device. The cache has a maximum size (configurable) and uses LRU eviction. Offline licenses must be renewed every 30 days by going online.

Historical: Peer-to-Peer (P2P)

In its early years (2008–2014), Spotify used a P2P network to reduce server costs. The desktop client would cache recently played tracks and serve them to nearby users, similar to BitTorrent. At peak, P2P accounted for up to 40% of all audio delivery. However, P2P caused issues: it consumed users' upload bandwidth, raised ISP concerns, and was complex to manage. As CDN costs dropped and mobile (which can't easily do P2P) became the dominant platform, Spotify phased out P2P entirely by 2014.

6 The Backend

The services that power every play, search, and recommendation

Core Backend Services

Client Apps Access Point (AP) User Service Auth, profiles Catalog Service Tracks, albums Playback Service Stream auth, CDN Social Service Friends, shares Recs Service ML models Cassandra PostgreSQL BigTable Cloud Storage

Service Communication

With 4,000+ services, how they talk to each other matters enormously:

  • gRPC — the primary synchronous RPC framework, using Protocol Buffers for serialization. Low-latency, strongly typed, with built-in load balancing.
  • Hermes — Spotify's internal pub/sub messaging system for asynchronous, event-driven communication. When a user saves a track, an event is published that dozens of downstream services consume (recommendation updates, analytics, social feed, etc.).
  • Google Cloud Pub/Sub — used for large-scale data pipeline events (play events, log aggregation).
  • Service discovery is handled through DNS-based discovery on Kubernetes, with custom service mesh components for routing, retries, and circuit breaking.

Data Storage

StoreTypeUse CasesWhy
Apache CassandraWide-column NoSQLUser data, playlists, play historyMassive write throughput, tunable consistency, linear scalability
PostgreSQLRelationalCatalog metadata, payment recordsACID transactions, complex queries, strong consistency
Google BigTableWide-column NoSQLTime-series data, feature stores for MLLow-latency at petabyte scale, GCP-native
Google Cloud StorageObject storeAudio files, album artwork, ML model artifactsVirtually unlimited capacity, CDN integration
BigQueryData warehouseAnalytics, A/B test analysis, ad-hoc queriesServerless, handles petabytes, SQL interface
Memcached / RedisIn-memory cacheSession data, hot metadata, rate limitingSub-millisecond latency

7 The Client

What happens between tapping play and hearing music

Spotify has native applications for iOS, Android, macOS, Windows, Linux, and a web player. The desktop and mobile clients share a core C++ library (internally called the "client library" or "libspotify successor") that handles audio decoding, caching, networking, and DRM. The UI layer on top varies by platform: Swift/UIKit on iOS, Kotlin/Jetpack Compose on Android, and React (via Chromium Embedded Framework) on desktop.

What Happens When You Press Play

  1. UI event fires — the play button tap is captured by the platform UI layer, which calls into the core client library.
  2. Resolve track — the client looks up the track's Spotify URI (e.g., spotify:track:6rqhFgbbKwnb9MLmUQDhG6) in the local metadata cache. If not cached, it requests metadata from the Catalog Service.
  3. Request playback token — the client contacts the Access Point (AP) server to get a playback token. The AP verifies the user's subscription, checks geo-restrictions, and returns a CDN file key + access token.
  4. Fetch audio chunks — using the CDN key, the client makes HTTP range requests to the nearest CDN edge server. The first chunk is prioritized for fast start-up (typically <200ms to first audio).
  5. Decrypt & decode — audio chunks are decrypted (Spotify uses AES-128 encryption on stored files), then decoded from Ogg Vorbis to raw PCM samples.
  6. Apply audio processing — volume normalization, equalizer settings, and crossfade mixing are applied to the PCM buffer.
  7. Output to audio device — PCM samples are written to the platform's audio output API (CoreAudio on Apple, AAudio/OpenSL ES on Android, WASAPI on Windows).
  8. Report playback event — the client sends a play event to Spotify's event pipeline (track ID, timestamp, duration, skip/complete, device type). This feeds recommendations, royalty calculations, and analytics.

Spotify Connect

Spotify Connect is the protocol that lets you control playback on one device from another—start a song on your phone, then seamlessly transfer it to your smart speaker or desktop. The architecture is elegant:

Every Spotify client maintains a persistent connection to the Access Point server. Each device registers itself as a "connect endpoint." When you transfer playback, no audio is actually streamed between devices. Instead, the controlling device sends a command message through the AP to the target device: "Play this track, at this position, in this context." The target device then independently fetches the audio from the CDN. This means Spotify Connect works even on devices with no Bluetooth or local network connection to each other—they just need internet access.

8 Collaborative Filtering

Recommending music based on what similar listeners enjoy

Collaborative filtering is the oldest and still one of the most powerful recommendation techniques. The core idea: if User A and User B have similar listening histories, songs that A loves but B hasn't heard are good recommendations for B. Spotify applies this at a scale of 600M+ users and 100M+ tracks.

User-User CF

Find users with similar taste profiles, recommend what they listen to. Intuitive but doesn't scale well—computing pairwise similarity between 600M users is prohibitive.

VS

Item-Item CF

Find tracks that co-occur in listening sessions. If tracks A and B are frequently listened to by the same users, they're "similar." More scalable and stable since the item catalog changes less frequently than user behavior.

Matrix Factorization

At Spotify's scale, both pure user-user and item-item approaches are impractical. Instead, they use matrix factorization—specifically, implicit feedback ALS (Alternating Least Squares). The approach:

Imagine a gigantic matrix with 600M rows (users) and 100M columns (tracks). Each cell represents how much a user has interacted with a track (play count, save, skip, playlist add). This matrix is extremely sparse (>99.99% empty). Matrix factorization decomposes it into two smaller matrices: a user matrix (600M × k) and a track matrix (100M × k), where k is typically 40–200 latent factors.

Each user and each track is now represented as a vector in k-dimensional space. The dot product of a user vector and a track vector predicts how much that user will like that track. To generate recommendations, you find tracks whose vectors are closest to the user's vector. Training this model on billions of interactions requires distributed computing (they use custom implementations on Google Cloud Dataflow and TensorFlow).

Implicit Feedback Signals

Unlike Netflix (where users rate movies 1–5 stars), Spotify primarily relies on implicit signals:

SignalInterpretationWeight
Stream (30+ seconds)PositiveHigh
Save to libraryStrong positiveVery High
Add to playlistStrong positiveVery High
Listen on repeatVery strong positiveHighest
Skip (<30 sec)NegativeMedium
Skip (<3 sec)Strong negativeHigh
Not interacting at allUnknown (NOT negative)N/A
The Cold Start Problem: New users with no listening history can't be placed in the latent factor space. Spotify addresses this with an onboarding flow (pick artists you like), fallback to popularity-based recommendations, and rapid adaptation—after just 10–20 interactions, collaborative filtering starts producing useful results.

9 Content-Based Filtering

Understanding the music itself, not just who listens to it

While collaborative filtering asks "who else likes this?", content-based filtering asks "what is this?" It analyzes the intrinsic properties of music to find similarities. Spotify uses three distinct approaches to understanding content:

Audio Analysis

Spotify runs every track through an audio analysis pipeline that extracts features:

  • Tempo (BPM)
  • Key and mode (major/minor)
  • Time signature
  • Energy (0.0–1.0: intensity and activity)
  • Danceability (0.0–1.0: rhythm stability, beat strength)
  • Valence (0.0–1.0: musical positivity/happiness)
  • Acousticness (probability of being acoustic)
  • Instrumentalness (probability of no vocals)
  • Speechiness (presence of spoken words)
  • Loudness (average dB)

These features are exposed via the Spotify Web API and used internally to cluster songs into audio-similar groups.

Natural Language Processing

Spotify continuously crawls the web—music blogs, reviews, forums, social media, news articles—to understand how people talk about music. Using NLP techniques (word embeddings, topic modeling, sentiment analysis), they extract cultural vectors that capture the vibe and context of artists and tracks.

For example, the NLP system might learn that an artist is described as "dreamy," "shoegaze," "ethereal," and "lo-fi." These text-derived features complement audio features because they capture cultural context that raw audio cannot (genre associations, mood descriptions, comparisons to other artists).

Genre Classification

Spotify maintains an internal genre taxonomy with over 6,000 micro-genres (you can explore them at everynoise.com, created by Spotify's Glenn McDonald). Genres are assigned using a combination of cultural NLP data, audio features, and crowd-sourced tagging. Each artist can belong to multiple genres, and each genre is defined by its centroid in audio-feature space plus its cultural descriptors. This granular taxonomy enables extremely precise recommendations—the system knows the difference between "vaporwave" and "future funk" or "midwest emo" and "math rock."

10 Discover Weekly

The playlist that made algorithmic recommendations personal

"Discover Weekly was born at a hack week in 2014. A small team wondered: what if we gave every user a personalized mixtape every Monday? The result became one of the most beloved features in Spotify's history." — Matthew Ogle, former Spotify product lead for discovery

Launched in July 2015, Discover Weekly delivers 30 personalized songs every Monday to each of Spotify's 600M+ users. Within its first year, it had been streamed over 5 billion times. Here's how it works:

The Discover Weekly Pipeline

  1. Build taste profile: Analyze the user's listening history from the past several weeks. Identify their preferred genres, artists, audio features, and listening patterns (what they play repeatedly vs. skip).
  2. Collaborative filtering: Find the user's "taste neighbors"—other users with overlapping taste profiles. Collect tracks that taste neighbors love but the target user hasn't heard.
  3. NLP cultural filtering: Filter and rank candidates using text-based cultural vectors. This ensures the recommendations feel culturally coherent (not just acoustically similar).
  4. Audio analysis scoring: Score remaining candidates against the user's preferred audio feature ranges. If a user primarily listens to high-energy tracks (0.8+), low-energy candidates are deprioritized.
  5. Novelty & diversity: Apply the exploration vs. exploitation tradeoff. Some slots are "safe" recommendations (high confidence the user will like them); others are deliberate "stretch" picks to broaden taste. The system also ensures genre diversity—no playlist of 30 tracks from one genre.
  6. Filtering: Remove tracks the user has already listened to, saved, or added to playlists. Remove explicit content if the user has a content filter enabled.
  7. Assemble & deliver: The final 30 tracks are compiled into a playlist object and published every Monday at approximately midnight in each time zone.

Why Mondays?

Spotify's data shows that Monday is when users are most open to new music. After a weekend of playing familiar favorites at social events, Monday (especially Monday mornings) represents a return to individual listening—commutes, desk work, headphones. The team also considered that "music discovery" aligns with the psychological fresh-start effect of a new week.

Exploration vs. Exploitation: A core tension in recommendation systems. Exploitation means recommending what the model is most confident you'll like (safe, similar to past listening). Exploration means introducing variety and novelty to discover new preferences and avoid filter bubbles. Discover Weekly explicitly balances both—roughly 70% exploitation, 30% exploration.

11 Audio Intelligence

Deep learning applied directly to raw audio waveforms

Collaborative filtering and NLP work well for popular music with lots of listeners and web coverage. But what about a brand-new track uploaded by an independent artist with zero plays and no press? This is where audio intelligence—understanding music from its raw waveform—becomes critical.

Convolutional Neural Networks on Audio

Spotify pioneered the use of deep convolutional neural networks (CNNs) applied to mel-spectrograms—visual representations of audio where the x-axis is time, y-axis is frequency (on the mel scale, which approximates human perception), and color/intensity represents amplitude.

A mel-spectrogram effectively turns audio into an image, and CNNs are exceptionally good at image recognition. Spotify's models process 3–5 second spectrogram slices and learn to extract features like genre, mood, instrumentation, and vocal characteristics without any human labeling. The learned representations (embeddings) are used as content vectors in the recommendation pipeline.

Audio Intelligence Pipeline

Raw Audio → Mel-Spectrogram → CNN → Embedding → Genre / Mood / Similarity

Music Information Retrieval (MIR)

MIR is the academic field behind Spotify's audio analysis. Key tasks include: beat tracking, chord recognition, key detection, structural segmentation (identifying verse/chorus/bridge), instrument recognition, singer identification, and mood classification. Spotify's research team (based in Barcelona, New York, London, and Stockholm) publishes actively in top MIR venues like ISMIR.

DJ Feature & AI Playlists

Spotify's DJ feature (launched 2023) uses a combination of generative AI and music intelligence. A large language model generates contextual commentary ("Here's something that matches the mood of what you've been listening to..."), voiced by a synthetic voice model. The music selection is driven by the same recommendation pipeline, but curated for flow—energy curves, tempo transitions, and thematic coherence across a listening session. AI-generated playlists like "daylist" (which changes throughout the day based on your mood patterns) also leverage audio intelligence to match music to temporal contexts.

12 Search System

Finding any of 100M+ tracks in milliseconds

Spotify's search must handle queries in every language, tolerate typos, understand context ("that song from the Barbie movie"), and return results in under 100 milliseconds. The system serves billions of queries per day.

Architecture

At the core is an inverted index—a data structure that maps every word (and n-gram) to the set of entities (tracks, artists, albums, playlists, podcasts) that contain it. The index is built from multiple metadata sources: track titles, artist names, album names, lyrics, genre tags, and more.

Fuzzy Matching

Typo tolerance uses edit distance (Levenshtein distance) and phonetic matching (Soundex/Metaphone). Searching "Byonsay" still returns Beyoncé. The system also handles transliteration (searching in Latin characters for artists whose names are in Korean/Japanese/Arabic).

Autocomplete

As you type, the search bar suggests completions using a prefix trie augmented with popularity scores. Results are personalized—if you frequently listen to a specific artist, they'll appear higher in autocomplete even if they're not globally popular.

Search Ranking

Results are ranked by a learned model that considers:

  • Text relevance — how well the query matches the entity name (BM25 + neural re-ranking)
  • Popularity — global and regional play counts (a track with 1B streams ranks higher than one with 1K)
  • Personalization — your listening history, saved artists, and playlist contents boost relevant results
  • Recency — newly released tracks get a temporary boost
  • Entity type — if you search an artist name, the artist result appears first, followed by their top songs and albums

The ranking model is a Learning to Rank (LTR) system trained on click-through data: given a query and the result the user actually selected, the model learns to surface similar results for similar queries.

13 Playlist Ecosystem

The playlists that drive the modern music industry

Playlists are the dominant way people consume music on Spotify. The platform hosts over 5 billion playlists, and landing on a major editorial playlist can make or break an artist's career. The ecosystem has three pillars:

Editorial Playlists

Human-curated

Spotify employs a global team of music editors who curate flagship playlists like Today's Top Hits (35M+ followers), RapCaviar (15M+), and Viva Latino (13M+). Editors listen to hundreds of submissions per week through Spotify for Artists. Placement on these playlists can generate millions of streams overnight. The editorial team combines their expertise with data (trending signals, algorithmic picks, listener engagement metrics) to select tracks.

Algorithmic Playlists

Personalized

Discover Weekly (30 new songs, Mondays), Release Radar (new releases from artists you follow + similar artists, Fridays), Daily Mix (multiple mixes blending your favorite genres with new discoveries), and Daylist (dynamically updating throughout the day). These are generated per-user by the recommendation pipeline described in sections 8–11.

User Playlists

Community

The 5B+ playlists created by users represent a massive source of implicit data for collaborative filtering. When thousands of users independently add the same two songs to their playlists, the system infers those songs are related. Popular user playlists with many followers effectively become tastemaker channels, and some playlist curators have built large followings and influence.

How Getting on a Major Playlist Works

Artists and labels can submit unreleased tracks to Spotify's editorial team via Spotify for Artists at least 7 days before release. The submission includes genre tags, mood descriptions, and promotional context. The algorithmic system also surfaces trending tracks to editors. About 30% of editorial playlist additions come from algorithmic triggers (rapid increase in saves, Shazam identifies, social buzz). The remaining 70% are direct editorial picks based on listening, submissions, and cultural context.

14 The Economics

How $0.003–0.005 per stream adds up to a $70B+ company

Spotify's business model is deceptively simple: collect revenue from subscriptions and advertising, then pay out approximately 70% to rights holders (labels, publishers, distributors). The remaining 30% funds Spotify's operations, R&D, and (eventually) profit. But the details of how royalties are calculated are contentious and complex.

Revenue Flow

User pays $10.99/mo
→
Spotify takes ~30%
→
~70% to rights pool
→
Label / Distributor
→
Artist

Pro-Rata Model (Current)

All subscription revenue goes into one pool. Each track's share is its proportion of total global streams. If Track A gets 0.001% of all streams, it gets 0.001% of the royalty pool. This means a user who listens to 10 songs/month effectively subsidizes heavy listeners. It also favors high-stream pop and viral tracks.

VS

User-Centric Model (Proposed)

Each user's subscription fee is divided only among the artists that specific user listened to. If you only listen to jazz, 100% of your royalty contribution goes to jazz artists. This would benefit niche genres and dedicated fanbases. Deezer adopted this model; Spotify has tested but not fully implemented it.

The Per-Stream Rate

The commonly cited "$0.003–0.005 per stream" is an average, not a fixed rate. The actual payment per stream varies based on: the country where the listener is located (a stream from the US pays more than from India due to subscription pricing), whether the listener is on Free or Premium tier, and the total number of streams in that period. This rate has been relatively stable but is a source of ongoing tension between Spotify and artists/labels.

TierApprox. Per-StreamStreams for $1,000Streams for $50K/year
Premium (US)~$0.004–0.005~220,000~11M
Premium (Global avg)~$0.003–0.004~285,000~14M
Free tier~$0.001–0.002~650,000~32M

The Royalty Chain

When Spotify pays "rights holders," the money typically flows through multiple intermediaries before reaching the artist:

Spotify
→
Record Label (50–80%)
→
Artist (20–50% of label share)

Additionally, publishing royalties (for songwriters) flow separately: Spotify pays publishing rights organizations (e.g., ASCAP, BMI, PRS), which pay publishers, who pay songwriters. An artist who both performs and writes might receive two separate (small) payments for each stream. Independent artists using distributors like DistroKid, TuneCore, or CD Baby typically keep 80–100% of the distributor's share, making per-stream economics significantly better for them.

15 Ad-Supported Tier

Programmatic audio advertising at scale

Spotify's free tier serves approximately 400M+ users and generates revenue through audio, video, and display advertising. The ad-supported tier accounts for roughly 12–15% of total revenue, but serves a critical function: it's the top of the funnel that converts free users to premium subscribers (conversion rate: ~25% over time).

Ad Delivery Architecture

Audio ads must be seamlessly inserted into the listening experience without buffering gaps or abrupt volume changes. Here's how it works:

  1. Pre-fetch ad content: The client receives ad decisions from the ad server before the ad break. While the user is still listening to music, the ad audio file is downloaded and cached locally. This prevents any loading delay when the ad break begins.
  2. Volume normalization: Ads are loudness-normalized to match the preceding music (targeting -14 LUFS, the same standard applied to music). This prevents the jarring experience of ads being louder than the music.
  3. Seamless insertion: The player transitions to the pre-cached ad with a brief crossfade, plays the ad, then crossfades back to the next music track. The entire transition is handled locally by the client.
  4. Impression reporting: The client reports ad impressions, completions, and interactions back to the ad server for billing and analytics.

Streaming Ad Insertion (SAI) for Podcasts

Podcast ads use a fundamentally different mechanism called Streaming Ad Insertion (SAI). Unlike traditional podcast ads (baked into the audio file by the creator), SAI dynamically stitches ads into the podcast stream at the time of playback. This enables:

  • Targeting: Different listeners hear different ads based on demographics, interests, and location
  • Impression tracking: Spotify can confirm the ad was actually heard (not just downloaded)
  • Freshness: Old episodes can serve current ads instead of outdated ones
  • A/B testing: Advertisers can test different ad creatives against different audiences

SAI works by the podcast containing timestamp markers where ads can be inserted. At playback time, the server assembles a personalized version of the episode with targeted ads stitched in at those markers. The stitching happens server-side, and the client receives what appears to be a single continuous audio stream.

16 Scale Numbers

The sheer magnitude of the world's largest audio streaming platform

600M+

Monthly active users

220M+

Premium subscribers

100M+

Tracks in catalog

5B+

User-created playlists

4,000+

Microservices

183

Markets worldwide

Handling Traffic Spikes

When a major artist (Taylor Swift, Drake, Bad Bunny) drops a new album, Spotify experiences massive, sudden traffic spikes. The infrastructure must handle these gracefully:

  • Pre-provisioning: For known release dates (announced weeks in advance), the infrastructure team pre-scales services—additional Kubernetes pods, CDN cache warming for the new tracks, and extra capacity on access point servers.
  • Auto-scaling: GKE auto-scaling responds to real-time metrics (CPU utilization, request latency, queue depth). New pods can spin up in under 60 seconds.
  • Circuit breakers: If a downstream service becomes overwhelmed, circuit breakers prevent cascade failures. The playback service, for instance, can gracefully degrade by serving slightly stale metadata rather than failing entirely.
  • Load shedding: In extreme scenarios, non-critical features (social feed, canvas videos, animated covers) are deprioritized to protect core playback functionality.
When Drake's "Scorpion" dropped in 2018, it was streamed 132 million times on its first day. The infrastructure handled it without a single playback failure visible to users. Behind the scenes, auto-scaling provisioned 3x normal capacity within the first hour. — Spotify Engineering Blog

17 Data Pipeline

Turning billions of daily events into insights, recommendations, and royalty payments

Every interaction on Spotify—every play, skip, search, save, playlist add, scroll, and ad impression—generates an event. At 600M+ monthly active users, this produces billions of events per day, creating one of the largest real-time data pipelines in the world.

Data Pipeline Architecture

Client Events → Cloud Pub/Sub → Apache Beam (RT) Scio (Batch) → → BigQuery → ML Training A/B Analysis Royalties Dashboards Reporting Billions/day Message bus Processing Data warehouse Consumers

Real-Time vs. Batch Processing

AspectReal-Time (Streaming)Batch
LatencySeconds to minutesHours
ToolApache Beam on Cloud DataflowScio (Scala wrapper for Beam) on Dataflow
Use casesLive listening counts, real-time charts, fraud detection, ad pacingRecommendation model training, royalty calculation, monthly reports
VolumeMillions of events/secondPetabytes per batch job

A/B Testing Infrastructure

At Spotify, every feature is an experiment. The A/B testing platform, built internally, supports thousands of concurrent experiments across all clients. Every user is randomly assigned to experiment buckets, and every interaction is tagged with the active experiments. This allows the data team to measure the causal impact of any change—from a new recommendation algorithm to a button color change—on metrics like stream count, session length, retention, and conversion.

The system handles the statistical complexity of running thousands of overlapping experiments (multiple testing correction, interaction effects between experiments, novelty effects) using sophisticated Bayesian methods. Results are surfaced in an internal dashboard where product teams can monitor experiment health and make ship/no-ship decisions with statistical rigor.

Event Schema: What a Single Play Event Contains

When you listen to a song for more than 30 seconds, the following (simplified) event is generated:

{
  "event_type": "track_playback",
  "timestamp": "2026-03-27T14:32:01.234Z",
  "user_id": "hashed_user_id",
  "track_uri": "spotify:track:6rqhFgbbKwnb9MLmUQDhG6",
  "context_uri": "spotify:playlist:37i9dQZF1DXcBWIGoYBM5M",
  "duration_ms": 217840,
  "ms_played": 217840,
  "reason_start": "fwdbtn",
  "reason_end": "trackdone",
  "shuffle": true,
  "offline": false,
  "platform": "android",
  "product": "premium",
  "country": "US",
  "experiments": ["rec_v42", "ui_refresh_3", "codec_opus_test"]
}

This single event feeds: royalty calculation, recommendation model training, A/B test analysis, artist analytics (Spotify for Artists), chart calculations, and capacity planning. Multiply by billions per day, and you understand why Spotify is fundamentally a data company that happens to stream music.