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

  1. 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 Playlist instances, and a Player. 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 Output interface), network audio streaming, and multi-device cloud sync (covered as a follow-up).

    Explicit product & behavioral policies

    • Duplicates use unique slot tickets (EntryID), not bare SongIDs: 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 monotonic EntryID. Removing, moving, or tracking the "currently playing" item always targets an EntryID—never a SongID (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 (unique mode): When unique == true, Add and Insert reject an already-present SongID with ErrDuplicate in O(1) time. Toggling SetUnique(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 Merge with three policies: Merge(name, a, b, policy) returns a brand-new *Playlist preserving relative order without mutating a or b, supporting:
      • KeepAll: concatenate a followed by b (result has unique = false).
      • KeepFirst: keep each distinct song once at its earliest position in a-then-b (unique = true).
      • KeepLast: keep each distinct song once at its latest position in a-then-b (unique = true).
    • Crisp Player edge-case semantics:
      • Next and Previous while Paused move the cursor while staying Paused (pressing Play then starts the newly selected track from 0:00).
      • RepeatOne replays a track automatically when it finishes naturally (TrackEnded), whereas manually pressing Next still advances to the next track.
      • Previous on the first track in the play order restarts that track from 0:00.
      • Removing the currently playing EntryID automatically skips to the entry that immediately followed it (stopping if it was last and RepeatOff is set).
      • Toggling Shuffle on 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,000 entries (100x faster than the ~100 ms human 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.
  2. 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 ns
    

    What the numbers tell us

    1. Contiguous O(N) slice shifts (~4.5 us) are completely invisible at N = 10,000. CPU cache locality makes shifting 240 KB of contiguous memory faster and far simpler than maintaining a doubly linked list or balanced tree.
    2. 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.
    3. Know the scaling cliff: Around N = 1,000,000 entries, linear reconcile approaches ~90 ms, at which point incremental edit deltas and an O(log N) tree become justified.
  3. Public Go API: separating data (`Playlist`) from playback (`Player`)

    We separate pure data (Playlist) from the playback state machine (Player). Crucially, Playlist does not import or reference Player—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 alongside Snapshot(): On every button press (Next, Pause), Player checks pl.Version() == p.seenVer in O(1) without allocating memory, calling Snapshot() (O(N)) only when an edit actually occurred.
    • Why Output and *rand.Rand are injected: Passing a recording fake Output and a seeded rand.New(rand.NewSource(1)) makes every playback and shuffle test 100% deterministic.
  4. Data structures and time/space complexity

    Inside Playlist, we pair a contiguous []Entry slice with a map[SongID]int frequency table protected by a sync.RWMutex (a reader-writer mutual-exclusion lock that lets many goroutines read concurrently via RLock, while giving a writer exclusive access via Lock):

    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 losing O(1) index reads and tripling memory overhead; []Entry wins hands-down at N <= 10,000.

  5. 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, benchmarks
    

    Notice the strict one-way call arrow: Player and Store call Playlist, while Playlist never calls Player or Store. When Playlist changes, it performs a non-blocking send on a 1-element buffered chan struct{}. Because the buffer size is 1, a slow subscriber never blocks an edit, and 1,000 rapid edits coalesce into a single wake-up signal.

  6. Deep dive 1: Playlist edits, optional deduplication, and `Merge`

    Every write method acquires pl.mu.Lock(), validates arguments, mutates entries and counts atomically together, increments version, 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 Merge and why sequential snapshots avoid self-deadlock

    Trace Merge on a = [x, y, x, z] and b = [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 a and b one at a time instead of locking both? First, locking a then b while another goroutine calls Merge(..., b, a, ...) causes a classic AB-BA deadlock. Second, even Merge("copy", x, x, KeepAll) would deadlock under two nested RLock() calls! Go's sync.RWMutex is not reentrant (the same goroutine may not acquire a second read lock while holding one): if a writer calls x.mu.Lock() between the first RLock() and the second RLock(), Go blocks new readers behind the waiting writer, while the writer waits for the first RLock() to release—freezing both forever. Sequential Snapshot() calls eliminate both traps cleanly.

  7. 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 once
    
    type 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] with pos = 1 (a is playing, c already played). A goroutine deletes a and appends e:

    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-1 to 1 and swapping out[i] with a uniformly chosen out[0..i] so every n! permutation is equally probable in O(n) time). When RepeatAll wraps around in shuffle mode, if the entry that just ended (avoid) happens to land at out[0], we swap out[0] with a uniformly chosen index in 1 .. len(out)-1 (rather than always swapping with the last slot, which would bias avoid toward 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)
    }
    
  8. Deep dive 3: Concurrency safety, stale `TrackEnded` races, and mutex vs. actor

    Five concurrency invariants keep the system race-free and deadlock-free

    1. Strict lock hierarchy (Player.mu -> Playlist.mu, never reversed): Player may call Playlist.Version() or Playlist.Snapshot() while holding p.mu, whereas Playlist never calls Player (it only performs a non-blocking channel push). A directed acyclic lock graph makes deadlocks impossible.
    2. Never lock two Playlists simultaneously: Merge snapshots one at a time.
    3. Defensive copies across boundaries: Snapshot() clones []Entry, so Player and AutoSave never read backing memory that Playlist is mutating. Notice also that Go maps and *rand.Rand instances are not safe for concurrent access and are touched strictly under their owner's mutex.
    4. Non-blocking Output calls inside p.mu: Issuing out.Start/Pause/Stop while holding p.mu guarantees the audio engine receives commands in the exact order of state transitions, under the contract that Output enqueues commands asynchronously and never calls Player synchronously.
    5. Sequence numbers defeat stale TrackEnded races: If a user clicks Next at the exact millisecond song #1 finishes, the audio thread's TrackEnded for song #1 arrives after song #2 has already started (p.seq incremented). Checking seq != p.seq ignores 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 Player fields inside a for { 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; Playlist should remain RWMutex-based so concurrent readers (Player, UI, SavePlaylist) never serialize behind a single channel queue.

  9. Persistence: debounced, crash-safe atomic JSON writes

    Overwriting workout.json directly in place corrupts the file if power fails mid-write, and writing to a fixed workout.json.tmp corrupts data when a manual export races an autosave. Instead, we snapshot under RLock (~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 via Sync() (fsync), and perform an atomic POSIX os.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 single Add would trigger 10,000 fsync calls during a bulk import. Debouncing sleeps for a short window (for example 500 ms) after receiving a change signal so a burst of edits collapses into at most two disk writes, and stop() 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, 3072 or fractional lexicographic keys "a", "am", "b" so inserting or moving one track updates O(1) rows instead of renumbering O(N) rows.)

  10. 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 JSON
    
    func 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,000 entries: (1) Emit structured edit deltas (Inserted, Removed, Moved) so Player patches order incrementally instead of rebuilding O(N); (2) swap []Entry for an order-statistic tree (a balanced binary search tree augmented with subtree node counts so rank lookup, insert, delete, and move all run in O(log N) time) paired with map[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 *.tmp files from power cuts are cleaned on startup while the prior JSON remains intact; disk-full errors in AutoSave surface a UI warning while preserving in-memory playback.
  11. Summary of key design trade-offs

    • EntryID tickets vs. bare SongIDs: Adds an 8-byte ID per row so duplicate songs, removals, and concurrent inserts never corrupt what is currently playing.
    • Contiguous []Entry slice + counts map vs. linked list or tree: Trades O(N) shifts (~4.5 us at 10k items) for O(1) index reads, O(1) duplicate checks, minimal memory, and straightforward code.
    • Pure Merge over sequential snapshots vs. in-place dual-lock merge: Copies both slices (O(N + M)) to guarantee zero partial failures and zero Merge(x, x) or AB-BA lock deadlocks.
    • Version-checked Player order reconciliation vs. static play queue: Costs ~0.9 ms after 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) + seq counters vs. callbacks: Eliminates deadlocks and drops stale TrackEnded events at the cost of a single monotonic uint64.
    • 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 EntryID per occurrence vs. bare []SongID. Assigning an 8-byte EntryID to each playlist slot makes duplicate tracks, removals, moves, and "currently playing" references unambiguous even while other goroutines insert rows concurrently. A bare []SongID saves 8 bytes per item but breaks duplicate handling and index stability.
  • Contiguous []Entry slice + counts map vs. linked list vs. balanced tree. A Go slice gives O(1) index reads, cache-friendly snapshots (~29 us at 10k items), O(1) duplicate checks via counts[SongID], and ~4.5 us O(N) shifts. A doubly linked list optimizes only Remove(EntryID) to O(1) while degrading index reads to O(N) and tripling pointer memory. An order-statistic tree (a balanced binary search tree storing subtree sizes for O(log N) index access, insert, and delete) only pays off past ~1,000,000 entries.
  • Version-reconciled play order vs. static queue copied once at Play(). Copying tracks once when Play() is pressed ignores live edits, so deleted songs still play and newly added songs never play. Reconciling order whenever Playlist.Version() advances matches user expectations at the cost of a < 1 ms O(N) pass after edits.
  • One-way mutex hierarchy (Player -> Playlist) vs. an actor goroutine. Protecting Playlist with a sync.RWMutex (allowing concurrent readers or one exclusive writer) and Player with a sync.Mutex adds only ~20 ns per call and prevents deadlocks because locks are acquired strictly top-down (Player, then Playlist). An actor (one dedicated goroutine owning Player state inside a select loop over channels) eliminates Player mutexes altogether, trading channel-hop latency and goroutine shutdown bookkeeping for single-threaded state logic.
  • Calling Output inside Player.mu vs. after unlocking. Issuing Start/Pause/Stop while holding Player.mu guarantees the audio engine receives commands in exact state-transition order, requiring Output methods to be non-blocking and never call back into Player synchronously.
  • Pure Merge over sequential snapshots vs. locking both playlists in place. Snapshotting a and then b into a new *Playlist (O(N + M) memory) avoids partial mutations and prevents AB-BA deadlocks as well as Merge(x, x) self-deadlocks on Go's non-reentrant sync.RWMutex (which deadlocks if the same goroutine calls RLock twice on x when 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 via fsync, and running an atomic os.Rename avoids torn files and turns a 10k-track import into 1–2 disk writes, at the risk of losing the final 500 ms of edits on sudden power loss.

Common mistakes

  • Passing raw slice indices or SongIDs to Remove and Move: 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.entries during SetShuffle(true): Shuffling the underlying playlist slice destroys the user's curated order so SetShuffle(false) can never restore it; always keep a separate order []EntryID inside Player.
  • Broken shuffle algorithms: Sorting with a random comparator violates strict weak ordering and produces biased permutations, while picking a random unplayed index on every Next takes O(N) per step and leaves Previous undefined. Use Fisher-Yates shuffle (O(N), uniform 1/N!) and, when avoiding a boundary repeat on RepeatAll, swap index 0 with a random index in 1 .. N-1 rather than hard-coding N-1.
  • Calling Snapshot() on every button press just to check for edits: Copying 10,000 entries on every Next allocates 240 KB needlessly; check Playlist.Version() == seenVer (O(1)) first.
  • Subscribing after syncLocked() in Load() or failing to check list == nil: Subscribing after snapshotting opens a race gap where a concurrent edit's signal is missed, and Load(nil) panics if Subscribe() is called unconditionally.
  • Exposing internal slices/maps directly or touching *rand.Rand without a lock: Returning pl.entries without slices.Clone or calling Go's non-thread-safe *rand.Rand from concurrent goroutines triggers go test -race failures and runtime crashes.
  • Ignoring stale TrackEnded events or writing save files to a fixed path + ".tmp": Without a seq check, pressing Next as a song ends skips two tracks; with a fixed .tmp filename, 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 EntryID to 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 (Remove wins over a concurrent Move of the same EntryID). 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's k tracks evenly across [0, 1) using pos_i = (offset + i + jitter) / k (with a random per-artist offset and small bounded jitter), and sort all entries by pos_i in O(N log N) time. Because this replaces only shuffled(), 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 []SongID slice inside Player plus a bounded playedHistory []SongID stack. Whenever Next or TrackEnded advances (outside RepeatOne), pop from upNext first if non-empty before advancing pos in the playlist's order. Because upNext holds SongIDs directly rather than playlist EntryIDs, toggling playlist shuffle or deleting a row from the background playlist never unexpectedly drops tracks the user explicitly queued up next.

Follow-up questions

Similar questions

More Paramount Commerce interview questions

All 2 Paramount Commerce questions →