Concurrent Music Player and Playlist Engine in Go
Hard · System Design · Software Engineer · Technical Screen
Prompt
Design an in-process, object-oriented audio playback and playlist engine in Go centered on three core domain types: Song, Playlist, and Player. Callers must be able to append or insert tracks, delete tracks, move tracks to new positions, toggle duplicate-track prevention, and combine two playlists into a new ordered playlist under a well-defined duplicate-resolution rule.
Once a Playlist is loaded into a Player, callers control playback through start/resume, pause, forward skip, backward skip, randomized shuffle, and repeat modes—even while other goroutines edit playlists or persist state to disk concurrently.
Scope & Expectations
- Go APIs and internal data structures: Define clean idiomatic Go types, methods, and error contracts for
Song,Playlist,Player, and playlist merging, analyzing the time and space complexity of each operation. - Playback and duplicate semantics: Specify deterministic rules for duplicate entries, deduplication toggles, order-preserving playlist merges, shuffle permutations, repeat modes, and cursor behavior when active tracks move or are deleted.
- Concurrency safety and durability: Guarantee race-free, deadlock-free execution across concurrent goroutines performing playlist mutations and playback controls simultaneously, and design crash-safe local persistence.
- Verification plan: Outline a deterministic Go unit-test suite covering playlist editing, merge policies, playback edge cases, persistence round-trips, and race-detector stress tests.
Step-by-step walkthrough
Clarify scope and pin down ambiguous policies
Unlike a distributed cloud architecture prompt, this design centers on in-process object-oriented modeling, data-structure complexity, and goroutine-safe concurrency in Go. Start by bounding the runtime scope and turning underspecified product edges—how duplicate slots are addressed, how playlist merges resolve repeats, and what happens when an active track is edited mid-play—into explicit, testable contracts.
Runtime scope (confirmed with the interviewer)
- In scope: A single Go process (a desktop app, CLI player, or local home-media daemon) managing a song catalog, multiple
Playlistinstances, and aPlayer. Multiple goroutines (lightweight concurrent threads managed by the Go runtime—such as UI handlers, an HTTP control API, a bulk importer, an autosaver, and the audio output loop) read and mutate state simultaneously. - Out of scope: Low-level MP3/FLAC audio decoding (isolated behind an injected
Outputinterface), network audio streaming, and multi-device cloud sync (covered as a follow-up).
Explicit product & behavioral policies
- Duplicates use unique slot tickets (
EntryID), not bareSongIDs: By default, playlists allow duplicate songs (listeners often put an anthem twice in a workout mix). Every row in a playlist therefore receives a unique monotonicEntryID. Removing, moving, or tracking the "currently playing" item always targets anEntryID—never aSongID(which is ambiguous when a song appears twice) and never a raw slice index (which goes stale if another goroutine inserts a row above it). - Optional deduplication (
uniquemode): Whenunique == true,AddandInsertreject an already-presentSongIDwithErrDuplicateinO(1)time. TogglingSetUnique(true)on an existing playlist compacts it in place, keeping the first occurrence of each song and returning the number of removed entries. - Non-destructive
Mergewith three policies:Merge(name, a, b, policy)returns a brand-new*Playlistpreserving relative order without mutatingaorb, supporting:KeepAll: concatenateafollowed byb(result hasunique = false).KeepFirst: keep each distinct song once at its earliest position ina-then-b(unique = true).KeepLast: keep each distinct song once at its latest position ina-then-b(unique = true).
- Crisp
Playeredge-case semantics:NextandPreviouswhilePausedmove the cursor while stayingPaused(pressingPlaythen starts the newly selected track from0:00).RepeatOnereplays a track automatically when it finishes naturally (TrackEnded), whereas manually pressingNextstill advances to the next track.Previouson the first track in the play order restarts that track from0:00.- Removing the currently playing
EntryIDautomatically skips to the entry that immediately followed it (stopping if it was last andRepeatOffis set). - Toggling
Shuffleon or off never interrupts the currently playing track; only the play order around it changes.
Non-functional goals
- Sub-millisecond responsiveness for playlists up to
10,000entries (100x faster than the~100 mshuman perception threshold). - Zero data races (unsynchronized concurrent memory accesses, verified via
go test -race) and zero deadlocks (goroutines waiting forever in a lock cycle). - Crash-safe persistence (power loss never leaves a half-written JSON file) and deterministic unit tests.
- In scope: A single Go process (a desktop app, CLI player, or local home-media daemon) managing a song catalog, multiple
Back-of-the-envelope numbers and data-structure sizing
Estimating realistic memory and latency numbers tells us right away whether simple Go slices beat pointer-heavy trees or linked lists:
Scale & Memory Estimates Song library 50,000 songs x ~300 B metadata ~15 MB RAM Single playlist 10,000 entries x 24 B (8 B EntryID + ~240 KB contiguous slice 16 B Go string header sharing SongID) Counts map <= 10,000 SongID keys ~300 KB hash map JSON file on disk 10,000 entries x ~60 B JSON ~0.6 MB per playlist Typical Operation Latency at N = 10,000 Entries (modern laptop CPU) Move (worst-case shift of 10k contiguous 24-byte structs) ~4.5 us Snapshot (contiguous copy of all 10k entries under RLock) ~29 us Player full order reconcile after an edit ~0.9 ms Player Next / Previous when playlist version is unchanged ~75 nsWhat the numbers tell us
- Contiguous
O(N)slice shifts (~4.5 us) are completely invisible atN = 10,000. CPU cache locality makes shifting240 KBof contiguous memory faster and far simpler than maintaining a doubly linked list or balanced tree. - Correctness—not raw CPU speed—is the real engineering challenge: keeping duplicate copies distinct, keeping playback coherent while concurrent edits happen, and ordering locks so deadlocks are structurally impossible.
- Know the scaling cliff: Around
N = 1,000,000entries, linear reconcile approaches~90 ms, at which point incremental edit deltas and anO(log N)tree become justified.
- Contiguous
Public Go API: separating data (`Playlist`) from playback (`Player`)
We separate pure data (
Playlist) from the playback state machine (Player). Crucially,Playlistdoes not import or referencePlayer—so one playlist can be played, autosaved to disk, and merged into another playlist concurrently.type SongID string type Song struct { ID SongID Title string Artist string Duration time.Duration URI string } // EntryID uniquely identifies one row in one Playlist; 0 means "no entry". type EntryID uint64 type Entry struct { ID EntryID `json:"id"` Song SongID `json:"song"` } // Sentinel errors let callers branch cleanly using errors.Is(err, ErrDuplicate). var ( ErrDuplicate = errors.New("playlist: duplicate song in unique mode") ErrNotFound = errors.New("playlist: entry ID not found") ErrOutOfRange = errors.New("playlist: index out of range") ) // Playlist methods (all safe for concurrent use by multiple goroutines) func NewPlaylist(name string, unique bool) *Playlist func (pl *Playlist) Add(song SongID) (EntryID, error) func (pl *Playlist) Insert(index int, song SongID) (EntryID, error) func (pl *Playlist) Remove(id EntryID) error func (pl *Playlist) Move(id EntryID, to int) error func (pl *Playlist) SetUnique(on bool) int // returns count of removed duplicates func (pl *Playlist) Snapshot() ([]Entry, uint64) // defensive copy + version number func (pl *Playlist) Version() uint64 // cheap O(1) version check (no copy) func (pl *Playlist) Subscribe() (<-chan struct{}, func()) // coalesced change signal + cancel func func Merge(name string, a, b *Playlist, policy DupPolicy) *Playlist // Player methods (all safe for concurrent use) func NewPlayer(out Output, rng *rand.Rand) *Player func (p *Player) Load(list *Playlist) func (p *Player) Play() func (p *Player) Pause() func (p *Player) Stop() func (p *Player) Next() func (p *Player) Previous() func (p *Player) SetShuffle(on bool) func (p *Player) SetRepeat(m RepeatMode) func (p *Player) TrackEnded(seq uint64) // invoked asynchronously when audio finishes func (p *Player) Current() (SongID, State) // Output abstracts the audio hardware/decoder so unit tests run silently and instantly. type Output interface { Start(seq uint64, song SongID) Pause() Resume() Stop() }- Why
Version()exists alongsideSnapshot(): On every button press (Next,Pause),Playercheckspl.Version() == p.seenVerinO(1)without allocating memory, callingSnapshot()(O(N)) only when an edit actually occurred. - Why
Outputand*rand.Randare injected: Passing a recording fakeOutputand a seededrand.New(rand.NewSource(1))makes every playback and shuffle test 100% deterministic.
- Why
Data structures and time/space complexity
Inside
Playlist, we pair a contiguous[]Entryslice with amap[SongID]intfrequency table protected by async.RWMutex(a reader-writer mutual-exclusion lock that lets many goroutines read concurrently viaRLock, while giving a writer exclusive access viaLock):type Playlist struct { mu sync.RWMutex name string unique bool entries []Entry // ordered playlist slots counts map[SongID]int // active occurrences per SongID -> O(1) duplicate check lastID EntryID // monotonic ticket generator (1, 2, 3, ...) version uint64 // starts at 1; incremented on every state mutation subs []chan struct{} } func NewPlaylist(name string, unique bool) *Playlist { // Starting version at 1 ensures a Player's initial seenVer = 0 always triggers a sync. return &Playlist{ name: name, unique: unique, counts: make(map[SongID]int), version: 1, } }Complexity comparison: slice vs. doubly linked list vs. balanced order-statistic tree
Operation []Entry + counts (Chosen) Doubly Linked List + Map Order-Statistic Tree ---------------------------------------------------------------------------------------------------------- Add (append at tail) O(1) amortized O(1) O(log N) Insert(index, song) O(N) contiguous shift O(N) pointer walk O(log N) Remove(entryID) O(N) scan + shift O(1) via map[EntryID]*node O(log N) Move(entryID, toIndex) O(N) scan + shift O(N) walk to toIndex O(log N) Read at index i (UI / Player) O(1) O(N) pointer walk O(log N) Snapshot all entries O(N) fast memcpy O(N) cache-miss chase O(N) traversal Duplicate check (unique mode) O(1) via counts[song] O(1) via counts[song] O(1) via counts[song] SetUnique(true) O(N) time, O(N) seen map O(N) time, O(N) seen map O(N) rebuild Merge(a, b) O(N + M) time & space O(N + M) time & space O(N + M) time & space Shuffle (Fisher-Yates) O(N) time, O(N) order slice O(N) extract + shuffle O(N) order slice Player Next/Prev (no edit) O(1) time, O(1) space O(1) with order slice O(1) with order slice Player reconcile after edit O(N) (or O(K*N) if K added O(N) O(log N) with edit in shuffle batch) delta stream Memory per entry 24 B (+ shared count key) ~72+ B (node + 2 ptrs + ~80+ B (tree node + EntryID map bucket) subtree size + map)A doubly linked list wins only on
Remove(entryID)while losingO(1)index reads and tripling memory overhead;[]Entrywins hands-down atN <= 10,000.Component architecture and lock-order flow
UI / CLI / HTTP Handlers / Bulk Importer (Concurrent Goroutines) | Playlist edits | Playback controls v v +-----------------------+ Snapshot() +-----------------------+ Start/Pause/ +------------------+ | Playlist |<----------------| Player |--------------->| Output | | mu sync.RWMutex | (takes RLock) | mu sync.Mutex | Resume/Stop | (Audio Engine | | entries []Entry | | order []EntryID | (non-blocking)| Goroutine) | | counts, version |--- notify ----->| pos, state, seq |<---------------| | +-----------------------+ (1-slot chan, +-----------------------+ TrackEnded(seq)+------------------+ ^ | never blocks) | Load | Subscribe() + Snapshot() | v +-----------------------+ +-----------------------+ | Persistence Store | | Song Library | | Temp-file + fsync + | | Read-mostly map of | | atomic os.Rename | | SongID -> Song | +-----------------------+ +-----------------------+Package organization and one-way dependency rule
music/ song.go Song, SongID, thread-safe Library catalog playlist.go Playlist, Entry, EntryID, Merge, DupPolicy, sentinel errors player.go Player, Output, RepeatMode, State store.go SavePlaylist, LoadPlaylist, AutoSave music_test.go table-driven unit tests, fake Output, -race stress test, benchmarksNotice the strict one-way call arrow:
PlayerandStorecallPlaylist, whilePlaylistnever callsPlayerorStore. WhenPlaylistchanges, it performs a non-blocking send on a 1-element bufferedchan struct{}. Because the buffer size is1, a slow subscriber never blocks an edit, and 1,000 rapid edits coalesce into a single wake-up signal.Deep dive 1: Playlist edits, optional deduplication, and `Merge`
Every write method acquires
pl.mu.Lock(), validates arguments, mutatesentriesandcountsatomically together, incrementsversion, and signals subscribers:func (pl *Playlist) Add(song SongID) (EntryID, error) { pl.mu.Lock() defer pl.mu.Unlock() return pl.insertLocked(len(pl.entries), song) } func (pl *Playlist) Insert(index int, song SongID) (EntryID, error) { pl.mu.Lock() defer pl.mu.Unlock() return pl.insertLocked(index, song) } func (pl *Playlist) insertLocked(index int, song SongID) (EntryID, error) { if index < 0 || index > len(pl.entries) { return 0, ErrOutOfRange } if pl.unique && pl.counts[song] > 0 { return 0, ErrDuplicate } pl.lastID++ entry := Entry{ID: pl.lastID, Song: song} pl.entries = slices.Insert(pl.entries, index, entry) pl.counts[song]++ pl.notifyLocked() return entry.ID, nil } func (pl *Playlist) Remove(id EntryID) error { pl.mu.Lock() defer pl.mu.Unlock() idx := pl.indexLocked(id) // O(N) linear scan matching Entry.ID == id if idx < 0 { return ErrNotFound } song := pl.entries[idx].Song if pl.counts[song] <= 1 { delete(pl.counts, song) } else { pl.counts[song]-- } pl.entries = slices.Delete(pl.entries, idx, idx+1) pl.notifyLocked() return nil } // Move places entry id so its final index after the move equals to. func (pl *Playlist) Move(id EntryID, to int) error { pl.mu.Lock() defer pl.mu.Unlock() from := pl.indexLocked(id) if from < 0 { return ErrNotFound } if to < 0 || to >= len(pl.entries) { return ErrOutOfRange } if from == to { return nil // No-op: avoid unnecessary version bumps and autosaves } entry := pl.entries[from] pl.entries = slices.Delete(pl.entries, from, from+1) pl.entries = slices.Insert(pl.entries, to, entry) pl.notifyLocked() return nil } func (pl *Playlist) SetUnique(on bool) int { pl.mu.Lock() defer pl.mu.Unlock() if on == pl.unique { return 0 } pl.unique = on removed := 0 if on { seen := make(map[SongID]bool, len(pl.entries)) kept := pl.entries[:0] for _, e := range pl.entries { if !seen[e.Song] { seen[e.Song] = true kept = append(kept, e) } } removed = len(pl.entries) - len(kept) pl.entries = kept clear(pl.counts) for _, e := range kept { pl.counts[e.Song] = 1 } } pl.notifyLocked() // Always bump version so AutoSave persists the updated unique flag! return removed } func (pl *Playlist) notifyLocked() { pl.version++ for _, ch := range pl.subs { select { case ch <- struct{}{}: default: // A wake-up is already buffered; coalescing avoids blocking writers } } }Order-preserving
Mergeand why sequential snapshots avoid self-deadlockTrace
Mergeona = [x, y, x, z]andb = [y, w, x]:Combined stream (a then b): [ x, y, x, z, y, w, x ] KeepAll -> [ x, y, x, z, y, w, x ] (all 7 entries kept; unique = false) KeepFirst -> [ x, y, z, w ] (first occurrence left-to-right wins; unique = true) KeepLast -> [ z, y, w, x ] (scan right-to-left then reverse -> latest wins; unique = true)func Merge(name string, a, b *Playlist, policy DupPolicy) *Playlist { // Snapshot one playlist at a time instead of locking both simultaneously! entriesA, _ := a.Snapshot() entriesB, _ := b.Snapshot() combined := make([]SongID, 0, len(entriesA)+len(entriesB)) for _, e := range entriesA { combined = append(combined, e.Song) } for _, e := range entriesB { combined = append(combined, e.Song) } switch policy { case KeepFirst: combined = filterKeepFirst(combined) case KeepLast: combined = filterKeepLast(combined) } out := NewPlaylist(name, policy != KeepAll) for _, song := range combined { out.insertLocked(len(out.entries), song) // Safe without Lock: out has not escaped yet } return out } func filterKeepFirst(songs []SongID) []SongID { seen := make(map[SongID]bool, len(songs)) out := make([]SongID, 0, len(songs)) for _, s := range songs { if !seen[s] { seen[s] = true out = append(out, s) } } return out } func filterKeepLast(songs []SongID) []SongID { seen := make(map[SongID]bool, len(songs)) out := make([]SongID, 0, len(songs)) for i := len(songs) - 1; i >= 0; i-- { if !seen[songs[i]] { seen[songs[i]] = true out = append(out, songs[i]) } } slices.Reverse(out) return out }Why snapshot
aandbone at a time instead of locking both? First, lockingathenbwhile another goroutine callsMerge(..., b, a, ...)causes a classic AB-BA deadlock. Second, evenMerge("copy", x, x, KeepAll)would deadlock under two nestedRLock()calls! Go'ssync.RWMutexis not reentrant (the same goroutine may not acquire a second read lock while holding one): if a writer callsx.mu.Lock()between the firstRLock()and the secondRLock(), Go blocks new readers behind the waiting writer, while the writer waits for the firstRLock()to release—freezing both forever. SequentialSnapshot()calls eliminate both traps cleanly.Deep dive 2: Player state machine, shuffle, and live playlist edits
Let's map every state transition before writing code:
User / Audio Event When Stopped When Playing or Paused -------------------------------------------------------------------------------------------------------- Play() Start order[0] (reshuffle first if If Playing: no-op. If Paused: Resume() if shuffle == true) loaded == current, else Start() from 0:00 Next() No-op Advance to pos+1; at end: Stop if RepeatOff, else wrap to 0 (reshuffle if shuffle == true) Previous() No-op Move to pos-1; if pos == 0, restart pos 0 TrackEnded(seq) Ignored If RepeatOne: replay pos; else same as Next() SetShuffle(on) Rebuild order; pos stays -1 Current song keeps playing uninterrupted; remaining entries permute/unpermute around it Current entry deleted No-op Automatically advance to its successor New entry added Included in order Unshuffled: natural slot; Shuffled: random slot in the unplayed suffix so it plays oncetype Player struct { mu sync.Mutex out Output rng *rand.Rand list *Playlist stopWatch func() listOrder []EntryID // playlist order at seenVer songs map[EntryID]SongID // live EntryID -> SongID at seenVer seenVer uint64 order []EntryID // active play sequence (listOrder or a shuffled permutation) pos int // index into order; -1 when Stopped state State // Stopped, Playing, or Paused shuffle bool repeat RepeatMode seq uint64 // incremented on every Start() to filter out stale TrackEnded callbacks loaded EntryID // EntryID currently paused in Output (0 if Next/Prev moved while Paused) }Reconciling live edits without losing our place
Walk through a concrete shuffle edit: suppose
order = [c, a, d, b]withpos = 1(ais playing,calready played). A goroutine deletesaand appendse:Before edit: order = [ c, a, d, b ] (pos = 1 -> playing 'a'; 'c' already heard) ^played ^current 1. Keep surviving entries in existing order: [ c, d, b ]. Count survivors at or before oldPos (1): only 'c' survived -> played = 1. 2. Insert new entry 'e' at a random index k in [played .. len(order)] = [1 .. 3], say k = 2: order = [ c, d, e, b ] ('e' lands in the unplayed suffix, never behind already-heard 'c'!) 3. Set pos = played - 1 = 0; since old current 'a' was deleted, call advance() -> pos = 1 -> starts 'd'!func (p *Player) syncLocked() { if p.list == nil || p.list.Version() == p.seenVer { return } entries, ver := p.list.Snapshot() cur := p.currentLocked() oldOrder, oldPos := p.order, p.pos p.seenVer = ver p.songs = make(map[EntryID]SongID, len(entries)) p.listOrder = make([]EntryID, 0, len(entries)) for _, e := range entries { p.songs[e.ID] = e.Song p.listOrder = append(p.listOrder, e.ID) } if p.shuffle { p.order, p.pos = p.reconcileShuffled(oldOrder, oldPos, entries) } else { p.order = slices.Clone(p.listOrder) p.pos = p.positionInList(cur, oldOrder, oldPos) } if cur != 0 && !p.alive(cur) { p.advanceLocked() // Current entry was removed -> step onto its successor } } func (p *Player) positionInList(cur EntryID, oldOrder []EntryID, oldPos int) int { if cur == 0 { return -1 } if p.alive(cur) { return slices.Index(p.order, cur) } // Find the first surviving entry after oldPos so advanceLocked() lands right on it. for i := oldPos + 1; i < len(oldOrder); i++ { if p.alive(oldOrder[i]) { return slices.Index(p.order, oldOrder[i]) - 1 } } return len(p.order) - 1 } func (p *Player) reconcileShuffled(oldOrder []EntryID, oldPos int, entries []Entry) ([]EntryID, int) { known := make(map[EntryID]bool, len(oldOrder)) order := make([]EntryID, 0, len(entries)) played := 0 for i, id := range oldOrder { known[id] = true if !p.alive(id) { continue } order = append(order, id) if i <= oldPos { played++ } } for _, e := range entries { if !known[e.ID] { k := played + p.rng.Intn(len(order)-played+1) order = slices.Insert(order, k, e.ID) } } return order, played - 1 }Playback controls and uniform Fisher-Yates shuffle
We shuffle using the Fisher-Yates algorithm (walking backward from index
n-1to1and swappingout[i]with a uniformly chosenout[0..i]so everyn!permutation is equally probable inO(n)time). WhenRepeatAllwraps around in shuffle mode, if the entry that just ended (avoid) happens to land atout[0], we swapout[0]with a uniformly chosen index in1 .. len(out)-1(rather than always swapping with the last slot, which would biasavoidtoward playing dead last):func (p *Player) Play() { p.mu.Lock() defer p.mu.Unlock() p.syncLocked() if len(p.order) == 0 || p.state == Playing { return } if p.state == Paused { p.state = Playing if p.loaded == p.currentLocked() { p.out.Resume() // Same song still paused in Output -> resume mid-track } else { p.startLocked() // Next/Prev or edit changed track while paused -> start from 0:00 } return } // Starting fresh from Stopped: generate a fresh shuffle if shuffle mode is active. if p.shuffle { p.order = p.shuffled(p.listOrder, 0, 0) } p.state = Playing p.moveToLocked(0) } func (p *Player) advanceLocked() { if p.pos+1 < len(p.order) { p.moveToLocked(p.pos + 1) return } if p.repeat == RepeatOff || len(p.order) == 0 { p.stopLocked() return } if p.shuffle { p.order = p.shuffled(p.order, 0, p.currentLocked()) } p.moveToLocked(0) } func (p *Player) moveToLocked(idx int) { p.pos = idx if p.state == Playing { p.startLocked() } else { p.loaded = 0 // Paused: remember that Output no longer holds the selected track } } func (p *Player) startLocked() { p.seq++ id := p.order[p.pos] p.loaded = id p.out.Start(p.seq, p.songs[id]) } func (p *Player) shuffled(ids []EntryID, pinFirst, avoidFirst EntryID) []EntryID { out := slices.Clone(ids) for i := len(out) - 1; i > 0; i-- { j := p.rng.Intn(i + 1) out[i], out[j] = out[j], out[i] } if pinFirst != 0 { i := slices.Index(out, pinFirst) out[0], out[i] = out[i], out[0] } else if avoidFirst != 0 && len(out) > 1 && out[0] == avoidFirst { // Swap with a uniformly chosen slot in [1 .. len(out)-1] to avoid back-to-back repeat // without biasing avoidFirst to the tail position. k := 1 + p.rng.Intn(len(out)-1) out[0], out[k] = out[k], out[0] } return out } func (p *Player) SetShuffle(on bool) { p.mu.Lock() defer p.mu.Unlock() p.syncLocked() if on == p.shuffle { return } p.shuffle = on cur := p.currentLocked() if on { p.order = p.shuffled(p.listOrder, cur, 0) } else { p.order = slices.Clone(p.listOrder) } p.pos = slices.Index(p.order, cur) // -1 when Stopped (cur == 0) }Deep dive 3: Concurrency safety, stale `TrackEnded` races, and mutex vs. actor
Five concurrency invariants keep the system race-free and deadlock-free
- Strict lock hierarchy (
Player.mu -> Playlist.mu, never reversed):Playermay callPlaylist.Version()orPlaylist.Snapshot()while holdingp.mu, whereasPlaylistnever callsPlayer(it only performs a non-blocking channel push). A directed acyclic lock graph makes deadlocks impossible. - Never lock two
Playlists simultaneously:Mergesnapshots one at a time. - Defensive copies across boundaries:
Snapshot()clones[]Entry, soPlayerandAutoSavenever read backing memory thatPlaylistis mutating. Notice also that Gomaps and*rand.Randinstances are not safe for concurrent access and are touched strictly under their owner's mutex. - Non-blocking
Outputcalls insidep.mu: Issuingout.Start/Pause/Stopwhile holdingp.muguarantees the audio engine receives commands in the exact order of state transitions, under the contract thatOutputenqueues commands asynchronously and never callsPlayersynchronously. - Sequence numbers defeat stale
TrackEndedraces: If a user clicksNextat the exact millisecond song #1 finishes, the audio thread'sTrackEndedfor song #1 arrives after song #2 has already started (p.seqincremented). Checkingseq != p.seqignores the stale event instead of accidentally skipping song #2!
func (p *Player) TrackEnded(seq uint64) { p.mu.Lock() defer p.mu.Unlock() if seq != p.seq || p.state != Playing { return // Stale callback from an earlier track the user already skipped past } p.syncLocked() if seq != p.seq || p.state != Playing { return // syncLocked() already advanced because this entry was deleted } if p.repeat == RepeatOne { p.startLocked() return } p.advanceLocked() } func (p *Player) Load(list *Playlist) { p.mu.Lock() if p.stopWatch != nil { p.stopWatch() // Acquires old Playlist.mu under Player.mu (valid lock order!) p.stopWatch = nil } p.stopLocked() p.list = list p.seenVer = 0 p.order = nil var ch <-chan struct{} if list != nil { // Subscribe BEFORE syncLocked() so an edit happening right as we load // either appears in syncLocked()'s snapshot or leaves a signal in ch! var cancel func() ch, cancel = list.Subscribe() p.stopWatch = cancel p.syncLocked() } p.mu.Unlock() if ch != nil { go func() { for range ch { p.Refresh() // Locks p.mu and runs p.syncLocked() } }() } }Alternative concurrency model — Mutex per object vs. Actor goroutine
An actor gives one dedicated goroutine exclusive ownership of
Playerfields inside afor { select { ... } }loop, communicating strictly over channels:Dimension Mutex per Object (Chosen) Actor Goroutine for Player --------------------------------------------------------------------------------------------------- Data-race prevention Enforced by mutex discipline By construction (single owner goroutine) Per-call overhead Uncontended mutex (~15-30 ns) 2 channel ops + scheduler hop (~300+ ns) Lifecycle cleanup Zero background goroutine if idle Must close quit chan to avoid goroutine leak Deadlock pitfall Synchronous callback under lock Handler sending to its own command chan Best fit Shared read-heavy state (Playlist) Event-loop state machines (Player)Either model works cleanly for
Player;Playlistshould remainRWMutex-based so concurrent readers (Player, UI,SavePlaylist) never serialize behind a single channel queue.- Strict lock hierarchy (
Persistence: debounced, crash-safe atomic JSON writes
Overwriting
workout.jsondirectly in place corrupts the file if power fails mid-write, and writing to a fixedworkout.json.tmpcorrupts data when a manual export races an autosave. Instead, we snapshot underRLock(~29 us), release the lock before JSON marshalling and disk I/O, write to a uniquely named temporary file in the same directory, flush bytes to disk viaSync()(fsync), and perform an atomic POSIXos.Rename:type playlistFile struct { Name string `json:"name"` Unique bool `json:"unique"` LastID EntryID `json:"last_id"` Entries []Entry `json:"entries"` } func SavePlaylist(pl *Playlist, path string) error { pl.mu.RLock() snap := playlistFile{ Name: pl.name, Unique: pl.unique, LastID: pl.lastID, Entries: slices.Clone(pl.entries), } pl.mu.RUnlock() // Release lock before CPU- and disk-heavy JSON + fsync! data, err := json.Marshal(snap) if err != nil { return err } return writeFileAtomic(path, data) } func LoadPlaylist(path string) (*Playlist, error) { data, err := os.ReadFile(path) if err != nil { return nil, err } var f playlistFile if err := json.Unmarshal(data, &f); err != nil { return nil, err } pl := NewPlaylist(f.Name, f.Unique) pl.entries = f.Entries pl.lastID = f.LastID for _, e := range pl.entries { pl.counts[e.Song]++ if e.ID > pl.lastID { pl.lastID = e.ID // Guard against hand-edited JSON causing colliding future EntryIDs } } return pl, nil } func writeFileAtomic(path string, data []byte) error { f, err := os.CreateTemp(filepath.Dir(path), filepath.Base(path)+".*.tmp") if err != nil { return err } tmp := f.Name() if _, err := f.Write(data); err != nil { f.Close() os.Remove(tmp) return err } if err := f.Sync(); err != nil { f.Close() os.Remove(tmp) return err } if err := f.Close(); err != nil { os.Remove(tmp) return err } return os.Rename(tmp, path) // Atomic swap on POSIX when temp file shares directory }Debounced
AutoSave: Saving on every singleAddwould trigger 10,000fsynccalls during a bulk import. Debouncing sleeps for a short window (for example500 ms) after receiving a change signal so a burst of edits collapses into at most two disk writes, andstop()waits for any in-flight write to finish before shutdown writes one final snapshot:func AutoSave(pl *Playlist, path string, delay time.Duration) (stop func()) { ch, cancel := pl.Subscribe() done := make(chan struct{}) go func() { defer close(done) for range ch { time.Sleep(delay) if err := SavePlaylist(pl, path); err != nil { log.Printf("autosave %s: %v", path, err) } } }() return func() { cancel() <-done // Wait so an older autosave cannot rename over our final shutdown SavePlaylist! } }(If persistence later moves to SQLite/PostgreSQL for huge playlists, store order using gapped integer ranks
1024, 2048, 3072or fractional lexicographic keys"a", "am", "b"so inserting or moving one track updatesO(1)rows instead of renumberingO(N)rows.)Unit test plan and scaling/failure handling
Deterministic unit & race-detector test suite (
go test -race -count=3 ./...)Test Category Behaviors Verified ----------------------------------------------------------------------------------------------------- Playlist CRUD Add, Insert, Remove, Move boundaries; double Remove -> ErrNotFound; out-of-bounds Insert/Move -> ErrOutOfRange; Move to current index is a version-preserving no-op Deduplication Unique mode rejects duplicate SongID; SetUnique(true) keeps first copy & updates counts; removing last copy allows re-adding; SetUnique bumps version even if 0 dropped Merge KeepAll, KeepFirst, KeepLast with duplicates in both inputs; empty lists; source immutability; self-merge Merge(x, x) completes with zero deadlock Navigation & Pause Next/Prev wrap vs stop; RepeatOne loops on TrackEnded yet advances on Next; Previous at index 0 restarts; Next while Paused stays Paused and Play starts at 0:00 Shuffle & Live Edits Seeded shuffle visits every entry once per cycle; SetShuffle preserves playing song; deleting playing copy skips to successor while sparing duplicate copy; adding song mid-shuffle inserts into unplayed suffix; stale TrackEnded(oldSeq) is ignored Concurrency & I/O 8 goroutines editing + navigating + firing TrackEnded under -race; Save/Load round trip preserves counts & LastID; concurrent SavePlaylist calls leave valid JSONfunc TestMergePolicies(t *testing.T) { a, _ := newList(false, "x", "y", "x", "z") b, _ := newList(false, "y", "w", "x") cases := []struct { policy DupPolicy want []SongID }{ {KeepAll, []SongID{"x", "y", "x", "z", "y", "w", "x"}}, {KeepFirst, []SongID{"x", "y", "z", "w"}}, {KeepLast, []SongID{"z", "y", "w", "x"}}, } for _, tc := range cases { got := songsOf(Merge("merged", a, b, tc.policy)) if !slices.Equal(got, tc.want) { t.Errorf("policy %v: got %v, want %v", tc.policy, got, tc.want) } } } func TestRemovingPlayingEntrySkipsToSuccessor(t *testing.T) { pl, ids := newList(false, "a", "b", "c") p, _ := newPlayer(pl) // Injects recording fakeOutput + rand.New(rand.NewSource(1)) p.Play() p.Next() // Now playing ids[1] ("b") _ = pl.Remove(ids[1]) // Delete "b" while it is playing if song, st := p.Current(); song != "c" || st != Playing { t.Fatalf("expected 'c' Playing after removing 'b', got %q (%v)", song, st) } _ = pl.Remove(ids[2]) // Delete last song "c" with RepeatOff -> must stop cleanly if _, st := p.Current(); st != Stopped { t.Fatalf("expected Stopped after removing final entry, got %v", st) } }Scaling past 1M entries & failure resilience
- Scaling beyond
1,000,000entries: (1) Emit structured edit deltas (Inserted,Removed,Moved) soPlayerpatchesorderincrementally instead of rebuildingO(N); (2) swap[]Entryfor an order-statistic tree (a balanced binary search tree augmented with subtree node counts so rank lookup, insert, delete, and move all run inO(log N)time) paired withmap[EntryID]*node. - Failure handling: Unplayable/missing audio files trigger an error callback that skips to the next entry and halts after
len(order)consecutive failures (preventing infinite spin on an unplugged drive); stray*.tmpfiles from power cuts are cleaned on startup while the prior JSON remains intact; disk-full errors inAutoSavesurface a UI warning while preserving in-memory playback.
- Scaling beyond
Summary of key design trade-offs
EntryIDtickets vs. bareSongIDs: Adds an 8-byte ID per row so duplicate songs, removals, and concurrent inserts never corrupt what is currently playing.- Contiguous
[]Entryslice +countsmap vs. linked list or tree: TradesO(N)shifts (~4.5 usat10kitems) forO(1)index reads,O(1)duplicate checks, minimal memory, and straightforward code. - Pure
Mergeover sequential snapshots vs. in-place dual-lock merge: Copies both slices (O(N + M)) to guarantee zero partial failures and zeroMerge(x, x)or AB-BA lock deadlocks. - Version-checked
Playerorder reconciliation vs. static play queue: Costs~0.9 msafter an edit so live deletions and additions immediately reflect in playback without destroying the user's original playlist order. - One-way lock hierarchy (
Player -> Playlist) +seqcounters vs. callbacks: Eliminates deadlocks and drops staleTrackEndedevents at the cost of a single monotonicuint64. - Debounced atomic temp-file rename vs. per-edit in-place writes: Risks losing up to one debounce window (
~500 ms) on sudden power loss in exchange for zero torn JSON files and 1,000x fewer disk flushes during imports.
Intuition & how it works
Think of the music player like a café jukebox where every slot in a playlist binder gets its own permanent numbered ticket (EntryID), while the turntable (Player) keeps a private photocopy of the ticket order stamped with a version number: even if a listener adds "Bohemian Rhapsody" twice, the two slots hold distinct tickets (EntryID 1 and EntryID 3), so deleting ticket #1 never rips the needle off ticket #3 while it is playing. Whenever a button is pressed, Player peeks at Playlist.Version() in O(1) time: if nothing changed, Next simply increments an integer index in ~75 ns; if another goroutine (a lightweight concurrent execution thread managed by Go) edited the playlist, Player grabs a fresh Snapshot() copy, reconciles its play order without interrupting the active track, and numbers every audio Start(seq, song) command with a rising sequence number seq so late "track finished" callbacks from skipped songs are harmlessly ignored.
Why do the obvious designs fail? Storing a playlist as a plain []SongID slice makes "remove song X" and "currently playing song X" ambiguous whenever X appears more than once. Tracking playback with a bare integer index into the playlist silently shifts to the wrong song whenever someone inserts or deletes a track earlier in the list, and shuffling the playlist slice in place permanently destroys the user's saved track order. Finally, having Playlist invoke synchronous observer callbacks on Player while holding its lock creates an instant deadlock (two goroutines waiting on each other's locks forever) the moment Player calls back into Playlist to read tracks.
Let's trace a 4-entry playlist through duplicate insertion, shuffle, a live deletion, and a concurrent audio callback:
1. Build playlist with duplicates (unique = false):
Add("x") -> Entry{1, "x"}
Add("y") -> Entry{2, "y"}
Add("x") -> Entry{3, "x"} (second copy of "x" gets its own EntryID = 3!)
Add("z") -> Entry{4, "z"} -> entries = [1:x, 2:y, 3:x, 4:z], version = 5
2. Play & toggle shuffle while Entry 3 ("x") is playing:
Play() -> Next() -> Next() -> pos = 2, playing Entry 3 ("x"), seq = 3.
SetShuffle(true) -> Fisher-Yates permutes listOrder and pins Entry 3 at index 0:
order = [3, 4, 1, 2], pos = 0 -> Entry 3 keeps playing uninterrupted; original listOrder intact!
3. Concurrent edit deletes playing Entry 3 while sparing duplicate Entry 1:
pl.Remove(3) -> entries = [1:x, 2:y, 4:z], version = 6, pushes 1-slot signal on subscriber chan.
Player syncLocked() sees version 6 != seenVer 5 -> Entry 3 is gone, successor in old order is Entry 4:
order = [4, 1, 2], pos = 0 -> calls out.Start(seq=4, "z")! Entry 1 ("x") remains queued at index 1.
4. Stale audio callback arrives late:
Audio thread fires TrackEnded(seq=3) for old Entry 3 -> seq 3 != current p.seq 4 -> ignored!
Key trade-offs
- Unique
EntryIDper occurrence vs. bare[]SongID. Assigning an 8-byteEntryIDto each playlist slot makes duplicate tracks, removals, moves, and"currently playing"references unambiguous even while other goroutines insert rows concurrently. A bare[]SongIDsaves 8 bytes per item but breaks duplicate handling and index stability. - Contiguous
[]Entryslice +countsmap vs. linked list vs. balanced tree. A Go slice givesO(1)index reads, cache-friendly snapshots (~29 usat10kitems),O(1)duplicate checks viacounts[SongID], and~4.5 usO(N)shifts. A doubly linked list optimizes onlyRemove(EntryID)toO(1)while degrading index reads toO(N)and tripling pointer memory. An order-statistic tree (a balanced binary search tree storing subtree sizes forO(log N)index access, insert, and delete) only pays off past~1,000,000entries. - Version-reconciled play order vs. static queue copied once at
Play(). Copying tracks once whenPlay()is pressed ignores live edits, so deleted songs still play and newly added songs never play. ReconcilingorderwheneverPlaylist.Version()advances matches user expectations at the cost of a< 1 msO(N)pass after edits. - One-way mutex hierarchy (
Player -> Playlist) vs. an actor goroutine. ProtectingPlaylistwith async.RWMutex(allowing concurrent readers or one exclusive writer) andPlayerwith async.Mutexadds only~20 nsper call and prevents deadlocks because locks are acquired strictly top-down (Player, thenPlaylist). An actor (one dedicated goroutine owningPlayerstate inside aselectloop over channels) eliminatesPlayermutexes altogether, trading channel-hop latency and goroutine shutdown bookkeeping for single-threaded state logic. - Calling
OutputinsidePlayer.muvs. after unlocking. IssuingStart/Pause/Stopwhile holdingPlayer.muguarantees the audio engine receives commands in exact state-transition order, requiringOutputmethods to be non-blocking and never call back intoPlayersynchronously. - Pure
Mergeover sequential snapshots vs. locking both playlists in place. Snapshottingaand thenbinto a new*Playlist(O(N + M)memory) avoids partial mutations and prevents AB-BA deadlocks as well asMerge(x, x)self-deadlocks on Go's non-reentrantsync.RWMutex(which deadlocks if the same goroutine callsRLocktwice onxwhen a writer arrives in between). - Debounced atomic JSON files vs. immediate per-edit writes or SQLite. Debouncing (coalescing rapid edits over a short window like
500 ms) plus writing a unique temp file, flushing viafsync, and running an atomicos.Renameavoids torn files and turns a10k-track import into 1–2 disk writes, at the risk of losing the final500 msof edits on sudden power loss.
Common mistakes
- Passing raw slice indices or
SongIDs toRemoveandMove: Song IDs delete the wrong copy when duplicates exist, and UI slice indices point to the wrong row if another goroutine inserted above them milliseconds earlier. - Mutating
Playlist.entriesduringSetShuffle(true): Shuffling the underlying playlist slice destroys the user's curated order soSetShuffle(false)can never restore it; always keep a separateorder []EntryIDinsidePlayer. - Broken shuffle algorithms: Sorting with a random comparator violates strict weak ordering and produces biased permutations, while picking a random unplayed index on every
NexttakesO(N)per step and leavesPreviousundefined. Use Fisher-Yates shuffle (O(N), uniform1/N!) and, when avoiding a boundary repeat onRepeatAll, swap index0with a random index in1 .. N-1rather than hard-codingN-1. - Calling
Snapshot()on every button press just to check for edits: Copying10,000entries on everyNextallocates240 KBneedlessly; checkPlaylist.Version() == seenVer(O(1)) first. - Subscribing after
syncLocked()inLoad()or failing to checklist == nil: Subscribing after snapshotting opens a race gap where a concurrent edit's signal is missed, andLoad(nil)panics ifSubscribe()is called unconditionally. - Exposing internal slices/maps directly or touching
*rand.Randwithout a lock: Returningpl.entrieswithoutslices.Cloneor calling Go's non-thread-safe*rand.Randfrom concurrent goroutines triggersgo test -racefailures and runtime crashes. - Ignoring stale
TrackEndedevents or writing save files to a fixedpath + ".tmp": Without aseqcheck, pressingNextas a song ends skips two tracks; with a fixed.tmpfilename, two overlapping saves truncate each other's bytes.
Follow-up questions
- How would you synchronize concurrent playlist edits—including offline changes—across multiple user devices? Promote
EntryIDto a globally unique identifier (such as(device_id, monotonic_counter)or UUIDv7) and log relative operations—InsertAfter(newEntry, prevEntryID),MoveAfter(entryID, prevEntryID),Remove(entryID)—rather than brittle array indices. With a central cloud server, devices push pending operations with optimistic concurrency (base_version), the server orders them monotonically, and clients rebase local queues (Removewins over a concurrentMoveof the sameEntryID). For peer-to-peer offline sync without a central coordinator, assign each entry a fractional lexicographic position with(timestamp, device_id)tie-breaking—a sequence CRDT (Conflict-Free Replicated Data Type, a data structure whose concurrent replicas mathematically converge to the exact same order without central locks). - If listeners feel true uniform shuffle clusters tracks by the same artist together, how would you redesign shuffle ordering? True Fisher-Yates shuffle is mathematically uniform, which naturally produces clusters that humans perceive as "non-random". Group playlist entries by
Artist, shuffle within each artist group, space an artist'sktracks evenly across[0, 1)usingpos_i = (offset + i + jitter) / k(with a random per-artistoffsetand small boundedjitter), and sort all entries bypos_iinO(N log N)time. Because this replaces onlyshuffled(),Previous,RepeatAll, and live edit reconciliation continue to work unchanged—just document explicitly that uniformity was traded for perceptual variety. - How would you add a transient 'Play Next' queue alongside the active playlist without mutating saved playlist order? Add a separate FIFO
upNext []SongIDslice insidePlayerplus a boundedplayedHistory []SongIDstack. WheneverNextorTrackEndedadvances (outsideRepeatOne), pop fromupNextfirst if non-empty before advancingposin the playlist'sorder. BecauseupNextholdsSongIDs directly rather than playlistEntryIDs, toggling playlist shuffle or deleting a row from the background playlist never unexpectedly drops tracks the user explicitly queued up next.
Follow-up questions
- How would you synchronize concurrent playlist edits—including offline changes—across multiple user devices?
- If listeners feel true uniform shuffle clusters tracks by the same artist together, how would you redesign shuffle ordering?
- How would you add a transient 'Play Next' queue alongside the active playlist without mutating saved playlist order?
Similar questions
- Role Motivation, Cultural Adaptability, and Commercial Ownership
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests
- Diagnosing and Optimizing Full-Stack Web Request Latency