Design the web player for a music streaming service like Spotify.
Users browse a home page of recommendations, search for artists, albums and tracks, open album and playlist pages, manage their library, and play music. The player bar at the bottom shows the current track with play/pause, seek, next/previous, shuffle, repeat, volume and a queue.
The interviewer adds:
Focus on the app architecture, the playback engine, the queue model, data fetching and caching, multi-device sync and performance.
A music player is a long-lived media session living inside a browsing app. The two halves have different lifetimes: pages come and go with navigation, the player must survive all of it. Most of the interesting design is about that boundary, the playback engine (streaming, gapless, DRM), and keeping playback state consistent across the user's devices.
| Concern | Target |
|---|---|
| Time to first audio | < 500 ms p50 after pressing play on a warm session; < 1.5 s cold |
| Track transitions | 0 ms gap for gapless albums; next track pre-buffered ≥ 10 s before the end |
| Navigation | playback uninterrupted; page transitions < 200 ms with cached data |
| Rebuffering | < 0.5% of playback time; adapt quality on slow networks |
| Remote control | command to playback change on another device < 1 s |
| Lists | 10k-track playlist scrolls at 60 fps |
| Accessibility | player fully keyboard operable, screen reader announces track changes, WCAG 2.2 AA |
| Bundle | initial JS < 200 KB gzip for the shell; routes code-split |
Assume premium and free tiers, all evergreen browsers, web only.
The SPA has two regions with different lifetimes:
/, /search, /album/:id, /playlist/:id). Mounted and unmounted by the router.This is the core answer to "playback must never stop". A full page reload would kill audio, so the app must be an SPA (or use a framework with client-side navigation; with React Server Components/Next.js App Router, the player goes in the root layout, which persists across navigations).
| Component | Responsibility |
|---|---|
| Router + pages | data-driven pages, code-split per route |
| Server cache | TanStack Query (or similar): catalogue entities, library, search results |
| Entity store | normalised tracks/albums/artists so a "liked" toggle updates everywhere |
| Player controller | the state machine: what is playing, queue, position, shuffle/repeat; the only API the UI uses |
| Playback engine | wraps <audio> + Media Source Extensions + EME; segment fetching, buffering, gapless, ABR |
| Queue manager | context (album/playlist), user queue, shuffle order, history |
| Device sync (Connect) | WebSocket to the playback-state service: publishes local state, receives commands |
| OS integration | Media Session API metadata and action handlers |
| Telemetry | play events (for royalties and recommendations), QoE metrics |
<audio src>: simplest; but no DRM for progressive files without EME, limited control over buffering,
and a decoder gap between tracks.SourceBuffer; EME obtains licences from the DRM server. This gives control over
pre-buffering, quality switching and gapless joins. This is the right choice and what major services do.MediaElementAudioSourceNode with gain nodes. Not for decoding DRM content directly (EME-decrypted audio cannot
be read into buffers).interface Track {
id: string;
title: string;
durationMs: number;
artists: Array<{ id: string; name: string }>;
album: { id: string; name: string; images: Image[] };
explicit: boolean;
playable: boolean; // licensing by region
audio: { manifestUrl: string; loudnessDb: number; gaplessInfo?: { encoderDelay: number; padding: number } };
}
interface PlaylistPage {
id: string;
name: string;
owner: { id: string; name: string };
totalTracks: number;
snapshotId: string; // version for concurrent edits
items: Array<{ uid: string; trackId: string; addedAt: string; addedBy?: string }>;
nextCursor: string | null;
}
interface Image { url: string; width: number; height: number }
Tracks are normalised by ID: a playlist stores trackIds, the entity store holds tracks once. Playlist items have a
uid distinct from trackId, because the same track can appear twice.
interface PlaybackState {
deviceId: string;
isPlaying: boolean;
positionMs: number;
positionTimestamp: number; // wall clock when position was sampled, so others can extrapolate
track: { id: string; uid?: string } | null;
context: { type: 'album' | 'playlist' | 'artist' | 'search'; id: string } | null;
shuffle: boolean;
repeat: 'off' | 'context' | 'track';
volume: number;
}
interface QueueState {
userQueue: string[]; // "Add to queue" items, played before the context continues
contextOrder: string[]; // uids in play order (shuffled or not), may be windowed for huge contexts
contextIndex: number;
history: string[]; // for "previous"
}
The canonical queue lives server-side in the playback-state service, so any device can resume or control it. The active device holds a local copy and drives playback; it reports state changes. Other devices render the server's state and send commands.
GET /v1/home?limit=10 -> { shelves: [{ id, title, items: [...] }] }
GET /v1/search?q=radiohead&types=track,album,artist&limit=10
GET /v1/albums/:id -> album with tracks (albums are small)
GET /v1/playlists/:id/items?cursor=&limit=100
PUT /v1/me/library/tracks { ids: ["..."] }
POST /v1/playlists/:id/items { trackIds, position, snapshotId } -> { snapshotId }
GET /v1/tracks/:id/playback -> { manifestUrl, licenseUrl, formats: [{ codec: "opus", bitrate: 160 }, ...] }
Playlist edits send the snapshotId they were based on; the server rebases positional inserts/moves or rejects with
409 if it cannot, and the client refetches.
type ClientToServer =
| { t: 'register-device'; device: { id: string; name: string; type: 'web' } }
| { t: 'state'; state: PlaybackState } // from the active device
| { t: 'command'; targetDeviceId: string; cmd: Command }; // from a remote control
type Command =
| { type: 'play'; context?: { type: string; id: string }; offsetUid?: string; positionMs?: number }
| { type: 'pause' } | { type: 'resume' } | { type: 'next' } | { type: 'previous' }
| { type: 'seek'; positionMs: number }
| { type: 'set-shuffle'; value: boolean }
| { type: 'transfer'; toDeviceId: string };
type ServerToClient =
| { t: 'devices'; devices: Array<{ id: string; name: string; type: string; isActive: boolean }> }
| { t: 'state'; state: PlaybackState; version: number }
| { t: 'command'; cmd: Command; commandId: string };
interface PlayerController {
play(opts: { context?: ContextRef; startAtUid?: string; positionMs?: number }): Promise<void>;
pause(): void;
resume(): void;
seek(ms: number): void;
next(): void;
previous(): void; // restarts the track if > 3 s in, else goes back
setShuffle(on: boolean): void;
setRepeat(mode: 'off' | 'context' | 'track'): void;
addToQueue(trackId: string): void;
subscribe(listener: (s: PlaybackState) => void): () => void;
}
Components subscribe with useSyncExternalStore. The progress bar does not subscribe to position at 60 Hz
through React state; it reads currentTime in a requestAnimationFrame loop and writes the DOM transform directly
(or uses a CSS animation started at the right offset and paused on pause).
MediaKeySession alive and request licences that cover multiple tracks where the
DRM policy allows, to avoid a licence round trip per track.AudioContext inside the click handler; handle play() rejections by showing a "Click to play" state.SourceBuffer using timestampOffset set to
the previous track's end, and trim encoder delay/padding with appendWindowStart/appendWindowEnd. One continuous
media timeline, no gap.loudnessDb from metadata via a gain node, so tracks play at consistent volume.Audio bitrates are small (roughly 24–320 kbps), so ABR is simpler than video: measure segment download throughput,
keep a buffer target (e.g. 30 s ahead), and step quality down when the buffer drains or the connection is metered
(navigator.connection.saveData where supported). Quality also depends on the subscription tier. Switch only at
segment boundaries; codecs must match within a SourceBuffer (use changeType() if switching codec).
userQueue, which is consumed before resuming the context.PlaybackState and a version.(positionMs, positionTimestamp) so remote UIs extrapolate the progress bar without
per-second messages.BroadcastChannel election, so audio never plays
twice.totalTracks.srcset from the multiple Image sizes, lazy loading below the fold, dominant colour placeholder (also
used for page header gradients).staleTime, normalised so the same track updates everywhere.Cache-Control); encrypted, so caching is safe.
A service worker can keep the app shell and recently played artwork for fast startup.navigator.mediaSession.metadata (title, artist, album, artwork in several sizes) and
handlers for play, pause, previoustrack, nexttrack, seekto; update setPositionState so OS scrubbers are
accurate.<footer> or role="region" with a label). Buttons have accessible names that
reflect state ("Pause", "Shuffle on"). The seek bar is a slider (role="slider" or <input type="range">) with
aria-valuetext="1 minute 20 seconds of 3 minutes 45 seconds".start, 30s reached, end, skip) are business-critical (royalties): queue them durably in
IndexedDB and send with fetch(..., { keepalive: true }) or navigator.sendBeacon on page hide.SourceBuffer, timestampOffset, append windows) instead of "preload
the next track".How do you keep playing when the user opens a link that does a full page load? Avoid full loads inside the app: intercept internal links. For true cross-document navigation, you cannot keep audio playing; some apps open the player in a separate window. The View Transitions API for MPAs does not preserve media.
How would you implement synced lyrics? Fetch time-coded lines; on each animation frame compare currentTime
with line start times (binary search), highlight and auto-scroll the active line, pausing auto-scroll while the user
scrolls manually.
What about collaborative "group sessions"? Extend Connect: a session has many listeners each playing locally, with the host's commands broadcast and positions synchronised by timestamp, accepting a small drift tolerance.
How do you handle a track that becomes unavailable mid-queue (licensing)? The queue skips unplayable items
(playable: false) and greys them in lists; if a licence fails at play time, log it and move to the next track.
Why not one <audio> per track? Simpler, but you get gaps, duplicated buffering logic and more licence sessions.
It is acceptable for a prototype or podcasts.
Spotted a mistake or a rights concern? Report an issue