Skip to content

Groove: A Radio Station as a Pure Function

How Kapell's Groove stations were made fast and private.


Kapell, my Apple Music player, recently got a new feature called a Groove. You hand it a song, an album, an artist, a producer, a studio, a label (whatever!) and it tries to play — it’s still in beta, lol — an endless station that walks out from there through the people who made the music. Not “people who liked this also liked that.” Who mixed it, who produced it, who played bass on it, where it was recorded. Every track comes with the path that got there, so you can see why it’s playing. It’s a souped-up, modern version of how I found and enjoyed music in my early life.

I want to yap about the backend, because I made a selfish choice early on: I wanted a Groove to work without having to store any state about the user. No favorites, no recent listens, etc. I think it’s novel, as the Groove has ended up being a (kinda) pure function.

The Function

Here’s the whole engine’s front door, more or less verbatim. It gives one page of a “station”:

func Next(g Graph, def Definition, st State,
    randSeed uint64, first int) (*Page, error)

Three inputs (and the graph):

  • Definition is the “station”: the seeds, plus the knobs. How far from the seed’s era it may wander, how strict about genre, how familiar vs. obscure, how much it drifts, whether it’s clean-only. Nothing about you.
  • State is your session: what you’ve heard recently, what you skipped (and how far in!), what you favorited, the evolved seed set from the last page. The client holds this, not the server. It sends it up every time.
  • randSeed is randomness, but not the kind you’d expect. More on this in a sec.
  • Graph is the catalog, a snapshot of the credit graph. It’s an interface with one method per read the engine makes.

And one thing comes out: a Page of tracks, each with its “why” path, plus the evolved seeds the client sends back next time.

Where the Randomness Comes From

A radio station that plays the same thing every time is… a CD. A Groove needs randomness, but I didn’t want hidden randomness. So the API hashes the request itself:

randSeed := fnv64a(json(station, seeds, recent, feedback, color, first, shuffleSeed))
page := Next(graph, def, state, randSeed, first)

That’s the random seed. It sounds backwards, but it gives exactly the behavior I want:

  • A retry is safe. Flaky cell connection? The client asks again, it gets the same page. No double-advancing.
  • Every page is different anyway, because recent grows each time you listen. The request changes, so the hash changes, so the walk changes.
  • A new station is one integer away. shuffleSeed is part of the hash. Bump it, new station, same everything else.
  • A bug report is replayable. If something weird plays, I can rerun that exact request and watch it pick the same weird song, then step through why.

The Walk

So what does the function actually do? It runs a bunch of short random walks over the credit graph and keeps the best places they land.

A page asks for some number of tracks (this is largely a tuning area of the client, which tends to only expose the “next” 3 tracks). It runs 30 walks per track, with a floor of 150 and a ceiling of 900. Each walk picks a seed weighted by importance, steps out through a connector (a person, studio, label, series or scene), and lands on a record. Then it flips a coin weighted by the station’s tether to decide whether to go home or take one more hop. Max two landings, because past that the “why” stops being something a human can follow. A real one looks like:

Midnight Marauders —mixer→ Bob Power —mixer→ Illadelph Halflife

Every landing passes through gates (era, genre, storefront availability, content rating, recently played, no compilations), and every rejection is recorded so a page that comes up short can say which gate booted it out. The survivors get scored on familiarity, variety, your feedback, an artist cooldown, and so on, and the top ones become the page.

The walks run concurrently on six workers. That’s the first place determinism gets tested, because goroutines finish in whatever order they please. The trick is that each walk gets its own random stream, derived from the page seed and the walk’s index:

walk[i].rng = PCG(pageSeed, i+1)

Results merge in walk order, not finish order. Walk #47 makes the same choices whether it ran first or last.

That almost worked. The walks share a memo of loaded records, and one gate peeked at that memo to skip records cheaply. If walk #12 had already loaded a record, walk #47 could reject it early. If not, it got judged later, a different way. Same inputs, different page, depending on scheduling! This was frustrating and took a while to sort out. The fix was boring: load the record before gating. Dugh. It’s a one-line comment in the code now, which belies the frustration it caused me.

An Aside: The Station Definition

I’ve been saying “the knobs” like it’s a couple of sliders. It isn’t. A station Definition has sixteen fields, and one of them, the lens, holds nine more weights. That’s about two dozen dials before your session adds its own steering (feedback, avoids, genre preferences). The defaults are a combination of gut feel, vibes, and listening. I wrote some CLI tooling to play with the output and see how it felt.

What makes this manageable is that every knob acts at exactly one stage of a page:

