---
title: "Groove: A Radio Station as a Pure Function"
description: "How Kapell's Groove stations were made fast and private."
canonical: "https://onemogin.com/music/appstore/groove-pure-function.html"
published: "2026-11-24T07:51:00.000Z"
author: "Cory Watson"
---

November 24, 2026

# Groove: A Radio Station as a Pure Function

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

* * *

[Kapell](https://kapell.fm), 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”:

```go
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:

```go
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:

```go
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:

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:

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](https://musicbrainz.org). Maybe go add a few. They’ll show up tomorrow. :)
