System Design

E3

Music player analytics

Three small questions over one stream of plays. Each has a data structure that fits in a few lines. The race is in the unique count, and the second half is about what happens when the sets no longer fit.

Not startedSaved in this browser only.
  1. 1A set of users per song gives an exact count, and a repeat play changes nothing.
  2. 2A linked map keeps recent songs: the list holds the order, and the map finds a node in one step.
  3. 3Top k needs a heap of k songs, not a full sort. State the tie rule, or two calls can disagree.
  4. 4The build is exact. The talk trades exactness for memory: HyperLogLog, count-min and sorted sets.
E3
    A

    The spec

    as the interviewer states it
    Build a music analytics service as an HTTP API, in memory. Add a song. Record a play of a song by a user. Return the songs ranked by unique listeners. Return a user's most recent distinct songs. Return the top k songs. Many clients call the service at once.
    askanswer assumed
    Who picks a song ID?The client. A second add is 409.
    Must a user be added first?No. The first play creates the user.
    Two songs tie?More listeners first, then the smaller song ID, compared by bytes.
    A user replays a song?It moves to the front of recent, with no second copy.
    How long is a recent list?The latest 100 distinct songs per user.
    What is k?1 to 1000, and 10 by default.

    Before I type, I confirm that unique means distinct users per song, and I state the tie rule.

    B

    The endpoints

    the contract the grader checks
    requestsuccesserrors
    POST /songs201 song400, 409
    POST /plays201 song, listeners400, 404
    GET /songs/ranked200 songs
    GET /songs/top?k=200 songs400
    GET /users/{user}/recent?k=200 songs400
    • A song has the body {"song":"a"}. A play has "song" and "user".
    • A ranking is a list of song and listeners. Songs with no plays are in it.
    • Recent is a list of song IDs, newest first. A user with no plays gets an empty list.
    • IDs are 1 to 256 bytes.

    A play answers with the listener count, so a client sees the result of its own write.

    C

    The checkpoints

    15, 30 and 45 minutes
    bybuildproofif you are late
    15 minThe kit, renamed. Add song, record play, and the ranking from a set per song.TestUniqueListenersSkip ID length checks. Add them in the last 5 minutes.
    30 minThe linked map per user, and the limit of 100.TestRecentDistinctUse a slice and scan it. Say what the map would save.
    45 minThe heap and the tie rule. Race test with repeating users.TestTopBreaksTiesBySong, TestParallelPlaysByRepeatingUsersSort all songs with the same compare function, and say the cost: "O(n log n) where a heap gives O(n log k)."

    I keep a running service at each checkpoint. If I am late at 30 minutes, I sort for top k and describe the heap.

    D

    The core idea

    a linked map, one per user
    list: the ordercnewestaboldestplay of bmap: song to nodecabA play of b: the map finds the node, and the list moves it, with no scan.Past 100 songs, a new play removes the tail node and its map entry.One user's memory then has a fixed limit.

    The map finds the song and the list moves it. Both steps are constant time, and the limit bounds the memory.

    E

    Top k without a full sort

    n songs, k kept
    methodplayreadstatus
    Sort all at readO(1)O(n log n)Small data
    Heap of k at readO(1)O(n log k)The build
    Rank indexO(log n)O(k)Postgres
    Sorted setO(log n)O(log n + k)Redis
    • The build favours plays, because they far outnumber reads in this prompt.
    • An index or a sorted set moves the work to each play, and a read then touches k entries.
    • A test compares the heap with a full sort for every k from 1 to 310, with many ties.

    I scan once and keep k songs in a heap. The ranking is the same code with room for every song.

    F

    Why it fits

    computed from the files
    partvalue
    Lines, with tests413
    Typed characters8,501
    Typing at 500 a minute17:00
    Typing at 300 a minute28:20
    Left for thinking, at 500 a minute28:00
    Dependencies0

    Typed characters leave out imports, closing brackets, indentation and comments. Arithmetic, not a measurement of a person.

    I have rehearsed the kit part of this build. The new work is the store.

    G

    Rules for the room

    what to do, what to avoid
    choicestatus
    Exact sets in the buildApproved
    A stated tie rule, in one compare functionApproved
    One lock over all the mapsSay the cost
    Check "is new", unlock, then countNot approved
    Count plays and call them listenersNot approved
    A recent list with no limitNot approved
    A sketch in the buildTalk only

    I say what I chose and what it costs, then I move on.

    H

    store.go

    reference build
    store.gogo
    package build
    
    import (
    	"cmp"
    	"container/heap"
    	"container/list"
    	"context"
    	"errors"
    	"slices"
    	"sync"
    )
    
    var (
    	ErrInvalid  = errors.New("invalid")
    	ErrNotFound = errors.New("not found")
    	ErrConflict = errors.New("conflict")
    )
    
    // maxRecent bounds the memory one user can take.
    const maxRecent = 100
    
    // Rank is one song's place in the ranking.
    type Rank struct {
    	Song      string `json:"song"`
    	Listeners int64  `json:"listeners"`
    }
    
    // before is the ranking order: more listeners first, then the song id, so ties have one answer.
    func before(a, b Rank) int {
    	return cmp.Or(cmp.Compare(b.Listeners, a.Listeners), cmp.Compare(a.Song, b.Song))1
    }
    
    type Store interface {
    	AddSong(ctx context.Context, song string) error
    	// Play records a play and returns the song's listener count.
    	Play(ctx context.Context, song, user string) (int64, error)
    	// Top returns the first k songs in ranking order.
    	Top(ctx context.Context, k int) ([]Rank, error)
    	// Recent returns the user's latest k distinct songs, newest first.
    	Recent(ctx context.Context, user string, k int) ([]string, error)
    }
    
    // recency is a linked map: the list keeps the order, and the map finds a node without a scan.
    type recency struct {
    	order *list.List
    	nodes map[string]*list.Element
    }
    
    func (r *recency) add(song string) {
    	if node, ok := r.nodes[song]; ok {
    		r.order.MoveToFront(node)2
    		return
    	}
    	r.nodes[song] = r.order.PushFront(song)
    	if r.order.Len() > maxRecent {
    		delete(r.nodes, r.order.Remove(r.order.Back()).(string))3
    	}
    }
    
    type MemStore struct {
    	mu        sync.RWMutex
    	listeners map[string]map[string]struct{}
    	recent    map[string]*recency
    }
    
    func NewMemStore() *MemStore {
    	return &MemStore{listeners: map[string]map[string]struct{}{}, recent: map[string]*recency{}}
    }
    
    func (s *MemStore) AddSong(_ context.Context, song string) error {
    	s.mu.Lock()
    	defer s.mu.Unlock()
    	if _, ok := s.listeners[song]; ok {
    		return ErrConflict
    	}
    	s.listeners[song] = map[string]struct{}{}
    	return nil
    }
    
    func (s *MemStore) Play(_ context.Context, song, user string) (int64, error) {
    	s.mu.Lock()
    	defer s.mu.Unlock()
    	users, ok := s.listeners[song]
    	if !ok {
    		return 0, ErrNotFound
    	}
    	users[user] = struct{}{}4
    	r, ok := s.recent[user]
    	if !ok {
    		r = &recency{list.New(), map[string]*list.Element{}}
    		s.recent[user] = r
    	}
    	r.add(song)
    	return int64(len(users)), nil
    }
    
    // worstFirst is a heap with the worst kept song on top, ready to be pushed out.
    type worstFirst []Rank
    
    func (h worstFirst) Len() int           { return len(h) }
    func (h worstFirst) Less(i, j int) bool { return before(h[i], h[j]) > 0 }5
    func (h worstFirst) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
    func (h *worstFirst) Push(x any)        { *h = append(*h, x.(Rank)) }
    func (h *worstFirst) Pop() any {
    	old := *h
    	last := old[len(old)-1]
    	*h = old[:len(old)-1]
    	return last
    }
    
    // Top scans every song once and keeps k in a heap: O(n log k), and no full sort.
    func (s *MemStore) Top(_ context.Context, k int) ([]Rank, error) {
    	s.mu.RLock()
    	defer s.mu.RUnlock()
    	h := &worstFirst{}
    	for song, users := range s.listeners {
    		r := Rank{song, int64(len(users))}
    		if h.Len() < k {
    			heap.Push(h, r)
    		} else if before(r, (*h)[0]) < 0 {6
    			(*h)[0] = r
    			heap.Fix(h, 0)
    		}
    	}
    	slices.SortFunc(*h, before)
    	return append([]Rank{}, *h...), nil7
    }
    
    func (s *MemStore) Recent(_ context.Context, user string, k int) ([]string, error) {
    	s.mu.RLock()
    	defer s.mu.RUnlock()
    	songs := []string{}
    	r, ok := s.recent[user]
    	if !ok {
    		return songs, nil
    	}
    	for node := r.order.Front(); node != nil && len(songs) < k; node = node.Next() {
    		songs = append(songs, node.Value.(string))
    	}
    	return songs, nil
    }
    
    1. 1The tie rule lives here and nowhere else. The heap and the final sort both use it.
    2. 2A replay moves the node, so a song has one entry, however often it plays.
    3. 3The list and the map change together. If they drift, memory leaks through the map.
    4. 4Adding a member twice changes nothing. That one line is the unique count.
    5. 5Reversed on purpose: the top of the heap is the song to push out.
    6. 6One comparison rejects most songs, so the scan stays near O(n) when k is small.
    7. 7A non-nil slice, so an empty result is [] in JSON and not null.

    All state sits behind one lock. A play changes the set and the recent list inside one critical section.

    I

    service.go

    reference build
    service.gogo
    package build
    
    import (
    	"context"
    	"fmt"
    	"math"
    )
    
    const (
    	maxID = 256
    	maxK  = 1000
    )
    
    type Service struct{ store Store }
    
    func NewService(store Store) *Service {
    	return &Service{store}
    }
    
    func checkID(name, id string) error {
    	if id == "" || len(id) > maxID {
    		return fmt.Errorf("%w: %s must be 1 to %d bytes", ErrInvalid, name, maxID)
    	}
    	return nil
    }
    
    func checkK(k int) error {
    	if k < 1 || k > maxK {2
    		return fmt.Errorf("%w: k must be 1 to %d", ErrInvalid, maxK)
    	}
    	return nil
    }
    
    func (s *Service) AddSong(ctx context.Context, song string) error {
    	if err := checkID("song", song); err != nil {
    		return err
    	}
    	return s.store.AddSong(ctx, song)
    }
    
    func (s *Service) Play(ctx context.Context, song, user string) (int64, error) {
    	if err := checkID("song", song); err != nil {
    		return 0, err
    	}
    	if err := checkID("user", user); err != nil {
    		return 0, err
    	}
    	return s.store.Play(ctx, song, user)
    }
    
    // Ranked is Top with room for every song.
    func (s *Service) Ranked(ctx context.Context) ([]Rank, error) {
    	return s.store.Top(ctx, math.MaxInt)1
    }
    
    func (s *Service) Top(ctx context.Context, k int) ([]Rank, error) {
    	if err := checkK(k); err != nil {
    		return nil, err
    	}
    	return s.store.Top(ctx, k)
    }
    
    func (s *Service) Recent(ctx context.Context, user string, k int) ([]string, error) {
    	if err := checkK(k); err != nil {
    		return nil, err
    	}
    	return s.store.Recent(ctx, user, k)
    }
    
    1. 1One path. In Postgres this is the same query with a large limit.
    2. 2The limit bounds the answer a client can ask for, so one request cannot return everything.

    The service holds only the rules. The ranking is Top with room for every song, so there is one sort order in the build.

    J

    handler.go and main.go

    reference build
    handler.gogo
    package build
    
    import (
    	"encoding/json"
    	"errors"
    	"fmt"
    	"log"
    	"net/http"
    	"strconv"
    )
    
    type body struct {
    	Song string `json:"song"`
    	User string `json:"user"`
    }
    
    func Handler(svc *Service) http.Handler {
    	mux := http.NewServeMux()
    	mux.Handle("POST /songs", route(201, func(r *http.Request) (any, error) {
    		var in body
    		if err := readJSON(r, &in); err != nil {
    			return nil, err
    		}
    		return Rank{Song: in.Song}, svc.AddSong(r.Context(), in.Song)
    	}))
    	mux.Handle("POST /plays", route(201, func(r *http.Request) (any, error) {
    		var in body
    		if err := readJSON(r, &in); err != nil {
    			return nil, err
    		}
    		n, err := svc.Play(r.Context(), in.Song, in.User)
    		return Rank{in.Song, n}, err1
    	}))
    	mux.Handle("GET /songs/ranked", route(200, func(r *http.Request) (any, error) {
    		ranks, err := svc.Ranked(r.Context())
    		return map[string][]Rank{"songs": ranks}, err
    	}))
    	mux.Handle("GET /songs/top", route(200, func(r *http.Request) (any, error) {
    		k, err := readK(r)
    		if err != nil {
    			return nil, err
    		}
    		ranks, err := svc.Top(r.Context(), k)
    		return map[string][]Rank{"songs": ranks}, err
    	}))
    	mux.Handle("GET /users/{user}/recent", route(200, func(r *http.Request) (any, error) {
    		k, err := readK(r)
    		if err != nil {
    			return nil, err
    		}
    		songs, err := svc.Recent(r.Context(), r.PathValue("user"), k)
    		return map[string][]string{"songs": songs}, err
    	}))
    	return mux
    }
    
    // readK reads ?k=, which defaults to 10.
    func readK(r *http.Request) (int, error) {
    	v := r.URL.Query().Get("k")2
    	if v == "" {
    		return 10, nil
    	}
    	k, err := strconv.Atoi(v)
    	if err != nil {
    		return 0, fmt.Errorf("%w: k must be a number", ErrInvalid)
    	}
    	return k, nil
    }
    
    func route(status int, fn func(*http.Request) (any, error)) http.Handler {
    	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    		code := status
    		v, err := fn(r)
    		if err != nil {
    			code, v = failure(err)
    		}
    		w.Header().Set("Content-Type", "application/json")
    		w.WriteHeader(code)
    		if err := json.NewEncoder(w).Encode(v); err != nil {
    			log.Print(err)
    		}
    	})
    }
    
    func readJSON(r *http.Request, v any) error {
    	if err := json.NewDecoder(r.Body).Decode(v); err != nil {
    		return fmt.Errorf("%w: %v", ErrInvalid, err)
    	}
    	return nil
    }
    
    func failure(err error) (int, any) {
    	status := 500
    	switch {
    	case errors.Is(err, ErrInvalid):
    		status = 400
    	case errors.Is(err, ErrNotFound):
    		status = 404
    	case errors.Is(err, ErrConflict):
    		status = 409
    	default:
    		log.Print(err)
    		err = errors.New("internal error")
    	}
    	return status, map[string]string{"error": err.Error()}
    }
    
    1. 1On an error the route ignores this value and answers from the error map.
    2. 2A missing k is 10. A bad k is 400 here, and a k out of range is 400 in the service.
    main.gogo
    // Command main serves the 45-minute music analytics service.
    package main
    
    import (
    	"log"
    	"net/http"
    
    	"github.com/rudrite/system-design/arena/exercises/music/build"
    )
    
    func main() {
    	handler := build.Handler(build.NewService(build.NewMemStore()))
    	log.Fatal(http.ListenAndServe(":8080", handler))
    }
    

    The handlers only translate. Parsing k lives in one helper, shared by two routes.

    K

    build_test.go

    type this part too
    build_test.gogo
    package build
    
    import (
    	"fmt"
    	"net/http"
    	"net/http/httptest"
    	"strings"
    	"sync"
    	"testing"
    )
    
    type step struct {
    	method, path, body string
    	status             int
    	want               string
    }
    
    func do(h http.Handler, method, path, body string) (int, string) {
    	w := httptest.NewRecorder()
    	h.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body)))
    	return w.Code, w.Body.String()
    }
    
    func run(t *testing.T, h http.Handler, steps []step) {
    	t.Helper()
    	for i, s := range steps {
    		status, body := do(h, s.method, s.path, s.body)
    		if status != s.status || !strings.Contains(body, s.want) {
    			t.Errorf("step %d, %s %s: got %d %s", i, s.method, s.path, status, body)
    		}
    	}
    }
    
    func newHandler() http.Handler {
    	h := Handler(NewService(NewMemStore()))
    	for _, song := range []string{"a", "b", "c"} {
    		do(h, "POST", "/songs", fmt.Sprintf(`{"song":%q}`, song))
    	}
    	return h
    }
    
    func play(song, user string) step {
    	return step{"POST", "/plays", fmt.Sprintf(`{"song":%q,"user":%q}`, song, user), 201, ""}
    }
    
    func TestUniqueListeners(t *testing.T) {
    	h := newHandler()
    	run(t, h, []step{
    		{"POST", "/songs", `{"song":"a"}`, 409, ""},
    		{"POST", "/plays", `{"song":"x","user":"u"}`, 404, ""},
    		{"POST", "/plays", `{"song":"a"}`, 400, ""},
    		play("a", "u"), play("a", "u"), play("a", "v"), play("b", "u"),1
    		{"GET", "/songs/ranked", "", 200, `[{"song":"a","listeners":2},{"song":"b","listeners":1},{"song":"c","listeners":0}]`},
    	})
    }
    
    func TestRecentDistinct(t *testing.T) {
    	h := newHandler()
    	run(t, h, []step{
    		play("a", "u"), play("b", "u"), play("c", "u"), play("a", "u"),
    		{"GET", "/users/u/recent?k=2", "", 200, `["a","c"]`},
    		{"GET", "/users/u/recent", "", 200, `["a","c","b"]`2},
    		{"GET", "/users/none/recent", "", 200, `[]`},
    	})
    }
    
    func TestTopBreaksTiesBySong(t *testing.T) {
    	h := newHandler()
    	run(t, h, []step{
    		play("c", "u"), play("b", "u"), play("a", "u"), play("c", "v"),
    		{"GET", "/songs/top?k=2", "", 200, `[{"song":"c","listeners":2},{"song":"a","listeners":1}]`3},
    		{"GET", "/songs/top?k=0", "", 400, ""},
    	})
    }
    
    func TestParallelPlaysByRepeatingUsers(t *testing.T) {
    	h := newHandler()
    	var wg sync.WaitGroup
    	for i := range 100 {
    		wg.Go(func() { do(h, "POST", "/plays", fmt.Sprintf(`{"song":"a","user":"u%d"}`, i%74)) })
    	}
    	wg.Wait()
    	run(t, h, []step{{"GET", "/songs/top?k=1", "", 200, `"listeners":7`}})
    }
    
    1. 1Three plays of a by two users: the count must be 2.
    2. 2The fourth play moved a to the front, and there is no second a.
    3. 3a and b tie on 1, and the smaller ID stays in.
    4. 4Run with -race. 100 plays by 7 users must count exactly 7.

    Each test is a list of steps. The race test uses 7 users for 100 plays, so most plays are repeats.

    L

    The grader agrees

    35 checks, saved from a real run
    reportsaved output
    arena run music --base http://localhost:8080
    
    correctness
      PASS  a new song has no listeners
      PASS  a user counts once however often they play
      PASS  two users count twice
      PASS  a play answers with the listener count
      PASS  one user's plays count for each song apart
      PASS  the ranking puts more listeners first
      PASS  ties in the ranking go to the smaller song id
      PASS  the ranking lists every song, played or not
      PASS  the whole ranking is in order
      PASS  top k matches the start of the ranking
      PASS  top k with ties: the smaller id stays in
      PASS  top k with k over the song count returns every song
      PASS  top k defaults to 10
      PASS  recent songs come newest first
      PASS  a replay moves a song to the front and adds no copy
      PASS  recent k limits the list
      PASS  users have separate recent lists
      PASS  a user with no plays has an empty list
      PASS  a recent list keeps the latest 100 songs
    
    status codes
      PASS  add song is 201
      PASS  a song added twice is 409
      PASS  a play is 201
      PASS  a play of an unknown song is 404
      PASS  a play of an unknown song leaves no trace in recent
    
    validation
      PASS  malformed JSON is 400
      PASS  a missing song or user is 400
      PASS  a value of the wrong type is 400
      PASS  an id over 256 bytes is 400
      PASS  an id of exactly 256 bytes is fine
      PASS  a k that is not from 1 to 1000 is 400
    
    concurrency
      PASS  100 parallel plays by 10 repeating users count 10
      PASS  100 parallel plays by 100 users count 100
      PASS  100 parallel plays of 10 songs by one user list 10 songs once each
      PASS  100 parallel adds of one song: exactly one wins
      PASS  the ranking stays in order during 100 parallel plays
    
    35 checks: 35 passed, 0 failed

    All checks pass, with 100 parallel requests in each race.

    M

    The check that matters

    repeating users, in parallel
    checks.gogo
    {Name: "100 parallel plays by 10 repeating users count 10", Group: grader.Concurrency, Run: func(t *grader.T) {
      song := addSong(t, "s")
      prefix := t.Key("u")
      t.Parallel(parallel, func(i int) {
        play(t, song, prefix+strconv.Itoa(i%10)1)
      })
      wantListeners(t, song, 10)2
    }},
    1. 1Ten users, ten plays each, all at once.
    2. 2A higher count means that a check and its write were two steps.

    A server that checks for a new user, unlocks, then counts. The race detector stays quiet, because each step holds the lock.

    reportsaved output, failures only
      FAIL  a recent list keeps the latest 100 songs
            the list holds 101 songs, want 100
      FAIL  100 parallel plays by 10 repeating users count 10
            song run-31-s has 15 listeners, want 10
      FAIL  100 parallel plays of 10 songs by one user list 10 songs once each
            the list holds ["run-33-s0" "run-33-s0" "run-33-s0" "run-33-s1" "run-33-s1" "run-33-s2" "run-33-s3" "run-33-s3" "run-33-s3" "run-33-s3" "run-33-s4" "run-33-s5" "run-33-s5" "run-33-s5" "run-33-s5" "run-33-s5" "run-33-s5" "run-33-s5" "run-33-s5" "run-33-s6" "run-33-s6" "run-33-s7" "run-33-s8" "run-33-s8" "run-33-s8" "run-33-s9" "run-33-s9"], want each of the 10 songs once
    35 checks: 32 passed, 3 failed

    Sequential tests cannot find this bug. It needs two plays by one user at the same moment.

    N

    The follow-ups

    what the interviewer adds next
    follow-upin the buildin the talk
    Efficient unique countsAn exact set per song. Each member costs memory.HyperLogLog: 12.8 kB for one million users, 1.3% off in a recorded run.
    Top k without sorting everythingA heap of k songs at read: O(n log k).A rank index, or a Redis sorted set: each play pays O(log n), and a read touches k entries.
    Memory limitsA recent list keeps 100 songs per user. A test plays 10,000 and finds 100.Count-min for play counts in fixed memory, and retention for old listens.

    The build answers each follow-up exactly. When the sets stop fitting, I give up exactness on purpose, and I say by how much.

    O

    The talk map

    the second 45 minutes
    the interviewer asksthe answergoes deeper
    One song has 100 million listeners. What does the exact set cost?About 40 bytes per member as a Redis set, measured, so about 4 GB for one song. A HyperLogLog holds the same count in 12.8 kB, with about 1% error.B10 Probabilistic structures
    Can a public ranking use HyperLogLog?Yes for a chart. Two songs within 1% can swap places, and no reader can tell. Keep exact counts for anything that pays royalties, because money needs the true number.B10 HyperLogLog
    You have unique listeners per day. How do you get the week?Exact counts do not add, because one user can appear on seven days. HyperLogLogs merge: keep the larger value of each register. The merged sketch counts the union.B10 Merging sketches
    Does a count-min sketch help here?For play counts, yes. It uses fixed memory and only overcounts, so it suits heavy songs. It cannot count distinct users, because a repeat play adds again. That job needs HyperLogLog.B10 Count-min
    How does a Redis sorted set change top k?ZINCRBY updates a score in O(log N), and a range reads the top without a scan. Ties sort by bytes. ZREVRANGE reverses that, so store negative counts and read with ZRANGE to keep the tie rule.C21 Leaderboard
    Plays arrive at 100,000 a second. Do you write each to Postgres?No. Append each play to a log, and let consumers update the counts in batches. The API answers once the log has the event. The cost is that a count can lag by seconds.B6 Queues and logs
    The consumer delivers an event twice. Is the count wrong?Not for unique listeners: adding one user to a set twice changes nothing, and so does a HyperLogLog add. Plain play counts do need an event ID to drop copies.B6 Delivery guarantees
    What about the top songs this week, not all time?Keep counts per hour or day as rollups, and sum the rollups in the window. A query over raw plays reads every row. Rollups trade detail for a fixed read cost.B12 Time series
    Plays arrive late and out of order. What breaks?Recency uses arrival order here, so a late event looks new. Store the client time, and accept a late event only if it is newer. Rollups reread a short recent window for the same reason.B12 Late data
    One viral song gets most new listeners. What is the limit?Every new listener updates one songs row, so those writes wait in line on its row lock. Repeat plays do not. Batch the count from the log, or split the row.T4 Locks in the database
    Why no idempotency key on POST /plays?A retried play adds no listener, and at most it moves the song back to the front of the recent list. The shape of the write makes it safe, so a key would add nothing.T9 Exactly-once

    I start from what the build lacks: durability and memory. Then I move plays to a log and name what that costs.

    P

    The production shape

    what moves out of the process
    loadbalancerinstance 1auth, metrics, buildinstance 2auth, metrics, buildPostgreslistensthe exact setsongscount, rank indexrecentone row per user, songA new listener writes all three in one database transaction.A repeat play inserts nothing in listens, so the count stays.

    Instances hold no state. A primary key replaces the set, and an index replaces the heap.

    Q

    What changes

    from build to production
    toolbuildproduction
    PostgresA set per songlistens: a primary key on song and user
    PostgresHeap at readAn index on listeners and ID; a plan test finds no sort
    PostgresLinked maprecent: one row per user and song, ordered by a sequence
    PostgresMutexOne transaction per play, and an advisory lock per user
    ServiceNo auth, no metricsThe same bearer tokens and metrics as the key-value exercise
    ServiceListenAndServeTimeouts, a body limit, drain on SIGTERM

    Tested: production passes the same 35 grader checks. Each kept count then matches its rows. The real binary passes over a socket, then exits cleanly on SIGTERM.

    One interface, one new implementation, and a wrapper around the same handler. The service file does not change.

    R

    The diff

    build to production

    store.go, service.go and handler.go of the build are imported as they are. The production package adds the files below.

    main.go+61 -4
    + // Command main serves the production music analytics service. It reads DATABASE_URL, API_TOKENS
    + // (owner:token,owner:token) and ADDR, which defaults to :8080.
    - // Command main serves the 45-minute music analytics service.
      package main
      
      import (
    + 	"cmp"
    + 	"context"
    + 	"errors"
      	"log"
      	"net/http"
    + 	"os"
    + 	"os/signal"
    + 	"syscall"
    + 	"time"
      
    + 	"github.com/jackc/pgx/v5/pgxpool"
    + 
    + 	kv "github.com/rudrite/system-design/arena/exercises/kvstore/prod"
    + 	"github.com/rudrite/system-design/arena/exercises/music/prod"
    - 	"github.com/rudrite/system-design/arena/exercises/music/build"
      )
      
      func main() {
    + 	if err := run(); err != nil {
    + 		log.Fatal(err)
    + 	}
    + }
    + 
    + func run() error {
    + 	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
    + 	defer stop()
    + 
    + 	pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
    + 	if err != nil {
    + 		return err
    + 	}
    + 	defer pool.Close()
    + 	if err := prod.Migrate(ctx, pool); err != nil {
    + 		return err
    + 	}
    + 	tokens, err := kv.ParseTokens(os.Getenv("API_TOKENS"))
    + 	if err != nil {
    + 		return err
    + 	}
    + 
    + 	srv := &http.Server{
    + 		Addr:              cmp.Or(os.Getenv("ADDR"), ":8080"),
    + 		Handler:           prod.Handler(pool, tokens, kv.NewMetrics()),
    + 		ReadHeaderTimeout: 5 * time.Second,
    + 		ReadTimeout:       10 * time.Second,
    + 		WriteTimeout:      10 * time.Second,
    + 		IdleTimeout:       60 * time.Second,
    + 	}
    + 	failed := make(chan error, 1)
    + 	go func() { failed <- srv.ListenAndServe() }()
    + 
    + 	select {
    + 	case err := <-failed:
    + 		return err
    + 	case <-ctx.Done():
    + 	}
    + 	// SIGTERM: stop accepting, finish what is running, then exit.
    + 	drain, cancel := context.WithTimeout(context.Background(), 20*time.Second)
    + 	defer cancel()
    + 	if err := srv.Shutdown(drain); err != nil {
    + 		return err
    + 	}
    + 	if err := <-failed; !errors.Is(err, http.ErrServerClosed) {
    + 		return err
    + 	}
    + 	return nil
    - 	handler := build.Handler(build.NewService(build.NewMemStore()))
    - 	log.Fatal(http.ListenAndServe(":8080", handler))
      }
    schema.sqlnew file
    -- COLLATE "C" compares bytes, so a tie breaks in the same order as in the build.
    CREATE TABLE IF NOT EXISTS songs (
        id        text COLLATE "C" PRIMARY KEY,
        listeners bigint NOT NULL DEFAULT 0
    );
    
    -- The index holds the ranking in order, so top k reads k entries and sorts nothing.
    CREATE INDEX IF NOT EXISTS songs_rank ON songs (listeners DESC, id);
    
    -- The primary key is the exact set: a second play by one user inserts nothing.
    CREATE TABLE IF NOT EXISTS listens (
        song    text COLLATE "C" NOT NULL REFERENCES songs,
        user_id text NOT NULL,
        PRIMARY KEY (song, user_id)
    );
    
    CREATE SEQUENCE IF NOT EXISTS play_order;
    
    -- One row per user and song, so a replay moves the song and adds no copy.
    CREATE TABLE IF NOT EXISTS recent (
        user_id text   NOT NULL,
        song    text   NOT NULL,
        seq     bigint NOT NULL,
        PRIMARY KEY (user_id, song)
    );
    
    CREATE INDEX IF NOT EXISTS recent_order ON recent (user_id, seq DESC);
    pgstore: implements Storenew file, +114
    + // Package prod is the music analytics service made production grade. It imports the 45-minute
    + // build and replaces the in-memory store behind its interface, then adds auth, metrics and health.
    + // The service and the handler do not change.
    + package prod
    + 
    + import (
    + 	"context"
    + 	"errors"
    + 	"fmt"
    + 
    + 	"github.com/jackc/pgx/v5"
    + 	"github.com/jackc/pgx/v5/pgconn"
    + 	"github.com/jackc/pgx/v5/pgxpool"
    + 
    + 	"github.com/rudrite/system-design/arena/exercises/music/build"
    + )
    + 
    + // foreignKeyViolation is the Postgres error for a play of a song that does not exist.
    + const foreignKeyViolation = "23503"
    + 
    + // PGStore implements build.Store on Postgres.
    + type PGStore struct {
    + 	pool *pgxpool.Pool
    + }
    + 
    + // NewPGStore returns a store on pool.
    + func NewPGStore(pool *pgxpool.Pool) *PGStore {
    + 	return &PGStore{pool: pool}
    + }
    + 
    + // AddSong adds a song. The primary key decides between parallel adds.
    + func (s *PGStore) AddSong(ctx context.Context, song string) error {
    + 	tag, err := s.pool.Exec(ctx, `INSERT INTO songs (id) VALUES ($1) ON CONFLICT DO NOTHING`, song)
    + 	if err != nil {
    + 		return fmt.Errorf("add song: %w", err)
    + 	}
    + 	if tag.RowsAffected() == 0 {
    + 		return build.ErrConflict
    + 	}
    + 	return nil
    + }
    + 
    + // Keep the latest 100 songs. A play that passes the limit deletes the rows behind it.
    + const (
    + 	moveToFront = `
    + INSERT INTO recent (user_id, song, seq) VALUES ($1, $2, nextval('play_order'))
    + ON CONFLICT (user_id, song) DO UPDATE SET seq = excluded.seq`
    + 
    + 	trimRecent = `
    + DELETE FROM recent WHERE user_id = $1 AND seq <= (
    +     SELECT seq FROM recent WHERE user_id = $1 ORDER BY seq DESC OFFSET 100 LIMIT 1
    + )`
    + )
    + 
    + // Play records a play in one database transaction. The advisory lock makes one user's plays run
    + // one at a time. Without it, two parallel plays each see 101 rows and delete the same oldest row,
    + // and the list keeps 101.
    + func (s *PGStore) Play(ctx context.Context, song, user string) (int64, error) {
    + 	var listeners int64
    + 	err := pgx.BeginFunc(ctx, s.pool, func(db pgx.Tx) error {
    + 		if _, err := db.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, user); err != nil {
    + 			return fmt.Errorf("lock user: %w", err)
    + 		}
    + 		tag, err := db.Exec(ctx, `INSERT INTO listens (song, user_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`, song, user)
    + 		var pgErr *pgconn.PgError
    + 		if errors.As(err, &pgErr) && pgErr.Code == foreignKeyViolation {
    + 			return build.ErrNotFound
    + 		}
    + 		if err != nil {
    + 			return fmt.Errorf("add listener: %w", err)
    + 		}
    + 		count := `SELECT listeners FROM songs WHERE id = $1`
    + 		if tag.RowsAffected() == 1 {
    + 			count = `UPDATE songs SET listeners = listeners + 1 WHERE id = $1 RETURNING listeners`
    + 		}
    + 		if err := db.QueryRow(ctx, count, song).Scan(&listeners); err != nil {
    + 			return fmt.Errorf("count listeners: %w", err)
    + 		}
    + 		if _, err := db.Exec(ctx, moveToFront, user, song); err != nil {
    + 			return fmt.Errorf("move to front: %w", err)
    + 		}
    + 		if _, err := db.Exec(ctx, trimRecent, user); err != nil {
    + 			return fmt.Errorf("trim recent: %w", err)
    + 		}
    + 		return nil
    + 	})
    + 	return listeners, err
    + }
    + 
    + // Top reads the first k entries of the rank index.
    + func (s *PGStore) Top(ctx context.Context, k int) ([]build.Rank, error) {
    + 	rows, err := s.pool.Query(ctx, `SELECT id, listeners FROM songs ORDER BY listeners DESC, id LIMIT $1`, k)
    + 	if err != nil {
    + 		return nil, fmt.Errorf("read ranking: %w", err)
    + 	}
    + 	ranks, err := pgx.CollectRows(rows, pgx.RowToStructByPos[build.Rank])
    + 	if err != nil {
    + 		return nil, fmt.Errorf("read ranking: %w", err)
    + 	}
    + 	return ranks, nil
    + }
    + 
    + // Recent reads the user's latest k songs.
    + func (s *PGStore) Recent(ctx context.Context, user string, k int) ([]string, error) {
    + 	rows, err := s.pool.Query(ctx, `SELECT song FROM recent WHERE user_id = $1 ORDER BY seq DESC LIMIT $2`, user, k)
    + 	if err != nil {
    + 		return nil, fmt.Errorf("read recent: %w", err)
    + 	}
    + 	songs, err := pgx.CollectRows(rows, pgx.RowTo[string])
    + 	if err != nil {
    + 		return nil, fmt.Errorf("read recent: %w", err)
    + 	}
    + 	return songs, nil
    + }
    server: auth and metricsnew file, +48
    + package prod
    + 
    + import (
    + 	"context"
    + 	_ "embed"
    + 	"fmt"
    + 	"net/http"
    + 	"time"
    + 
    + 	"github.com/jackc/pgx/v5/pgxpool"
    + 
    + 	kv "github.com/rudrite/system-design/arena/exercises/kvstore/prod"
    + 	"github.com/rudrite/system-design/arena/exercises/music/build"
    + )
    + 
    + //go:embed schema.sql
    + var schema string
    + 
    + // Migrate applies the schema. It is safe to run twice.
    + func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
    + 	if _, err := pool.Exec(ctx, schema); err != nil {
    + 		return fmt.Errorf("apply schema: %w", err)
    + 	}
    + 	return nil
    + }
    + 
    + // maxBody limits a request body. A larger one fails to decode and answers 400.
    + const maxBody = 1 << 20
    + 
    + // Handler serves the API behind auth, plus the two routes an operator needs. Auth and metrics come
    + // from the key-value exercise, unchanged.
    + func Handler(pool *pgxpool.Pool, tokens kv.Tokens, metrics *kv.Metrics) http.Handler {
    + 	api := build.Handler(build.NewService(NewPGStore(pool)))
    + 
    + 	mux := http.NewServeMux()
    + 	mux.Handle("/", metrics.Wrap(kv.Auth(tokens, http.MaxBytesHandler(api, maxBody))))
    + 	mux.Handle("GET /metrics", metrics)
    + 	mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
    + 		ctx, cancel := context.WithTimeout(r.Context(), time.Second)
    + 		defer cancel()
    + 		if err := pool.Ping(ctx); err != nil {
    + 			http.Error(w, "database unreachable", http.StatusServiceUnavailable)
    + 			return
    + 		}
    + 		w.WriteHeader(http.StatusNoContent)
    + 	})
    + 	return mux
    + }

    The store interface carries this change.

    S

    Drill

    predict, then reveal

    0 of 10 known

    1. Why does the store keep a set of users and not a counter?

    2. Why a list and a map for recency? Why not a slice?

    3. A user plays a, b, c, a. What does recent return?

    4. Why is the heap for top k a heap of the worst kept song?

    5. What does Top cost, and when is it bad?

    6. Why does the ranking need a tie rule at all?

    7. Your server checks "is this user new?", unlocks, then adds to a counter. What fails?

    8. In production, what makes parallel repeats count once?

    9. Why does a play take an advisory lock per user in production?

    10. Why is the song id COLLATE "C" in the schema?

    T

    Numbers to say

    from the files and tests
    build
    413 lines with tests, 17:00 of typing at 100 words a minute.
    checks
    35 grader checks, in 4 groups.
    race
    100 parallel plays by 10 users count exactly 10.
    recent
    100 distinct songs per user.
    top k
    O(n log k) at read; k is at most 1000.
    exact set
    About 40 bytes per member in Redis, measured.
    HyperLogLog
    12,831 bytes at one million items, measured.

    Sketch numbers are from the probabilistic structures sheet. The others are design values from the tested code. Sorted set costs are from the Redis command documentation.