Where each station knob acts. 1 start: seed weights, home share, color, grain pick where a walk begins. 2 step: the lens, tether and spread weight each edge; an edge's weight falls with how many credits the person has. 3 gate: era, genre, storefronts, content rating, avoids and record type pass or reject and never score. 4 score: path strength times a people bonus times a bell curve of popularity centered on familiarity, then likes, color and preferences. 5 pick: variety sets how often a weaker candidate gets picked, followed by the artist cooldown, spread cap and album runs; at variety 0 the top candidate wins 97% of the time, at variety 1 about half. 6 evolve: drift fades original seeds toward a 35% floor and evolved seeds until they drop out. 1 · start 2 · step 3 · gate 4 · score 5 · pick 6 · evolve seeds × weight home grain color lens (9) tether .35 spread .5 recent era ±3 years genre: strict storefronts content rating record type avoid · genres familiarity .5 subgenre feedback prefer ×2 variety .5 cooldown 8 spread cap album run drift .3 likes → seeds a walk picks aseed by weight;"home" is the shareof walks that stayon seed artists 1.0.12credits, 1 → 10k popularity 0 → 1fam .5 · - - .2 97%53%var 0var 1 ×35%pages →- - evolved edge ∝ lens × specificity × fatiguetether: P(stop) pass or reject.never a score.era and genre aremeasured from theoriginal seed,so drift can'twander out of it Σ path strength × people (≤3) × bell(pop) × likes, color variety = howoften a weakerpick gets a shot;then the caps seeds ×(1−d/4)ⁿnew ×(1−d/2)ⁿnew seeds fromyour favorites Definitionyour session (State)

A few of these are more interesting than their names suggest. Speaking of names, having an LLM help with this was really great, as we all know naming is really hard. I was able to add capabilities and let the LLM generate fitting names and explanations for each as I honed in on the feel. Anyway, the knobs of note:

  • The lens is nine weights, one per family of credit:

    hands players samples circle writing rooms scene labels sleeve
    1.0 0.8 0.7 0.7 0.6 0.4 0.25 0.15 0

    Hands are producers, mixers and engineers. Circle is the artist’s own bands and collaborators. Scene connects records by Apple subgenre with no person between them, and it stays low on purpose, because a station that runs on scene is just genre radio.

  • Specificity isn’t a knob, but it has a big impact on feel. An edge through a person is discounted by how many credits that person has: log₂3 / log₂(2 + credits). An engineer with three records is a strong link; a session player on ten thousand is a weak one (0.12). Before it, a few prolific engineers dominated the resulting tracks.

  • Familiarity isn’t “more popular.” It’s the center of a bell curve over popularity (width 0.22, never below 0.05). At 0.5 you get the middle of the catalog, at 0.2 the deep cuts, and hits get penalized.

  • Variety is how much of a gamble each pick is. At 0 the station almost always plays its strongest candidate (97% of the time, in the chart above). At 1 the strongest gets about half the picks, and weaker connections get a real shot.

  • Drift is how fast the station forgets where it started. Every ten tracks, original seeds fade by (1 − drift/4) but never below 35% of their weight. Evolved seeds (picked from your favorites) fade twice as fast and drop out under 0.1. All of the per-page rates scale with page size, so a station played three tracks at a time evolves like one played ten at a time.

  • Gates never score. The era, genre gate, storefront and content rating are fences. Scoring only decides between what’s inside them, so a fence can never be outvoted by a high score.

And because all of it lives in one value, a station is just data. I was a bit intimidated by trying to create a UI for this, so Kapell instead ships with a few presets.

Preset What it does How
Close Orbit Stays near the seed and its people Short walks, slow drift, a share of the seed’s own artists, same subgenre
Deep Cuts Same circle, less-played records Familiarity turned way down, era widened a little
Wander Follows the credits outward Long walks, fast drift, a decade either way, neighboring genres allowed
Surprise Lets go of the seed Longest walks, fastest drift, any genre, a 25-year window, less-played records
Default Whatever the engine does unprompted Everything in the middle

The Catalog: Pure, But Only for Today

Hrm. That whole “deterministic” thing has a problem. MusicBrainz replicates into Kapell hourly. Apple’s catalog feed lands daily. People (me, for one. i’ve been buying used CDs) keep adding credits. A function of the graph is only as pure as the graph is fixed, and it isn’t. 😂

To hold things still, I take daily snapshots. This is also an opportunity for speeeeeeeed. A job called groove-export opens one REPEATABLE READ transaction against Postgres and writes out every read the engine could possibly make, as flat little-endian files. No parsing on the way back in. The reader memory-maps them and reinterprets the bytes in place.

That index gets published as an OCI image, just data, no code, to the cluster’s registry. A commit bumps its digest and stationd, a little daemon that runs one pod per node, re-mounts the image as a volume. Rolling back yesterday’s catalog is a git revert.

