Ch.53: Shazam System Design: Find the Song in the Noise
Outline
- 0:00 Find the recording in the noise
- 0:46 The complete recognition map
- 1:33 Requirements and exercise assumptions
- 2:14 Why a file hash fails
- 3:00 Build a peak-pair key
- 3:49 Keep surviving pairs repeatable
- 4:31 Candidates and compatible extraction versions
- 5:22 Aligned evidence beats scattered hits
- 6:19 Acceptance rules and shared losses
- 7:24 The index storage budget
- 8:10 Batch the keys by partition
- 9:01 Bound a common key's work
- 9:47 The last reply changes the leader
- 10:30 Keep reference and query versions compatible
- 10:59 Test the promise and the whole deadline
- 12:03 A signature still reveals listening history
- 12:27 Run the request through the complete map
- 13:07 Let uncertainty stay uncertain
Transcript
0:00 Imagine a song comes on in a restaurant. You know it, but can't place the title. You hold up your phone and ask Shazam, the app that identifies the recording playing around you. And the microphone gets the conversations and clattering plates too. I'd rather keep listening than get a confident wrong title because somebody dropped a fork. We're designing the recognition service behind that button: make noisy sound searchable, find convincing matching evidence, and return an answer under a deadline.
0:28 Good. Because “put the songs in a database” leaves me wondering what the phone could possibly use as its lookup key. Yeah, let's build that key and follow it through the index. The response should admit when it needs more sound instead of guessing a title. Now put that recognition request on the complete map, with two paths. Reference recordings become a searchable index along the top. Our restaurant clip crosses the lower path to lookup, evidence checking and song details. So the expensive preparation happens before somebody reaches for their phone.
1:03 What are we keeping from each reference recording? Compact sound features and where they occurred. We'll use the peak-pair idea in Avery Wang's published Shazam paper, then design our own backend around it. Right, those are public pieces in Apple's ShazamKit docs too: compact signatures, reference recordings and where a match starts. The source links are in the description. So we can borrow the matching idea without pretending we know their server layout. We'll follow the clip through ours, then return to this map.
1:33 Before choosing machinery on that map, our functional requirements start with the person holding the phone: identify a known recording, return where the clip belongs, and distinguish weak evidence from a failed search. The phone records 6 seconds. Aim for an answer within 1 second of finishing capture, at the 95th percentile. Our non-functional requirements constrain speed, scale and match quality: 10 million recordings, 2000 requests per second, bounded work and few wrong matches. They're exercise assumptions. So 95% must meet that whole deadline, including network time. Timeouts count as misses.
2:09 We're identifying the catalog recording; humming or a cover performance needs its own recognition promise. The catalog boundary still leaves your lookup-key problem. The microphone hears a different waveform from the studio file, even when they're the same recording. My first thought was a file hash. But the microphone has changed the bytes before our backend even sees them. What survives that? Start with a spectrogram: a picture showing sound frequencies over time. Keep peaks stronger than their nearby neighbors, like landmarks on that picture.
2:39 We discard most of the detail and hope enough of those landmarks survive. So a plate crashing might add a landmark, while quieter parts of the music disappear. We need enough of the original pattern to survive. Exactly. Wang's team described choosing peaks after testing features against noisy phone capture. The useful representation came from the damage it had to tolerate. A single surviving peak could belong to plenty of recordings. Let's follow two peaks, one low and one high, separated by a half-second interval.
3:08 Keep their two frequencies and that time gap. The clip could begin well inside the recording. Why preserve the gap rather than simply matching the original timestamps? The distance between corresponding peaks can still match. We make a feature key from that little relationship, then retain the first peak's time separately. Ah, like recognizing a short rhythm even after someone starts counting later. The spacing survives the shifted starting point, although noise may destroy some pairs. Yes. A peak can end one pair and start another.
3:40 More pairs give us more chances to retain evidence, and more work to store and search. We haven't made a noise-proof barcode. Then how does a damaged pair ever produce exactly the same lookup key? For our extractor, group frequencies into fixed ranges and round gaps to the nearest 10th of a second, identically on both paths. Suppose the same pair survives selection, with its frequencies in those ranges. Gaps just below and just above half a second can both round to half a second, giving the same key. Ah, like nearby measurements sharing a ruler mark.
4:15 The fork can add a stray peak while that surviving pair still gives the index a key it knows. Yes. A pair using a lost peak fails. A peak moved into another range can break its key too. Recognition depends on enough repeatable pairs surviving. Those feature keys let us build the index before recognition requests arrive. Each key points to entries saying which recording contains it and the reference time where it occurs. I'm getting A at 40.5 seconds, and B at 4.5 seconds for our pair. So which title does the phone show?
4:51 Neither yet. Those positions give us candidates to check. We need the remaining landmarks to support one placement of our clip within a recording. Our phone sends the keys and the time of each pair's first peak within the clip. How does the service know which extraction rules created them? The request includes the extraction version. Our coordinator routes it to an index built with compatible rules. Otherwise healthy services can ask different questions of the same sound and never find each other. With compatible lookup running, one worker is still searching.
5:25 Let's compare the positions we've received. Call the first peak of a pair its anchor. Recording A has four matching query anchors. Recording B has six. Which one would a simple hit counter choose? B. The bigger number wins. But do those hits agree on where the clip starts? Picture sliding a transparent strip of query landmarks along the recording. Our low peak, half a second into the clip, matches A at 40.5 seconds. The high peak, at 1 second, matches at 41. Oh, I see it. Both put the clip 40 seconds into A.
5:59 If the other two anchors agree too, we have four pieces supporting the same placement. B's six might each suggest a different placement. Exactly. In our toy trace, they do. Group hits by recording and time displacement. Four coherent anchors beat six scattered hits in this early view; four is an illustration, not an acceptance threshold. Once aligned hits identify a candidate, a repeated chorus can still complicate the decision. Two recordings can also share material. We still need a rule for accepting the result.
6:30 How many aligned anchors would make you comfortable returning the title? I'd tune the rule on one set of clips, then test it on separate noisy recordings and songs outside the catalog. We need strong aligned support and separation from the runner-up. Four from our example hasn't earned that rule. Oh, and copying the same feature shouldn't create new evidence. Count distinct query anchors instead of duplicated rows. Otherwise one surviving sound gets to vote repeatedly. Yes. Keep our original low-to-high pair.
7:00 Consider a later drum peak. Add a new pair from the low peak to it. And another new pair could connect the high peak to that same drum peak. Those two share a target, like two ropes tied to one peg. Cover that drum peak and both pairs disappear together. We'd test shared losses like that, and ask for more sound when candidates stay close. With that evidence policy, index size becomes a design choice. Let’s say we store an average 20 pairs per reference second. 10 million 4-minute recordings produce 48 billion entries.
7:36 Oh, wow. I didn't realize the total would get that big. I'd pictured a much smaller index. At 16 bytes per uncompressed row, three copies need about 2.3 decimal terabytes before other index overhead. That small pair has multiplied into a substantial storage budget. So the noisy clip wants more chances, while our index budget asks for fewer pairs. How do we choose the density? We'd measure recognition quality at different densities, including noisy clips. Fewer pairs save space only if enough of the useful relationships still reach us.
8:09 Now bring that restaurant clip into serving. Suppose its 6 seconds yield 120 usable keys. At 2000 queries per second, that's 240 thousand individual key lookups each second. I can already picture an implementation sending a separate remote request for every key. How would you organize those probes? Partition the index by feature key. Our coordinator groups the keys for each partition, keeping query times attached. With 16 logical partitions, we send batched lookup work and combine the returned recording positions.
8:41 Nice. One button press no longer turns into a tiny storm of remote requests. Each worker gets a batch, though it still has to examine the matching positions. Exactly. The keys can distribute evenly while the work doesn't. One key might return a handful of positions, and another a very long list. Next, follow that long list. Imagine the captured sound contains a feature shared across lots of recordings. Most returned positions won't help us name this song. So we can prefer keys shared by fewer recordings.
9:13 But what if this query still consumes its work budget before the evidence is settled? Then we can't turn the first pile of returned rows into a winner. Otherwise the budget decides which song we heard by stopping us halfway through... ...and calling that stopping point a conclusion. If our chosen search didn't finish, the attempt is unavailable. The microphone did its job. Our search didn't. Right. Choosing which features to search is a policy we can test. Losing the rest of a chosen search is unfinished work.
9:44 We must preserve which of those happened. Once we've bounded lookup work, completion remains a separate condition. 15 required partitions have replied; the last is still running. A leads the evidence we have. I can hear a product manager asking, can we show that title while the last reply comes in? Imagine that worker returns other keys from the same query anchors. Four add support for B at one placement, joining one earlier hit. What happens to A's lead? Oh. B now leads, five aligned anchors against A's four.
10:16 Clearing our measured rule still depends on sufficient evidence and a lead over alternatives. Exactly. The coordinator's checklist must be complete. If that reply misses its deadline, return unavailable. More sound won't repair that missing worker. Before trusting those completed replies, check the key itself. Suppose our phone still packs low, high, gap. A new builder stores high, low, gap. Healthy lookup workers can miss the same sound. Even our surviving pair can vanish from lookup. How can old phones keep finding their recordings?
10:48 Route each version to matching files. A new catalog serves only when its required files are ready. If its build fails, the previous compatible catalog keeps answering those phones. Before trusting a compatible build, look at Wang's 2003 test with 10,000 tracks. They digitally mixed pub noise into clips, then applied old phone-call compression. At equal music and noise power, 10-second clips were recognized about half the time. Half. So extra listening isn't a guarantee. Our 6-second capture needs its own tests.
11:22 For example, a quiet passage can lose the peaks we're expecting from the chorus. Exactly. We're hearing the chorus in our heads; the phone didn't record it. Use separate test excerpts, including recordings we never indexed. Count wrong matches, misses and withheld titles. Yeah. Start one clock when the phone finishes capture, and stop it at the reply. Include final feature work, network time and waiting for required lookup workers. Use those complete times for our latency target, alongside how many index entries each request examined.
11:52 Right. Count completed searches that withhold a title separately from unavailable attempts. Faster replies shouldn't conceal more unfinished searches, or quietly reduce how often we identify the music. With recognition working, saved history becomes a privacy choice. Our restaurant match still reveals what was playing after we delete the clip. Apple describes compact, one-way matching data rather than a playable recording. I wouldn't turn that into a promise that a listening event is private, though. Right. Ask for microphone permission, minimize retained audio, and save a result only if the user chooses.
12:26 Now run our restaurant request through the same complete map. Its keys, query times and extraction version reach the coordinator. Reference positions are already indexed; lookups run in batches. A's early lead was four aligned anchors at 40 seconds. The final partition moved B ahead, five at 10 seconds. We needed the whole search to see that. Yes. A complete search can return a match or request more audio. A missing required reply returns unavailable. Those are different next actions for the phone.
12:57 If the rule accepts B, the reply includes its title and the 10-second position. The metadata service supplies that name, but can't tell us what the microphone heard. So I'd trust the button more if it occasionally asked for another few seconds than if it confidently named the wrong song. Same. Thanks for listening to Learning Podcasts.