Design an In-Memory Music Player and Playlist Engine in Go
System DesignModel answerLast updated
Design an in-memory music player engine in Go supporting playlists, deduplication, list merging, playback operations, and safe concurrent access.
Architect and implement an object-oriented, in-memory audio player component in Go.
Core Features & Design Specs:
- Domain Abstractions:
- Define types for
Song,Playlist, andPlayer. - Separate song metadata from playlist track instances so duplicate song occurrences remain individually addressable.
- Define types for
- Playlist Operations:
- Provide methods to append tracks, remove entries by index, and reorder items within a playlist.
- Support configurable duplicate rules (
AllowDuplicatesvsRejectDuplicates) along with explicit deduplication. - Provide a mechanism to merge two playlists into a new playlist according to policy options (e.g., standard concatenation, unique track filtering, or alternating elements), maintaining item ordering without incurring deadlocks or state contamination.
- Playback Control Engine:
- Implement control workflows:
Play,Pause,Next,Previous,SetShuffle, and repeat variations (RepeatOff,RepeatOne,RepeatAll). - Decouple hardware playback mechanisms behind an audio driver abstraction (e.g.,
AudioOutput).
- Implement control workflows:
- Concurrency & Thread Safety:
- Guarantee thread safety for simultaneous mutations (inserts, deletes, reordering) while active playback or snapshot processing is underway.
- Outline your strategy for lock management, memory snapshots, and deadlock prevention.
- Complexity & Testing:
- Document time and space complexities for each operation.
- Summarize key unit testing scenarios for edge behaviors (empty lists, out-of-bounds indices, repeat loops, shuffle mutations).
Hints
Hint 1
Assign each inserted track a unique incrementing sequence ID within the playlist to distinguish separate insertions of identical songs.
Hint 2
To prevent deadlocks during multi-playlist operations like merging, acquire brief snapshot copies of each source independently rather than locking multiple playlists simultaneously.
Hint 3
Maintain a monotonic version number on playlists. This allows the playback engine to refresh its internal index state lazily when mutations occur.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Architecture & Domain Design
An extensible player design decouples track metadata from playlist entries and hardware output execution. We divide the system into four core building blocks:
Song: Static track metadata (ID, title, artist, duration).Playlist: An ordered sequence of track references protected by a read-write lock, maintaining occurrence counts and mutation versioning.Player: A state machine that tracks active playback state, queue ordering (including shuffle permutations), cursor position, and repeat modes.AudioOutputInterface: A decoupled target interface for audio hardware or driver backends.
Entry Identification Strategy
Allowing identical songs to exist multiple times within a single playlist creates ambiguity if removal operations target raw SongID values. To resolve this, each track addition generates a PlaylistEntry wrapping the SongID alongside a unique, monotonic EntryID.
package musicplayer
import (
"errors"
"math/rand"
"sync"
"time"
)
type SongID string
type EntryID uint64
type Song struct {
ID SongID
Title string
Artist string
Duration time.Duration
}
type PlaylistEntry struct {
ID EntryID
SongID SongID
}
type DupPolicy int
const (
AllowDuplicates DupPolicy = iota
RejectDuplicates
)
var (
ErrDuplicateExists = errors.New("song already exists in playlist")
ErrIndexOutOfBounds = errors.New("playlist index out of bounds")
ErrEmptyPlaylist = errors.New("playlist is empty")
)
2. Playlist State & Thread-Safe Operations
Playlist encapsulates entry updates using sync.RWMutex. We track track counts via a map[SongID]int to enable $O(1)$ duplicate enforcement, and bump a version counter on every mutation to allow downstream components to detect updates.
type Playlist struct {
mu sync.RWMutex
ID string
Name string
entries []PlaylistEntry
counts map[SongID]int
policy DupPolicy
nextID EntryID
version uint64
}
func NewPlaylist(id, name string, policy DupPolicy) *Playlist {
return &Playlist{
ID: id,
Name: name,
entries: make([]PlaylistEntry, 0),
counts: make(map[SongID]int),
policy: policy,
}
}
func (p *Playlist) Add(songID SongID) (EntryID, error) {
p.mu.Lock()
defer p.mu.Unlock()
if p.policy == RejectDuplicates && p.counts[songID] > 0 {
return 0, ErrDuplicateExists
}
p.nextID++
entry := PlaylistEntry{ID: p.nextID, SongID: songID}
p.entries = append(p.entries, entry)
p.counts[songID]++
p.version++
return entry.ID, nil
}
func (p *Playlist) RemoveAt(index int) error {
p.mu.Lock()
defer p.mu.Unlock()
if index < 0 || index >= len(p.entries) {
return ErrIndexOutOfBounds
}
removed := p.entries[index]
p.counts[removed.SongID]--
if p.counts[removed.SongID] <= 0 {
delete(p.counts, removed.SongID)
}
p.entries = append(p.entries[:index], p.entries[index+1:]...)
p.version++
return nil
}
func (p *Playlist) Move(from, to int) error {
p.mu.Lock()
defer p.mu.Unlock()
n := len(p.entries)
if from < 0 || from >= n || to < 0 || to >= n {
return ErrIndexOutOfBounds
}
if from == to {
return nil
}
item := p.entries[from]
if from < to {
copy(p.entries[from:to], p.entries[from+1:to+1])
} else {
copy(p.entries[to+1:from+1], p.entries[to:from])
}
p.entries[to] = item
p.version++
return nil
}
func (p *Playlist) Dedupe() {
p.mu.Lock()
defer p.mu.Unlock()
seen := make(map[SongID]bool)
filtered := make([]PlaylistEntry, 0, len(p.entries))
for _, entry := range p.entries {
if !seen[entry.SongID] {
seen[entry.SongID] = true
filtered = append(filtered, entry)
}
}
p.entries = filtered
p.counts = make(map[SongID]int, len(seen))
for songID := range seen {
p.counts[songID] = 1
}
p.version++
}
// Snapshot yields a point-in-time slice copy alongside the mutation version.
func (p *Playlist) Snapshot() ([]PlaylistEntry, uint64) {
p.mu.RLock()
defer p.mu.RUnlock()
cp := make([]PlaylistEntry, len(p.entries))
copy(cp, p.entries)
return cp, p.version
}
3. Merging Engine & Lock-Free Compositions
Acquiring locks on multiple playlist instances at once can trigger cyclic lock waiting deadlocks under concurrent cross-merges (e.g., Goroutine 1 locks $A \to B$ while Goroutine 2 locks $B \to A$).
To eliminate deadlocks, Merge extracts isolated snapshots of each source playlist sequentially under read locks, then constructs the combined output playlist.
type MergeStrategy int
const (
MergeSequential MergeStrategy = iota
MergeUniqueOnly
MergeInterleave
)
func Merge(a, b *Playlist, strategy MergeStrategy, newID, newName string) *Playlist {
entriesA, _ := a.Snapshot()
entriesB, _ := b.Snapshot()
policy := AllowDuplicates
if strategy == MergeUniqueOnly {
policy = RejectDuplicates
}
result := NewPlaylist(newID, newName, policy)
appendEntry := func(e PlaylistEntry) {
_, _ = result.Add(e.SongID)
}
switch strategy {
case MergeInterleave:
maxLen := len(entriesA)
if len(entriesB) > maxLen {
maxLen = len(entriesB)
}
for i := 0; i < maxLen; i++ {
if i < len(entriesA) {
appendEntry(entriesA[i])
}
if i < len(entriesB) {
appendEntry(entriesB[i])
}
}
case MergeUniqueOnly, MergeSequential:
for _, e := range entriesA {
appendEntry(e)
}
for _, e := range entriesB {
appendEntry(e)
}
}
return result
}
4. Playback Controller State Machine
The Player binds an output interface to active playlist snapshot views, managing shuffle permutation arrays and current state transitions (Stopped, Playing, Paused).
type AudioOutput interface {
PlayTrack(songID SongID) error
PauseTrack() error
ResumeTrack() error
StopTrack() error
}
type PlaybackState int
const (
Stopped PlaybackState = iota
Playing
Paused
)
type RepeatMode int
const (
RepeatOff RepeatMode = iota
RepeatOne
RepeatAll
)
type Player struct {
mu sync.Mutex
output AudioOutput
playlist *Playlist
snapshot []PlaylistEntry
plVersion uint64
order []int // Logical playback index -> Index in snapshot
cursor int
state PlaybackState
repeat RepeatMode
shuffle bool
rng *rand.Rand
}
func NewPlayer(output AudioOutput) *Player {
return &Player{
output: output,
state: Stopped,
repeat: RepeatOff,
rng: rand.New(rand.NewSource(time.Now().UnixNano())),
}
}
func (p *Player) SetPlaylist(pl *Playlist) {
p.mu.Lock()
defer p.mu.Unlock()
p.playlist = pl
p.syncPlaylistLocked()
p.cursor = 0
p.state = Stopped
}
func (p *Player) syncPlaylistLocked() {
if p.playlist == nil {
p.snapshot = nil
p.order = nil
p.plVersion = 0
return
}
entries, ver := p.playlist.Snapshot()
if ver == p.plVersion && len(entries) == len(p.snapshot) {
return
}
p.snapshot = entries
p.plVersion = ver
p.rebuildOrderLocked()
}
func (p *Player) rebuildOrderLocked() {
n := len(p.snapshot)
p.order = make([]int, n)
for i := 0; i < n; i++ {
p.order[i] = i
}
if p.shuffle && n > 0 {
p.rng.Shuffle(n, func(i, j int) {
p.order[i], p.order[j] = p.order[j], p.order[i]
})
}
if p.cursor >= n {
if n > 0 {
p.cursor = n - 1
} else {
p.cursor = 0
}
}
}
func (p *Player) Play() error {
p.mu.Lock()
defer p.mu.Unlock()
p.syncPlaylistLocked()
if len(p.snapshot) == 0 {
return ErrEmptyPlaylist
}
switch p.state {
case Playing:
return nil
case Paused:
p.state = Playing
return p.output.ResumeTrack()
case Stopped:
p.state = Playing
entry := p.snapshot[p.order[p.cursor]]
return p.output.PlayTrack(entry.SongID)
}
return nil
}
func (p *Player) Pause() error {
p.mu.Lock()
defer p.mu.Unlock()
if p.state != Playing {
return nil
}
p.state = Paused
return p.output.PauseTrack()
}
func (p *Player) Next() error {
p.mu.Lock()
defer p.mu.Unlock()
p.syncPlaylistLocked()
n := len(p.snapshot)
if n == 0 {
return ErrEmptyPlaylist
}
if p.repeat == RepeatOne {
entry := p.snapshot[p.order[p.cursor]]
p.state = Playing
return p.output.PlayTrack(entry.SongID)
}
p.cursor++
if p.cursor >= n {
if p.repeat == RepeatAll {
p.cursor = 0
if p.shuffle {
p.rebuildOrderLocked()
}
} else {
p.cursor = n - 1
p.state = Stopped
return p.output.StopTrack()
}
}
entry := p.snapshot[p.order[p.cursor]]
p.state = Playing
return p.output.PlayTrack(entry.SongID)
}
func (p *Player) Previous() error {
p.mu.Lock()
defer p.mu.Unlock()
p.syncPlaylistLocked()
n := len(p.snapshot)
if n == 0 {
return ErrEmptyPlaylist
}
if p.cursor > 0 {
p.cursor--
} else if p.repeat == RepeatAll {
p.cursor = n - 1
}
entry := p.snapshot[p.order[p.cursor]]
p.state = Playing
return p.output.PlayTrack(entry.SongID)
}
func (p *Player) SetShuffle(enabled bool) {
p.mu.Lock()
defer p.mu.Unlock()
if p.shuffle == enabled {
return
}
p.shuffle = enabled
p.syncPlaylistLocked()
}
func (p *Player) SetRepeat(mode RepeatMode) {
p.mu.Lock()
defer p.mu.Unlock()
p.repeat = mode
}
5. Complexity Analysis
| Operation | Time Complexity | Space Complexity | Notes |
|---|---|---|---|
Playlist.Add | $O(1)$ amortized | $O(1)$ | Map check + slice append. |
Playlist.RemoveAt | $O(N)$ | $O(1)$ | Slicing overhead for elements shift. |
Playlist.Move | $O(N)$ | $O(1)$ | Slice block shift via copy. |
Playlist.Dedupe | $O(N)$ | $O(N)$ | Single pass using temporary occurrence map. |
Playlist.Snapshot | $O(N)$ | $O(N)$ | Full allocation and copy of entries. |
Merge | $O(N_A + N_B)$ | $O(N_A + N_B)$ | Snapshot reads + entry inserts into fresh playlist. |
Player.Next / Previous | $O(1)$ amortized | $O(1)$ | Indices lookup ($O(N)$ only if list reshuffled). |
6. Testing Strategy & Edge Cases
When unit testing this architecture, prioritize the following test suites:
- Boundary & State Integrity Tests:
- Verify
RemoveAtandMovefail gracefully with out-of-bounds indices without mutating internal state. - Assert
Playon an empty playlist returnsErrEmptyPlaylist.
- Verify
- Duplicate Enforcement & Deduplication:
- Test adding duplicate tracks under
RejectDuplicatespolicy; verify error return and invariant playlist length. - Run
Dedupe()on repeated sequences (e.g.,[S1, S2, S1, S3, S2]) and check that ordering of initial occurrences ([S1, S2, S3]) is preserved.
- Test adding duplicate tracks under
- Merge Isolation & Strategy Tests:
- Execute parallel merges on identical playlists to confirm total absence of lock contention deadlocks.
- Test
MergeInterleavewith mismatched source lengths (e.g., length 5 merged with length 2) to ensure non-overflowing append sequences.
- Playback State Transitions:
- Step through
Next()when set toRepeatOffat the end of a playlist to confirm transition toStoppedstate andStopTrack()invocation. - Verify
RepeatAllwraps the cursor to index0and generates a fresh shuffle ordering whenshuffle = true.
- Step through