Inside the Index

The index is 161 files and about 8 GB. Every file is a flat array of one fixed-size type: a []uint32, a []uint64, a run of 16-byte UUIDs, or a blob of string bytes with a []uint64 of end offsets beside it. Opening a file means mmap and a cast. There’s no header to parse, no decoding, and no allocation until a result is built.

Four shapes are built out of those arrays:

  • A uuid set: every MusicBrainz id in the export, sorted. An MBID’s integer id is just its position, so nobody needs a hash table.
  • A dictionary: every repeated string (relationship names, genres, storefronts) stored once, with a sorted permutation for reverse lookup. Interning these, along with a shared pool for lists, took the index from 11.3 GB to 8.1 GB.
  • A table: sorted keys, and for each key a start and a count n into a set of row columns. One key’s rows sit next to each other, already in the order Postgres would have returned them.
  • A two-part key: two uint32 ids packed into one uint64, so “this artist, under this relationship” is a single sorted key.

Here’s how one read the engine makes all the time, “which records did Bob Power mix?”, goes through those files:

One read in the Groove index: which records did Bob Power mix? 1: binary-search his MBID in the sorted mbid file; his position, 48213, is his id. 2: look up "mixer" in the string dictionary: id 7. 3: pack the two ids into one 64-bit key. 4: binary-search the sorted out.key file; the same position in out.start and out.n says his rows start at 9120 and there are 16. 5: rows 9120 to 9135 of out.to and out.pop are his records, most popular first, so a limit is a slice. 6: each out.to value is a position in the mbid file, which gives the record's MBID. The ids are illustrative. 1 Find Bob Power every MBID, sorted. A binary search finds his; his position is his id. … 4b2e9a… 48212 51c0d3… 48213 5e88f1… 48214 … mbid → id 48213 2 Find "mixer" every repeated string is stored once and numbered. producer 5 engineer 6 mixer 7 mastering 8 … dict → id 7 3 Pack one key two 32-bit ids side by side make one 64-bit number. 482137 high 32 bitslow 32 bits = key 48213·7 4 Look the key up in out the keys are sorted, so it is another binary search. The same spot in start and n says where his rows are, and how many. 48213·2 48213·5 48213·7 48213·9 48214·2 key 8960 9071 9120 9136 9150 start 111 49 16 14 3 n → 16 rows from row 9120 5 Read his rows his 16 mixes, already sorted most popular first, so a limit is just a slice. 7731052 9120 2204417 9121 6510943 9122 ⋮ 3391820 9135 to .91 .88 .85 ⋮ .12 pop 6 Back to an MBID each "to" is a position in mbid, the file from step 1. … 9a01c2… 7731051 b47e10… 7731052 c3f9d8… 7731053 … mbid → the record Bob Power mixed

No query planner, no row decoding, no network. I considered using Parquet or Arrow for this, but with LLM help the creation of this index was pretty simple. We didn’t really need them with this format, since we’re not going to be scanning.

The hot parts of those 8 GB sit in the page cache, and the kernel handles the rest. And because every list is stored complete, the engine’s knobs (“look at the top 40 records per hop”) are slices taken when the page is served. I can retune the engine without rebuilding the index.

What It Bought

Speed, mostly. My initial tests with Groove pages made around 2,900 Postgres queries and ate 83% of GraphQL server time. Same function, different Graph:

p50 p95
Postgres graph 299 ms 755 ms
Mapped index 44 ms 105 ms

Under load on the cluster, a served station page runs about 24 ms p50 and 64 ms p95. Postgres doesn’t hear about Groove at all anymore.

But the bits I’m happier about aren’t the numbers:

  • The server keeps nothing about you. Your session lives on your client and comes up with each request. Nothing in a station request is logged. There’s no table of your listening to leak, because there’s no table. Station responses are no-store too: deterministic doesn’t mean shareable.
  • Testing is calm. A fixture graph, a definition, a seed, assert the page. No mocks of time, no flaky ordering.
  • Reverts or adjustment are easy. I can fall back to Postgres if I must, but it’s also trivial to build new images and roll out changes to stationd.

Go Groove

I was really excited when I started on this idea, but the impact on my backend was pretty frustrating. Making a “station” that felt good to me was really rewarding, so I was bummed it was slow. But, in 2026, we have LLMs and can turn around proofs of concept really fast. It cost me a daily export job, an 8 GB data image, that little stationd guy. But it turned the most complicated (server-side) feature in Kapell into the one I’m least worried about bringing things down.

If you’ve got Kapell, start a Groove from a record you love and tap the “why” on each track. Every path is a real credit somebody entered into MusicBrainz. Maybe go add a few. They’ll show up tomorrow. :)